我是React的新手,我使用这个解释来构建一个基本的React应用程序:https://facebook.github.io/react/docs/installation.html
我开了一个新项目:
npm install -g create-react-app
create-react-app my-app
cd my-app
npm start
index.html文件位于hello-world / public中,以下是它的内容:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="theme-color" content="#000000">
<link rel="manifest" href="%PUBLIC_URL%/manifest.json">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
<title>React App</title>
</head>
<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div id="root">
</div>
</body>
</html>
但是,所有“React stuff”都放在hello-world \ src目录中 . 它看起来'hello-world \ src \ index.js'激活组件 .
我不明白的是index.html如何“读取”index.js的内容 . index.html没有导致index.js的html标记 .
我可以通过“npm start”启动这个应用程序 . 此命令的作用是引发在localhost:3000上运行的服务器 . 如何在不使用“npm start”的情况下查看应用程序?
2 回答
您只需要将所有代码捆绑在单个js文件中,为此,您可以使用webpack等工具 .
假设你有这样的项目结构: -
You need to add webpack.config.js : - 在您的根目录中,它将包含一些特定的配置以捆绑您的代码 .
webpack.config.js
看起来很相似: -Add a .babelrc file in your root directory:-
之后在根目录下运行命令: -
webpack
将创建一个包含bundle.min.js的dist文件夹 .Edits in your index.html : -
package.json
我知道这是相当大的,但在我看来,你必须经历这个过程,同时开发反应,所以最好在开始时通过这个 .
如果我们查看在浏览器上呈现的DOM(对于
npm start
),它会注入以下脚本节点:同样,对于生成版本(
npm run build
),构建文件夹下有一个index.html文件,它注入了类似的script
节点 .我案例中的例子:
因此,我倾向于认为脚本节点注入是由
react-scripts
库或其中一个依赖项完成的 .此外,要在没有Web服务器的情况下运行应用程序,以下应该可以:
在package.json中定义
"homepage": "./"
运行 生产环境 构建(
npm run build
)直接从
build
文件夹启动index.html
.Edited:
./node_modules/react-scripts/config
下的配置似乎负责<script>
节点注入 .示例:
./node_modules/react-scripts/config/webpack.config.dev.js
有,