How to specify output directory with "mini-css-extract-plugin"?
Asked Answered
D

2

27

I am using the mini-css-extract-plugin to extract the CSS from a bundle to a file. I need to drop that file in a different place in the filesystem.

How do I configure the mini-css-extract-plugin to drop the CSS file to a different path than the JS bundle?

Declass answered 19/10, 2018 at 13:54 Comment(1)
You can't do that. You can only specify the folder relative to the output folder specified on your webpack config. You would need to manually/automate the copy after the build is successReinforce
F
39

Let's assume the following config:

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!
    })
  ]
  // ...
}

Where your output path would resolve to - as an example - /home/terribledev/projects/some-project/dist.

If you change the filename property of the MiniCssExtractPlugin options object to ../../[name].css, it will now be output to /home/terribledev/projects/yourcssfile.css, e.g.:

module.exports = {
  output: {
    path: path.resolve(__dirname, "dist")
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: "../../[name].css"
    })
  ]
  // ...
}
Fascinating answered 19/10, 2018 at 15:12 Comment(3)
What if you want to customize the filename? Is there a way to have the output filename match the initial css filename (and not the js filename that holds the import statement)?Perfecto
how to save in a css/ directory in dist directory?Brainsick
@Brainsick see my answerCarnivore
C
8

To specify an output path within the build directory, I include the subdirectory in the filename:

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
        }),
    ],
    // ...
}

I've tested this in Webpack versions 4 and 5 with success. Check out the docs for Webpack output to learn more.

Carnivore answered 9/12, 2020 at 17:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.