为什么Webpack 5没有CSS文件输出?

7

我已经到处搜索了数天,但仍无法理解为什么我的最新尝试也不起作用。

为什么在dist文件夹中没有CSS文件?

现在我正在一个.js文件中导入样式,然后在我的应用程序入口点中导入该文件,但仍然没有效果。

webpack.config.js

const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const HTMLWebpackPlugin = require('html-webpack-plugin');

const path = require('path');

const paths = {
  src: path.resolve(__dirname, 'src'),
  dist: path.resolve(__dirname, 'dist'),
};

module.exports = {
  entry: 'index.js',
  mode: 'production',
  cache: false,
  output: {
    path: paths.dist,
    filename: 'index.js',
  },
  module: {
    rules: [
      {
        test: /\.s[ac]ss$/i,
        use: [
          'style-loader',
          {
            loader: 'css-loader',
            options: {
              sourceMap: true,
            },
          },
          {
            loader: 'sass-loader',
            options: {
              sourceMap: true,
            },
          },
        ],
      },
      {
        test: /\.(?:ico|gif|png|jpg|jpeg)$/i,
        type: 'asset/resource',
        generator: {
          filename: 'assets/[name][ext][query]',
        },
      },
      {
        test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
        type: 'asset/resource',
        generator: {
          filename: 'assets/fonts/[name][ext][query]',
        },
      },
    ],
  },

  plugins: [
    new CleanWebpackPlugin(),

    new MiniCssExtractPlugin({
      filename: '[name][contenthash].css',
      chunkFilename: '[id].css',
      ignoreOrder: false,
    }),

    new CopyWebpackPlugin({
      patterns: [
        {
          from: paths.src + '/assets',
          to: paths.dist + '/assets',
          toType: 'dir',
          globOptions: {
            ignore: ['*.DS_Store', 'Thumbs.db'],
          },
        },
        {
          from: paths.src + '/mocks',
          to: paths.dist + '/mocks',
          toType: 'dir',
          globOptions: {
            ignore: ['*.DS_Store', 'Thumbs.db'],
          },
        } /*{
            from: paths.src + '/styles.css',
            to: paths.dist + '/styles.css',
        }*/,
      ],
    }),

    new HTMLWebpackPlugin({
      filename: 'index.html',
      template: paths.src + '/index.html',
      favicon: paths.src + '/favicon.ico',
    }),
  ],
  performance: {
    hints: false,
    maxEntrypointSize: 512000,
    maxAssetSize: 512000,
  },
  resolve: {
    modules: [paths.src, 'node_modules'],
    extensions: ['.js', '.jsx', '.json'],
  },
};

src/importCSSForBuild.js

import './styles.scss'

src/index.js

import './js/ConsoleLog.js';
import './importCSSForBuild.js'
[... other stuff]

package.json

....
"sideEffects": [
    "**/*.css",
    "src/importCSSForBuild.js"
  ],
  "scripts": {
    "postinstall": "npm run start",
    "start": "npm-run-all --parallel css serve",
    "build": "cross-env NODE_ENV=production webpack --config webpack.config.js",
    "buildserve": "cross-env NODE_ENV=production webpack --config webpack.config.js && http-server ./dist -c-1 -p 8081",
    "test": "jest --no-cache ./src/*",
    "watch": "jest --no-cache --watch ./*",
    "coverage": "jest --coverage"
  },
  "devDependencies": {
    "@babel/core": "^7.16.12",
    "@babel/plugin-proposal-class-properties": "^7.16.7",
    "@babel/preset-env": "^7.16.11",
    "babel-jest": "^27.4.6",
    "babel-loader": "^8.2.3",
    "babel-preset-jest": "^27.4.0",
    "clean-webpack-plugin": "^4.0.0",
    "compression-webpack-plugin": "^9.2.0",
    "copy-webpack-plugin": "^10.2.2",
    "cross-env": "^7.0.3",
    "css-loader": "^6.6.0",
    "css-minimizer-webpack-plugin": "^3.4.1",
    "dead-server": "1.0.6",
    "html-webpack-plugin": "^5.5.0",
    "http-server": "^14.1.0",
    "jest": "^27.4.7",
    "mini-css-extract-plugin": "^2.5.3",
    "node-sass": "^7.0.1",
    "npm-run-all": "^4.1.5",
    "postcss-loader": "^6.2.1",
    "postcss-preset-env": "^7.2.3",
    "prettier": "^2.5.1",
    "resolve-url-loader": "^5.0.0",
    "sass": "^1.49.0",
    "sass-loader": "^12.4.0",
    "style-loader": "^3.3.1",
    "webpack": "^5.67.0",
    "webpack-cli": "^4.9.2",
    "webpack-dashboard": "^3.3.7",
    "webpack-dev-server": "^4.7.3"
  },
  "engines": {
    "node": ">=14.15.0"
  }
}

1
在webpack 5中,你可以使用output: { clean: true }来代替使用clean-webpack-plugin - mindlid
1个回答

7
我看到这个Webpack配置是为了在生产模式下运行Webpack,你想将CSS文件单独提取到其他文件中,以便浏览器在仅JS文件更改时(加载故障)不必重新加载整个应用程序(包括CSS和JS)。
使用mini-css-extract-plugin插件,将CSS提取到单独的文件中,该CSS文件链接到HTMLWebpackPlugin的模板属性中定义的HTML文件上。
MiniCSSExtractPlugin的官方文档中,提到需要使用MiniCSSExtractPlugin.loader将CSS与CSS加载器一起提取到文件中。
在您的配置中,您使用了style-loader,所以需要更改为MiniCSSExtractPlugin.loader
同时,不要在Loaders链中与style-loader一起使用此插件。
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const HTMLWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  plugins: [
    new MiniCssExtractPlugin({
      filename: "[name][contenthash].css",
      chunkFilename: "[id].css",
      ignoreOrder: false,
    }),
    ,
    new HTMLWebpackPlugin({
      filename: "index.html",
      template: paths.src + "/index.html", // css will be linked in this file
      favicon: paths.src + "/favicon.ico",
    }),
  ],
  module: {
    rules: [
      {
        test: /\.s[ac]ss$/i,
        use: [
          MiniCssExtractPlugin.loader, // extract css into files
          "css-loader", // convert css to js string css
          "sass-loader", // convert sass to css
        ],
      },
    ],
  },
};

style-loader主要用于使用样式标签将CSS添加/注入到DOM中,而MiniCSSExtractPlugin.loader用于提取CSS到文件中,并在HTMLWebpackPlugin指定的模板HTML文件中添加同一个CSS文件的链接标记。


1
在 https://webpack.js.org/plugins/mini-css-extract-plugin/#advanced-configuration-example 中提到,我们不应该在加载器链中使用 style-loader 这个插件。 - Subrato Pattanaik
没有运气,但现在我在控制台上也看到了这个:孤立模块 15.6 KiB (javascript) 4.74 KiB (css/mini-extract) 407 KiB (asset) 1.02 KiB (runtime) [orphan] 21 modules - Afonso Gomes

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接