如何反应 JS index.JS 文件联系 index.html 获取 id 引用?

我最近开始反应。

我的 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>

Index.js包含

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


ReactDOM.render(
<App />,
document.getElementById('root')
);

我怀疑我没有在 index.html的任何脚本标签中提到 index.js。但是它是如何引用 index.html中的 root div 元素的呢?我想知道,因为它是工作良好。请解释一下。

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

npm install -g create-react-app
create-react-app hello-world
cd hello-world
npm start
127151 次浏览

Create-React-App的设置非常有趣。

我开始深入研究 package.json npm 脚本 start

“开始”: “反应脚本开始”

这就把我带到了 node_modules/.bin下的二进制 react-scripts
我会把相关的东西贴在这里。

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

这告诉我他们正在 ../scripts/文件夹中寻找脚本。

因此,我转到 response-script 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,
}),

因此,paths.appIndexJs引用的文件是 webpack 配置中的条目文件。

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

拼图的最后一部分是把这个和你发布的文件联系起来。 发布来自 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'),
...
}

在应用程序目录中,
AppHtml 是文件 public/index.html
AppIndexJs 是文件 src/index.js

你的两份文件有问题。
哇! 这是一个相当长的旅程. . : P


更新1 -As of react-scripts@3.x

node_modules/.bin下的 react-scripts二进制文件改变了逻辑,如下所示。

if (['build', 'eject', 'start', 'test'].includes(script)) {
const result = spawn.sync(
'node',
nodeArgs
.concat(require.resolve('../scripts/' + script))
.concat(args.slice(scriptIndex + 1)),
{ stdio: 'inherit' }
);

针对 dev & prod 的 webpack 配置已经合并为一个。
const configFactory = require('../config/webpack.config');

HTMLWebpackPlugin 配置看起来像这样——这是因为他们必须有条件地在此之上添加生产配置

plugins: [
// Generates an `index.html` file with the <script> injected.
new HtmlWebpackPlugin(
Object.assign(
{},
{
inject: true,
template: paths.appHtml,
},

路径文件代码有一些更新

module.exports = {
...
appHtml: resolveApp('public/index.html'),
appIndexJs: resolveModule(resolveApp, 'src/index'),
...
};