如何将React JS index.js文件与index.html联系以获取id引用?

Mr_*_*ect 65 reactjs

我最近开始反应.

我的index.html包含

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
    <title>React App</title>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

index.js包含

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';

ReactDOM.render(
  <App />,
  document.getElementById('root')
);
Run Code Online (Sandbox Code Playgroud)

我的疑问是我没有index.js在任何脚本标签中提及index.html.但它是如何引用rootdiv元素的index.html呢?我想知道它工作正常.请解释一下.

我已经运行这些命令来创建应用程序

npm install -g create-react-app
create-react-app hello-world
cd hello-world
npm start
Run Code Online (Sandbox Code Playgroud)

Aft*_*han 111

Create-React-App 是非常有趣的设置.

我从package.jsonnpm脚本开始挖掘start

"开始":"react-scripts启动"

这将我带到他们的二进制文件react-scripts,node_modules/.bin
我将在这里发布相关的东西.

switch (script) {
  case 'build':
  case 'eject':
  case 'start':
  case 'test': {
    const result = spawn.sync(
      'node',
      [require.resolve('../scripts/' + script)].concat(args),
      { stdio: 'inherit' }
    );
Run Code Online (Sandbox Code Playgroud)

所以这告诉我他们正在寻找../scripts/文件夹内的脚本.

所以我转到react-scripts npm模块(node_modules/react-scripts)并打开node_modules/react-scripts/scripts/start.js文件,因为我正在做npm start.

现在我在这里找到了我正在寻找的webpack配置.
他们特指node_modules/react-scripts/config/webpack.config.dev.js.我会在这里发布相关内容.

entry: [
  // Finally, this is your app's code:
  paths.appIndexJs,
],
plugins: [
  // Generates an `index.html` file with the <script> injected.
  new HtmlWebpackPlugin({
    inject: true,
    template: paths.appHtml,
  }),
Run Code Online (Sandbox Code Playgroud)

所以引用的paths.appIndexJs文件是webpack配置中的条目文件.

他们正在使用HtmlWebpackPlugin在路径上加载html paths.appHtml.

拼图的最后一部分是将其链接到您发布的文件.发布相关内容paths.js

const appDirectory = fs.realpathSync(process.cwd());
const resolveApp = relativePath => path.resolve(appDirectory, relativePath);
module.exports = {
  ...
  appHtml: resolveApp('public/index.html'),
  appIndexJs: resolveApp('src/index.js'),
  ...
}
Run Code Online (Sandbox Code Playgroud)

所以在你的应用程序目录中,
appHtml是文件public/index.html
appIndexJs是文件src/index.js

你的两个文件有问题.
哇!这是一段相当艰难的旅程..:P

  • @AftabKhan 非常棒的答案!我非常感谢您向我们展示如何挖掘相关信息的方式!我一生中大部分时间都是后端人员,所以作为 JS/React 的新手,这就像天赐之物!谢谢! (2认同)