webpack4.X index.js加载了两次

按照webpack官网实践:

clipboard.png
index.html

<!doctype html>
<html>
<head>
    <title>webpack实践</title>
    <meta charset="utf-8">
</head>
<body>
<script src="main.js"></script>
</body>
</html>

src/index.js

import _ from 'lodash';

function component() {
    var element = document.createElement('div');

    // Lodash(目前通过一个 script 脚本引入)对于执行这一行是必需的
    element.innerHTML = _.join(['Hello', 'webpack'], ' ');

    return element;
}

document.body.appendChild(component());

webpack.config.js

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

module.exports = {
    entry: './src/index.js',
    devServer:{
        contentBase:'./dist'
    },
    plugins: [
        // new htmlWebpackPlugin(),
        new htmlWebpackPlugin({
            filename:"index.html",
            template:"index.html"
        })
    ],
    output: {
        filename: 'main.js',
        path: path.resolve(__dirname, 'dist')
    }
};

package.json

{
  "name": "webpack-template",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "webpack-dev-server --open"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/DevilLittle/webpack-template.git"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "html-webpack-plugin": "^3.2.0",
    "webpack": "^4.16.3",
    "webpack-cli": "^3.1.0",
    "webpack-dev-server": "^3.1.5"
  },
  "dependencies": {
    "lodash": "^4.17.10"
  }
}

然后神奇的事情就发生了:

clipboard.png

clipboard.png

clipboard.png
问:为什么执行了两次?求大神告知

阅读 3.7k
1 个回答

<script src="main.js"></script> 既然你选择了htmlWebpackPlugin 这一句就是多余的了,
这样导致了你引了main.js两次,当然会有两次输出了

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题