使用 mini-css-extract-plugin 指定输出目录

Ter*_*Dev 21 webpack webpack-4 mini-css-extract-plugin

我正在使用 mini-css-extract-plugin 将 css 从我们的包中提取到一个文件中。我需要将该文件放在文件系统中的不同位置。

如何配置 mini-css-extract-plugin 以将 css 文件放到与 js 包不同的路径。

axm*_*m__ 25

让我们假设以下配置:

webpack.config.js

module.exports = {
  // ...
  output: {
    path: path.resolve(__dirname, "dist") // this is the default value
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: "[name].css" // change this RELATIVE to your output.path!
    })
  ]
  // ...
}
Run Code Online (Sandbox Code Playgroud)

您的输出路径将解析为 - 例如 - /home/terribledev/projects/some-project/dist

如果将MiniCssExtractPlugin选项对象的文件名属性更改为../../[name].css,则现在将输出为/home/terribledev/projects/yourcssfile.css,例如:

module.exports = {
  output: {
    path: path.resolve(__dirname, "dist")
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: "../../[name].css"
    })
  ]
  // ...
}
Run Code Online (Sandbox Code Playgroud)

  • 如果你想自定义文件名怎么办?有没有办法让输出文件名与初始 css 文件名匹配(而不是包含 import 语句的 js 文件名)? (2认同)

bre*_*net 8

要指定构建目录中的输出路径,我在文件名中包含子目录:

const path = require('path');

module.exports = {
    // ...
    output: {
      path: path.resolve(process.cwd(), 'build'), // should be an absolute path
      filename: 'js/[name].js', // relative to output.path
    },
    plugins: [
        new MiniCssExtractPlugin({
            filename: "css/[name].css", // relative to output.path
        }),
    ],
    // ...
}
Run Code Online (Sandbox Code Playgroud)

我已经在 Webpack 版本 4 和 5 中成功测试了这一点。查看Webpack 输出的文档以了解更多信息。