鍍金池/ 問(wèn)答/HTML/ webpack4.X index.js加載了兩次

webpack4.X index.js加載了兩次

按照webpack官網(wǎng)實(shí)踐:

clipboard.png
index.html

<!doctype html>
<html>
<head>
    <title>webpack實(shí)踐</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(目前通過(guò)一個(gè) script 腳本引入)對(duì)于執(zhí)行這一行是必需的
    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"
  }
}

然后神奇的事情就發(fā)生了:

clipboard.png

clipboard.png

clipboard.png
問(wèn):為什么執(zhí)行了兩次?求大神告知

回答
編輯回答
小眼睛

<script src="main.js"></script> 既然你選擇了htmlWebpackPlugin 這一句就是多余的了,
這樣導(dǎo)致了你引了main.js兩次,當(dāng)然會(huì)有兩次輸出了

2018年3月31日 03:29