Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

WebPack: problem when compiling JS files in html

im having a problem while working with webpack. I’m using a JS file to call an API, but this API should be called only in escudos.html, but when I do the webpack build, the JS file calls the API int both (index.html, escudos.html). I only want that the ./src/js/teams.js call API when im in the escudos.html, not in in both (index.html, escudos.html) html.

const path = require(‘path’);
const HtmlWebpackPlugin = require(‘html-webpack-plugin’)

module.exports = {

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

entry: {
    index: './src/js/index.js',
    teams: './src/js/teams.js',
},
output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'js/[name].bundle.js',
},
plugins: [
    new HtmlWebpackPlugin({
        filename: 'index.html',
        template: './src/index.html',
    }),
    new HtmlWebpackPlugin({
        filename: 'escudos.html',
        template: './src/escudos.html',
    })
],
devServer: {
    static: './dist',
},
module: {
    rules: [
        {
            test: /\.js$/,
            exclude: /node_modules/,
            use: { loader: 'babel-loader' },
        }
    ],
},

}

for some reason my webpacked file index.html has the teams.js too

>Solution :

The problem (and the solution) is in HtmlWebpackPlugin. HtmlWebpackPlugin injects all entries in every page by default.
There exists three solutions I can think of:

  1. inject: false: This disables auto injection of <script> tags into the templete. You have to manually write <script>tag(s) with the proper src. (Psss: don’t)
  2. chunks: specifiy which entries you want to be included for this template. E.G: (Solves the OP problem, what you will need/use in most cases)
    new HtmlWebpackPlugin({
        template: "./src/index.html",
        chunks: ["index"]
    }),
    new HtmlWebpackPlugin({
        template: "./src/escudos.html",
        chunks: ["teams"]
    })
    
  3. exclude: inject all entries except the ones specified in this array. E.G
    new HtmlWebpackPlugin({
        template: "./src/test.html",
        exclude: ["index"]
    })
    
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading