简体   繁体   中英

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.

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.

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. 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.

You can however use the HtmlWebpackPlugin to have the bundle reference added automatically. It's added to the plugins section of your webpack.config.js file like this:

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...

Source: This code was taken from my webpack project template on github . 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.

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.

hence it is important to add that in your webpack else your code will never run.

Okay, my bad guys. HTMLWebpackPlugin wasn't configured correctly.

Thanks for your help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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