将webpack分离的css文件注入html头

时间:2018-06-06 10:28:32

标签: webpack-4 html-webpack-plugin extract-text-plugin extracttextwebpackplugin mini-css-extract-plugin

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

当前的网络包设置:

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选项中都没有找到这样的选项。你知道如何做到这一点的好方法吗?

0 个答案:

没有答案