我的所有代码在使用Webpack编译时都会运行两次

All my code runs twice when compiled by Webpack

本文关键字:运行 两次 编译 代码 Webpack 我的      更新时间:2023-09-26

当我使用webpack-dev-server使用webpack构建js捆绑包时,我的代码每次运行两次。不知道如何修复。

开发者工具控制台屏幕截图

我的webpack配置:

var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');
module.exports = {
  devtool: 'cheap-eval-sourcemap',
  entry: [
    'webpack-dev-server/client?http://localhost:8080',
    'webpack/hot/dev-server',
    path.join(__dirname, '../src/main')
  ],
  output: {
    path: path.join(__dirname, '../dist'),
    filename: 'bundle.js'
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.optimize.OccurenceOrderPlugin(),
    new HtmlWebpackPlugin({
      template: path.join(__dirname, '../src/index.html')
    }),
    new CopyWebpackPlugin([
      {
        from: path.join(__dirname, '../assets'),
        to: path.join(__dirname, '../dist/assets')
      }
    ])
  ],
  devServer: {
    contentBase: path.join(__dirname, '../dist'),
    outputPath: '/lol',
    hot: true
  },
  module: {
    loaders: [
      {
        test: /'.js$/,
        loaders: ['babel-loader'],
        include: path.join(__dirname, '../src')
      }
    ]
  }
};

在模板文件中,您可能手动添加了一个加载捆绑包的程序。

如果你没有

inject: false 

中的选项

new HtmlWebpackPlugin({
    template: path.join(__dirname, '../src/index.html')
}),

将再次添加捆绑包。

对@Emil Perhinschi和@ggloren早期的回复进行了扩展。。。

或者,如果您的../src/index.html文件不依赖于除<script src="bundle.js"></script>之外的任何脚本,只需将后者从index.html中删除即可

根据https://github.com/jantimon/html-webpack-plugin,inject的默认值为true,并且。。。

当传递true'body'时,所有javascript资源将放置在主体元件的底部。

因此,bundle.js的两个实例是:

  1. 您(大概)编码的<script src="bundle.js"></script>,以及
  2. HtmlWebpackPlugin的注入"在body元素的底部"