javascript - 如何使用 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 文件,或者根本没有。
理想情况下,解决方案将只包括给定页面所需的内容......
任何前进的想法将不胜感激。谢谢!
解决方案
推荐阅读
- c# - 打破这个简单的“while”循环的正确位置在哪里?
- winapi - 使用 GetOverlappedResultEx 中的超时来模拟超时等待?
- java - 如何在 Mac 中从 Java 程序编译 LaTex 文件
- swift - 在多个 SKTextures、SKSpriteKit 之间淡入淡出
- python - 如何将线程对象传递给 ThreadPoolExecutor?
- java - 在 Java 中,是否有一个很好的算法来计算涉及复数的指数函数的更精确值?
- javascript - 正确扩展 DOM
- ruby - 元编程:类似于“def”的方法
- sqlite - 使用带有 LIMIT 的 SUM() 对表中的所有行求和,忽略限制
- c++ - 如何在 Visual Studio 中取回旧的 C++ 空项目项?