d51*_*512 7 webpack webpack-dev-server html-webpack-plugin
我在 React 项目上使用 Webpack,它似乎以一种我不理解的奇怪方式HtmlWebpackPlugin影响了webpack 开发服务器。
它似乎允许我浏览到index.html该文件在代码库中的任何位置,这是单独使用开发服务器无法实现的。
假设我有以下目录结构:
myproj/
|- package.json
|- webpack.config.js
|- src/
|- index.html
|- index.jsx
Run Code Online (Sandbox Code Playgroud)
和一个webpack.config.js看起来像这样的文件:
const path = require('path');
module.exports = {
entry: './src/index.jsx',
devServer: {
contentBase: __dirname
}
};
Run Code Online (Sandbox Code Playgroud)
然后我跑webpack-dev-server --mode=development。由于我已devServer.contentBase设置为当前目录 ( myproj) 并且index.html文件在里面myproj/src,因此我必须浏览http://localhost:8080/src/index.html以查看我的 Web 应用程序。如果我尝试浏览,http://localhost:8080/index.html则会得到 404。这对我来说很有意义。
然后我添加了HtmlWebpackPlugin,里面没有改变任何东西webpack.config.js:
const HtmlWebpackPlugin = require('html-webpack-plugin');
....
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html'
})
]
Run Code Online (Sandbox Code Playgroud)
现在突然间我可以浏览到 http://localhost:8080/index.html 就好了。事实上,我可以点击http://localhost:8080/index.html或http://localhost:8080/src/index.html。
那是怎么回事?做了HtmlWebpackPlugin什么使这成为可能?
好吧,我想我想通了。
添加后,HtmlWebpackPlugin您应该从index.html以下位置删除此行:
<script type="text/javascript" src="main.bundle.js"></script>
Run Code Online (Sandbox Code Playgroud)
并且只浏览到http://localhost:8080/index.html.
添加 in 后HtmlWebpackPlugin,它会将您的index.html文件合并到一个<script>指向您的 webpack 包的标签中。它从http://localhost:8080. 它这样做即使index.html已经包含对包的引用,它也会这样做。
该插件实际上并没有被index.html合并版本覆盖。因此,浏览至http://localhost:8080/src/index.html仅向您显示该文件在磁盘上的状态。
因此,如果您的src/index.html文件在添加之前如下所示HtmlWebpackPlugin:
<body>
<div id="app">it worked</div>
<script type="text/javascript" src="main.bundle.js"></script>
</body>
Run Code Online (Sandbox Code Playgroud)
然后在添加后HtmlWebpackPlugin,浏览到http://localhost:8080为您提供此合并版本:
<body>
<div id="app">it worked</div>
<script type="text/javascript" src="main.bundle.js"></script>
<script type="text/javascript" src="main.bundle.js"></script>
</body>
Run Code Online (Sandbox Code Playgroud)
所以现在您将有两个对包的引用,一个是您在文件中添加的,另一个是HtmlWebpackPlugin添加的。
浏览到http://localhost:8080/src为您提供磁盘上的内容src/index.html:
<body>
<div id="app">it worked</div>
<script type="text/javascript" src="main.bundle.js"></script>
</body>
Run Code Online (Sandbox Code Playgroud)
但是,由于他使用的全部目的HtmlWebpackPlugin是让它为您插入包引用,这意味着您应该<script>从src/index.html. 这反过来意味着浏览到src/index.html将不再起作用,因为您不再有对您的包的引用!
您现在依赖于让为您HtmlWepbackPlugin插入<script>标签,这意味着您现在必须浏览http://localhost:8080/index.html以获取它生成的版本。
网络包。是。疯狂的。
| 归档时间: |
|
| 查看次数: |
7162 次 |
| 最近记录: |