I am using react and Webpack 5. After running a lighthouse report, I found a few css files that need to be preloaded. How do I do this in 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' },
],
}),
]
};
I tried Magic Comments (as follows) but it did not preload the css.
import (
/* webpackPrefetch: true */
/* webpackPreload: true */
'./Article.css'
);
And I tried PreloadWebpackPlugin, but I could only get it to preload all of the css files in the react project, or none at all.
Ideally, the solution would only include what is needed for the given page...
Any ideas moving forward would be appreciated. Thanks!