4

在我当前的设置中,webpack 将在 .js 文件中导入的 css 捆绑到单独的样式文件中,并在 .js 包完成加载后加载它。因为 .js 包是在 html(/body 标记的结尾)之后加载的,所以页面最初没有样式。

当前的 webpack 设置:

module.exports = {
  entry: './client/index.js',
  plugins: [
    new HtmlWebpackPlugin({
      template: 'client/index.html',
      minify: true,
    }),
    new CleanWebpackPlugin(['dist']),
  ],
  output: {
    filename: '[name].bundle.js',
    path: path.resolve(__dirname, 'dist'),
    publicPath: '/',
  },
  module: {
    rules: [{
        use: 'babel-loader',
        test: /\.js$/,
        exclude: /node_modules/,
      },
      {
        use: ['style-loader', 'css-loader'],
        test: /\.css$/,
      },
      {
        test: /\.scss$/,
        use: [{
            loader: 'style-loader',
          },
          {
            loader: 'css-loader',
            options: {
              sourceMap: true,
            },
          },
          {
            loader: 'sass-loader',
            options: {
              sourceMap: true,
            },
          },
        ],
      },
      {
        test: /\.(png|svg|jpg|gif)$/,
        use: ['file-loader'],
      },
    ],
  },
};

module.exports = merge(common, {
  mode: 'production',
  optimization: {
    minimizer: [
      new UglifyJsPlugin({
        cache: true,
        parallel: true,
        sourceMap: true, // set to true if you want JS source maps
      }),
      new OptimizeCSSAssetsPlugin({}),
    ],
    splitChunks: {
      cacheGroups: {
        styles: {
          name: 'styles',
          test: /\.css$/,
          chunks: 'all',
          enforce: true,
        }
      }
    }
  },
  plugins: [
    new UglifyJsPlugin({
      cache: true,
      parallel: true,
    }),
    new MiniCssExtractPlugin({
      filename: "[name].[contenthash].css",
      chunkFilename: "[id].[contenthash].css",
    }),
  ],
  module: {
    rules: [{
      test: /\.css$/,
      use: [
        MiniCssExtractPlugin.loader,
        "css-loader",
      ]
    }]
  },
});

理想情况下,我希望在 html 标头中添加一个单独的标签,其中将加载捆绑的 css 文件。我在 HtmlWebpackPlugin 选项和 MiniCssExtractPlugin 选项中都没有找到这样的选项。你知道如何做到这一点的好方法吗?

4

0 回答 0