Webpack 配置未在 public 文件夹中生成 index.html

Webpack config not generating index.html in public folder

我的 webpack 配置有点问题,由于某种原因它没有在我的 /public 文件夹中创建 index.html 文件。

请参阅下面webpack.config.js:

const path = require("path");
const ExtractTextPlugin = require("extract-text-webpack-plugin");

let DEBUG;

if (process.env.NODE_ENV === "production") {
  DEBUG = false;
} else {
  DEBUG = true; // process.env.NODE_ENV === "development"
}
//const DEBUG = true; // process.env.NODE_ENV === "development"

module.exports = {
  context: path.resolve(__dirname, "src"),
  entry: "./index.js",
  output: {
    path: path.resolve(__dirname, "public"),
    filename: DEBUG ? "bundle.js" : "bundle.min.js"
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        loader: "babel-loader",
        exclude: /node_modules/
      },
      {
        test: /\.jsx$/,
        loader: "babel-loader",
        exclude: /node_modules/,
        options: {
          presets: ["react", "es2015"]
        }
      },
      {
        test: /\.scss$/,
        loaders: DEBUG
          ? [
              "style-loader",
              "css-loader?sourceMap",
              "sass-loader?sourceMap",
              "postcss-loader"
            ]
          : ExtractTextPlugin.extract("css-loader!sass-loader!postcss-loader")
      },
      {
        test: /\.(ttf|eot|svg)(\?[\s\S]+)?$/,
        use: "file-loader?name=images/[name].[ext]"
      }
    ]
  },
  devServer: {
    historyApiFallback: true,
    hot: true,
  },
  plugins: [
    new ExtractTextPlugin("style.css", {
      allChunks: true
    })
  ]
};

我的根目录中有一个,当我 运行 在开发模式下时一切正常。构建脚本是 "build": "NODE_ENV='production' webpack -p"。

谢谢

您需要 HTML Webpack 插件。该插件为您创建 html 文件并将 webpacks entry prop 中定义的每个条目添加到您的 html。 不要忘记安装它。

$ npm install html-webpack-plugin --save-dev

然后在你的 webpack 配置中:

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

...

plugins: [
    new ExtractTextPlugin("style.css", {
      allChunks: true
    }),
    new HtmlWebpackPlugin()
  ]

有关详细信息,请参见此处: https://github.com/jantimon/html-webpack-plugin