Home > Mobile >  Body elements disappearing as I run webpack
Body elements disappearing as I run webpack

Time:07-30

I have tried looking for this problem on the internet and couldn't find anything related. I am trying to build a small project where the body of my HTML will only have one div with id="content" and I have to append the rest of the elements one-by-one to this div. Now I created an element h1 and appended it to the aforementioned div and then hit the npm run build command in the terminal. As soon as webpack emits a bundle, the div id="content" disappears from the body. I am attaching the screenshot of the issue. This is how the index.html look like before I run webpack: Index.html file index.js stays the same after running webpack: index.js file This is how index.html looks like after I run the command npm run build or npm run watch: index.html after running webpack Here is my webpack configuration:

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

module.exports ={
    entry: {
        index:{
            import: './src/index.js'
        }
    },
    mode: "development",
    devtool: "inline-source-map",
    plugins : [
        new HtmlWebpackPlugin({
            title: 'Resturant Page',
        })
    ],
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].bundle.js'
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
            },
            {
                test: /\.css$/,
                use: ['style-loader', 'css-loader']
            },
            {
                test: /\.png|jpg|jpeg$/,
                type: 'asset/resource',
            },
            {
                test: /\.svg$/,
                type: 'asset/resource',
            },
            {
                test: /\.woff|wof$/,
                type: 'asset/resource',
            }
        ]
    }
}

CodePudding user response:

Try replacing the HtmlWebpackPlugin lines with following:

  plugins: [
    new HtmlWebpackPlugin({
      template: 'src/index.html',
      inject: false, // prevents adding script tag to html so you may do it manually
    })
  ]

I suggest keeping index.html in src folder, Webpack will copy the output to dist for you.

Also, instead of inject: false it is much better to let it be added automatically for you.

  • Related