5

我尝试使用 Webpack5 + MiniCssExtractPlugin + html-webpack-plugin 和其他插件在生产环境中构建,但我无法在 index.html 中包含 css 标签。

每次 css 文件都由 javascript 附加“无样式内容的闪存”(FOUC)问题。

我通过这个简单的命令使用npm run build :webpack --config webpack.prod.js

webpack.prod.js

const path = require('path');
const common = require('./webpack.config');
const { merge } = require('webpack-merge');
const {CleanWebpackPlugin} = require('clean-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = merge(common,{
    mode: 'production',
    output: {
        path: path.resolve(__dirname, 'build'),
        publicPath: '',
        filename: '[name].[hash].js',
    },
    plugins: [
        new CleanWebpackPlugin({}),
        new MiniCssExtractPlugin({
            filename:'[name].[hash].css'
        })
    ],
    module: {
        rules: [
            {
                test: /\.css$/i,
                use: [
                    MiniCssExtractPlugin.loader,
                    'css-loader'
                ]
            },
            {
                test: /\.scss$/i,
                use: [
                    MiniCssExtractPlugin.loader,
                    'css-loader',
                    'sass-loader'
                ]
            }
        ]
    }
});

webpack.config.js

const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    entry: {
        index: './src/index.js',
        vendor: './src/vendor.js'
    },
    plugins: [
        new HtmlWebpackPlugin({
            inject: 'body',
            template: './src/index.html',
            scriptLoading: "defer"
        })
    ],
    module: {
        rules: [
            {
                test: /\.html$/,
                use: [{
                    loader: 'html-loader'
                }]
            },
            {
                test: /\.(png|jpe?g|gif)$/i,
                use: [{
                    loader: 'file-loader',
                    options: {
                        name: '[name].[ext]',
                        outputPath: 'assets/images/'
                    }
                }],
            },
            {
                test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
                use: [{
                    loader: 'file-loader',
                    options: {
                        name: '[name].[ext]',
                        outputPath: 'assets/fonts/'
                    }
                }]
            }
        ]
    }
};

这是 index.html 结果:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="msapplication-tap-highlight" content="no"/>
    <title>title</title></head>
<body>

 all code here... 
 
<script defer="defer" src="index.19fae54ea5525bb23f67.js"></script>
<script defer="defer" src="vendor.19fae54ea5525bb23f67.js"></script>
</body>
</html>

在构建文件夹中,我有一个 *.js 和 *.css 文件列表,其中包含哈希和资产文件夹及其内容。

谢谢你的帮助

4

0 回答 0