<div id="root"></div> 未在 webpack 构建中传输

Jef*_*ler 2 webpack webpack-dev-server

我正在使用 Webpack 3.8.1 和 webpack-dev-server 2.9.2。这是我在 React 中编写的一个项目。下面是我的 webpack.config 文件。每次运行构建命令时,都不会传输到 dist 目录中的 index.html 文件。当我进行生产构建时也会发生这种情况。我可以将该行写入 index.html 文件,但每次重建时都会删除该行。有任何想法吗?

const path = require('path');
const webpack = require('webpack');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');


module.exports = {
  devtool: 'cheap-module-eval-source-map',
  devServer: {
    contentBase: './dist',
    hot: true
  },
  entry: {
    app: './src/index.js',
    vendor: ['react']
  },
  plugins: [
    new CleanWebpackPlugin('dist'),
    new webpack.NamedModulesPlugin(),
    new HtmlWebpackPlugin({
      title: 'Production'
    }),
    new ExtractTextPlugin({
      filename: 'styles.css'
    }),
    new webpack.HotModuleReplacementPlugin({
      multiStep: true
    })
  ],
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].[hash].js',
    sourceMapFilename: 'bundle.js.map'
    },

  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: [
          'babel-loader'
        ]
      },
      {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use:'css-loader'
        })
      },
      { test: /\.(png|woff|woff2|eot|ttf|svg)$/,
        loader: 'url-loader?limit=100000'
      },
      { test: /\.eot(\?v=\d+.\d+.\d+)?$/,
        loader: 'file-loader'
      },
      { test: /\.scss$/,
        loaders: ['style-loader', 'css-loader', 'sass-loader']
      },
      {
        test: /\.(jpg|jpeg|gif|png)$/,
        exclude: /node_modules/,
        loader:'file-loader?name=img/[name].[ext]&context=./app/images'
      },
      {
        test: /\.(ico)$/,
        exclude: /node_modules/,
        loader:'file-loader?name=[name].[ext]&context=./app/images'
      }
    ]
  },

  resolve: {
    extensions: ['*', '.js', '.jsx']
  }
};
Run Code Online (Sandbox Code Playgroud)

Vis*_*rma 9

这是因为 html-webpack-plugin。你没有指定所以你看不到它。快速浏览 html-webpack-plugin doc 后,我建议您template.html在构建的 index.html 文件中创建一个包含所需内容的文件。

并将配置的插件部分更改为,

new HtmlWebpackPlugin({
   title: 'Production'
   template: 'template.html'
}),
Run Code Online (Sandbox Code Playgroud)

这样你就可以在你的模板文件中填写你想要的所有 DOM,你的构建index.html将拥有它。

并在您template.html刚使用时读取配置变量(标题)

<title><%= htmlWebpackPlugin.options.title %></title>