使用 webpack 时如何移动 "index.html"?

How can I move "index.html" when using webpack?

一般情况下,"index.html"什么时候使用webpack加载?

我想将 "index.html" 移动到 build/.

我在 npm start 使用 webpack 的数据流方面遇到了麻烦。

在package.json中,"start"定义为:

"node ./node_modules/webpack-dev-server/bin/webpack-dev-server.js".

但是,我找不到它从哪里跳转"webpack-dev-server.js"。

我在里面找到了两个关于"index.html"的描述如下:

     .boolean("history-api-fallback").describe("history-api-fallback", "Fallback to /index.html for Single Page Applications.")

    console.log("404s will fallback to %s", options.historyApiFallback.index || "/index.html");

当我尝试将 "index.html" 移动到 build/ 中时,浏览器返回 "Cannot Get error"。

"index.html" 和 webpack.config.js 现在在同一文件夹中。

    ./  index.html  package.json  src/    test/
    ../  build/  node_modules/  public/   style/             
    webpack.config.js

一种方法是更新脚本(在 package.json 中),以便将 index.html 复制到目标文件夹:

"scripts": {
  "start": "node node_modules/.bin/webpack-dev-server --content-base src",
  "build": "node node_modules/.bin/webpack && cp src/index.html build/index.html"
}

npm run build 现在也应该将 src/index.html 复制到 build/index.html

我不是 webpack 专家,但我遇到了同样的问题,并且能够使用插件解决它:html-webpack-plugin

首先安装它:npm install html-webpack-plugin --save-dev

然后编辑您的 webpack.config.js

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

module.exports = {
    //Your config here (entry, module, resolve, etc.)
    devServer: {
        contentBase: './build' //Or any other path you build into
    },
    plugins: [
        //other plugins if any
        new HtmlWebpackPlugin({
            template: './index.template.html', //your template file
            filename: 'index.html',
            inject: 'body'
        })
    ]
};

这会将您的 index.template.html 复制到 ./build/index.html 并从那里提供文件。
它还会在 <body> 标签底部注入所有资源。
您当然可以进一步自定义此设置以满足您的需要,只需 refer to the plugin docs