简体   繁体   English

为什么在运行webpack-dev-server时必须将bundle.js脚本放入html中

[英]Why do I have to put bundle.js script in html when running webpack-dev-server

I'm running webpack-dev-server from my package.json script. 我正在从我的package.json脚本运行webpack-dev-server。

When I don't put tag in my index.html, bundle is not being loaded even when webpack-dev-server should put it there automatically. 当我不在我的index.html中放置标记时,即使webpack-dev-server应该自动将其放置在其中,也不会加载捆绑软件。

My code looks like this: 我的代码如下所示:

<body>
  <div id="my-app"></div>
  <script src="bundle.js"></script>
  <script type="text/javascript" src="app.bundle.aa2801db8d757c2f2d78.js"></script>
</body>

I put the first bundle there when running webpack-dev-server and second bundle got generated by HTMLWebpackPlugin when I built project for production. 在运行webpack-dev-server时,我将第一个捆绑软件放在那里,而在构建生产项目时,第二个捆绑软件是由HTMLWebpackPlugin生成的。 Basically I want to get rid of the first bundle in my production code. 基本上,我想摆脱生产代码中的第一个捆绑软件。

Thanks for any suggestions. 感谢您的任何建议。

You need to reference your javascript bundle from your HTML, because it is not inserted there automatically. 您需要从HTML中引用JavaScript包,因为它不会自动插入其中。

You can however use the HtmlWebpackPlugin to have the bundle reference added automatically. 但是,您可以使用HtmlWebpackPlugin来自动添加捆绑软件参考。 It's added to the plugins section of your webpack.config.js file like this: 它将添加到webpack.config.js文件的插件部分,如下所示:

const webpack = require("webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
    entry: "./source/index.js",
    module: {
        // keep the rules you've already got
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: "./index.html"
        }),
        // ... keep all your other plugins here...
    ]
}

Make sure the value of template points to your HTML file... 确保模板的值指向您的HTML文件...

Source: This code was taken from my webpack project template on github . 来源:该代码取自我在github上的webpack项目模板 You can see the full configuration files and more explanatory text there. 您可以在此处看到完整的配置文件和更多说明性文本。

so what i understand is you don't know the importance of bundle.Basically whenever you run your code it compiles everything(including all your components of application) in bundle.js. 所以我了解的是您不知道bundle的重要性。基本上,每当您运行代码时,它都会编译bundle.js中的所有内容(包括应用程序的所有组件)。

you can have a look at bundle.js once the webpack is compiled successfully.You will see that webpack compiles and resolves everything in that bundle only. 您可以在webpack成功编译后查看bundle.js。您将看到webpack仅编译和解析该bundle中的所有内容。

hence it is important to add that in your webpack else your code will never run. 因此,重要的是要在Webpack中添加代码,否则您的代码将永远无法运行。

Okay, my bad guys. 好吧,我的坏家伙。 HTMLWebpackPlugin wasn't configured correctly. HTMLWebpackPlugin配置不正确。

Thanks for your help. 谢谢你的帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM