首页 > 解决方案 > 如何使用 Webpack 和 React 预加载 css?

问题描述

我正在使用react和Webpack 5。运行一个灯塔报告后,我发现了一些需要预加载的css文件。我如何在 Webpack 中做到这一点?

webpack config:

const HtmlWebpackPlugin = require('html-webpack-plugin')
const path = require( 'path' );
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CopyPlugin = require('copy-webpack-plugin');

module.exports = {
   context: __dirname,
   entry: './src/index.js',
   output: {
      path: path.resolve( __dirname, 'build' ),
      filename: '[name].js',
      publicPath: '/',
      chunkFilename: '[id].[chunkhash].js'
   },
   optimization: {
      chunkIds: "named",
      splitChunks: {
         chunks: 'all',
      },
   },
   devServer: {
      historyApiFallback: true
   },
   module: {
      rules: [
         {
            test: /\.js$/,
            use: 'babel-loader',
         },
         {
            test: /\.(png|svg|jpg|jpeg|gif|ico)$/,
            exclude: /node_modules/,
            use: ['file-loader?name=[name].[ext]']
          },
          {
            test: /\.css$/,
            use: [
               MiniCssExtractPlugin.loader,
                'css-loader',
            ],
          },
        ]
   },
   plugins: [
      new HtmlWebpackPlugin({
        template: path.resolve( __dirname, 'public/index.html' ),
        filename: 'index.html',
        favicon: 'public/favicon.ico',
      }),
      new MiniCssExtractPlugin({
         filename: '[name].css',
         chunkFilename: '[name]-[id].css',
      }),
      new CopyPlugin({
         patterns: [
           { from: './src/serviceWorker.js', to: './serviceWorker.js' },
           { from: './public/offline.html', to: './offline.html' },
           { from: './public/manifest.json', to: './manifest.json' },
         ],
       }),
   ]
};

我尝试了Magic Comments(如下),但它没有预加载css。

import (
  /* webpackPrefetch: true */
  /* webpackPreload: true */
  './Article.css'
  );

我尝试了 PreloadWebpackPlugin,但我只能让它预加载react 项目中的所有css 文件,或者根本没有。

理想情况下,解决方案将只包括给定页面所需的内容......

任何前进的想法将不胜感激。谢谢!

标签: javascriptcssreactjswebpackpreload

解决方案


推荐阅读