首页 > 解决方案 > 设置强制 CSS 在 JavaScript 之前加载

问题描述

我在我的项目中使用 webpack。我在“生产”模式下配置此插件时遇到问题。未生成 CSS 捆绑包。为此,我MiniCssExtractPlugin在我的使用中webpack.prod.js创建了一个 HTML 文件和 JS。结果,CSS 在浏览器中的 JavaScript 之后加载,然后在页面加载的第一秒内我遇到了一些难看的样式问题。在我的项目中,我使用“scss”。

我的webpack.prod.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const devMode = process.env.NODE_ENV !== 'production';
const webpack = require('webpack');

    module.exports = {
      //   devtool: '',
      entry: {
        index: ['@babel/polyfill', './src/js/index.js'],
        aboutUs: ['@babel/polyfill', './src/js/aboutUs.js'],
        offer: ['@babel/polyfill', './src/js/offer.js'],
        price: ['@babel/polyfill', './src/js/price.js'],
        contact: ['@babel/polyfill', './src/js/contact.js'],
      },
      plugins: [
        new CleanWebpackPlugin({ cleanStaleWebpackAssets: false }),
        new HtmlWebpackPlugin({
          title: 'empty',
          filename: 'index.html',
          template: './src/index.html',
          chunks: ['index'],
        }),
        new HtmlWebpackPlugin({
          title: 'empty',
          filename: 'aboutUs.html',
          template: './src/pages/aboutUs.html',
          chunks: ['aboutUs'],
        }),
        new HtmlWebpackPlugin({
          title: 'empty',
          filename: 'offer.html',
          template: './src/pages/offer.html',
          chunks: ['offer'],
        }),
        new HtmlWebpackPlugin({
          title: 'empty',
          filename: 'price.html',
          template: './src/pages/price.html',
          chunks: ['price'],
        }),
        new HtmlWebpackPlugin({
          title: 'empty',
          filename: 'contact.html',
          template: './src/pages/contact.html',
          chunks: ['contact'],
        }),
        new MiniCssExtractPlugin({
          filename: '[name].css',
          chunkFilename: '[id].css',
        }),
        new webpack.DefinePlugin({
          'process.env': {
          },
        }),
      ],
      output: {
        filename: '[name].[hash:20].js',
        path: path.resolve(__dirname, 'dist'),
      },
    
      module: {
        rules: [
          {
            test: /\.m?js$/,
            exclude: /(node_modules|bower_components)/,
            use: {
              loader: 'babel-loader',
              options: {
                presets: ['@babel/preset-env'],
              },
            },
          },
          {
            test: /\.(png|svg|jpg|jpeg|gif)$/i,
            type: 'asset/resource',
          },
          {
            test: /\.(woff|woff2|eot|ttf|otf)$/i,
            type: 'asset/resource',
          },
          {
            test: /\.s[ac]ss$/i,
            use: [
              // Creates `style` nodes from JS strings
              devMode ? 'style-loader' : MiniCssExtractPlugin.loader,
              // Translates CSS into CommonJS
              'css-loader',
              // Compiles Sass to CSS
              'sass-loader',
            ],
          },
        ],
      },
      optimization: {
        splitChunks: {
          chunks: 'all',
        },
      },
    };

我的package.json

  {
      
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1",
        "start": "webpack serve --config webpack.dev.js --mode development --open chrome.exe",
        "build": "webpack --config webpack.prod.js --mode production"
      },
      "devDependencies": {
        "@babel/core": "^7.12.7",
        "@babel/preset-env": "^7.12.7",
        "babel-loader": "^8.2.1",
        "clean-webpack-plugin": "^3.0.0",
        "css-loader": "^5.0.1",
        "file-loader": "^6.2.0",
        "html-loader": "^1.3.2",
        "html-webpack-plugin": "^4.5.0",
        "mini-css-extract-plugin": "^1.3.3",
        "optimize-css-assets-webpack-plugin": "^5.0.4",
        "sass": "^1.29.0",
        "sass-loader": "^10.1.0",
        "style-loader": "^2.0.0",
        "uglifyjs-webpack-plugin": "^2.2.0",
        "webpack": "^5.6.0",
        "webpack-cli": "^4.2.0",
        "webpack-dev-server": "^3.11.0"
      },
      "dependencies": {
        "@babel/polyfill": "^7.12.1",
        "@fortawesome/fontawesome-free": "^5.15.1",
        "emailjs-com": "^2.6.4",
        "lodash": "^4.17.20"
      },
      "browserslist": [
        "last 1 version",
        "> 1%",
        "IE 10"
      ]
    }

标签: javascriptcsswebpack

解决方案


在 Chrome、Brave、Microsoft Edge 等现代浏览器上,不存在在 javascript 之前加载 css 的技术。

在 JS 之前包含 CSS 的建议对于现代浏览器是无效的。把 CSS 放在你喜欢的地方,把 JS 放在最后。

对于 Firefox 或 Internet Explorer 等旧浏览器,请继续将 css 放在首位(如果您不想先显示裸露但可交互的页面)。


推荐阅读