Solvedoptimize css assets webpack plugin Source Maps not working with Webpack 4.8

My version of optimize-css-assets-webpack-plugin: 4.0.1

The issue I'm facing is the same as described here:
webpack-contrib/mini-css-extract-plugin#141

In summary, I'm defining source-maps on my configuration. I'm also using MiniCssExtractPlugin to extract the css modules to a specific bundle, but when using optimize-css-assets-webpack-plugin on webpacks 4 optimization.minimizer, the source-maps are not generated. Here is a snippet:

  optimization: {
    minimizer: [
      new UglifyJsPlugin({
        cache: true,
        parallel: true,
        sourceMap: true // set to true if you want JS source maps
      }),
      new OptimizeCSSAssetsPlugin({}) // <---- THIS. Commenting/Uncommenting results in: No Optimization with source-maps/ Optimization without source-maps
    ]
  },

  plugins: [

    new webpack.DefinePlugin({
      'process.env.NODE_ENV': 'production'
    }),
    new MiniCssExtractPlugin({
      filename: 'foo.min.css'
    }),
  ],
  devtools: 'source-maps'

Maybe optimize-css-assets-webpack-plugin is truncating source-maps some how?!

23 Answers

✔️Accepted Answer

Have you read PostCSS sourcemaps options section?
For example if you need inline source maps, use:

new OptimizeCSSAssetsPlugin({
  cssProcessorOptions: {
    map: {
      inline: true,
    }
  }
})

If you need external source maps, use:

new OptimizeCSSAssetsPlugin({
  cssProcessorOptions: {
    map: {
      inline: false,
      annotation: true,
    }
  }
})

Other Answers:

Just figured it out! (this helped with a useful snippet: cssnano/cssnano#302)

Actually this is not a bug, but can be improved (with docs or better defaults to identify if there are settings in webpack to generate source-maps...)

You just need to set the map property to cssProcessorOptions (something like this):

      new OptimizeCSSAssetsPlugin({
        cssProcessorOptions: {
          map: {
            inline: false
          }
        }
      })

If no other cssProcessor is specified, then cssnano is used by default.
Then the plugin will pass the cssProcessorOptions as options to it. So searching on how to do it with cssnano gave me that hint on how to properly configure cssnano.

Maybe docs improvements could be made so that it would become clearer on how to use cssProcessorOptions (at least for the default processor, cssnano). Or maybe this plugin could somehow know if the webpack setup is configured to use source-maps or if the css itself has it to set map property to cssnano in that case (sorry if I'm talking silliness, I'm not a webpack nor a cssnano expert at all... It was just a painful debugging session...)

Or we may add a special sourceMap option to OptimizeCSSAssetsPlugin which will do the same under the hood similar to postcss-loader.

For example:

new OptimizeCSSAssetsPlugin({ sourceMap: true })
new OptimizeCSSAssetsPlugin({ sourceMap: 'inline' })

PR is welcome :)

Thanks for all the effort to get the source maps working. Using the tips here and installing the 5.0 release I am now able to get external map files generated for my project and they are working in the browser.

However, there is still something a bit off with the paths that are generated and placed into the map file. When I do a non production build without using this optimize css plugin the generated map file has entries in it that look like this:

{"version":3,
"sources":[
  "webpack:///./src/components/controlbar/css/endpoint-mode-selector.less",
  "webpack:///./src/index.css",
  "webpack:///./src/assets/Roboto-local.css", 

When I do a production build using this optimize css plugin the map file looks like this:

{"version":3,
  "sources":[
    "/data/hbird/src/components/controlbar/css/endpoint-mode-selector.less",
    "/data/hbird/src/index.css",
    "/data/hbird/src/assets/Roboto-local.css",

I am using the config suggested above.

new OptimizeCSSAssetsPlugin({
  cssProcessorOptions: {
    map: {
      inline: false,
      annotation: true,
    }
  }
})

This still works in the browser, but the file system mappings look a bit odd in the developer tools. Is there some way to get the map file to be generated using the same webpack:///./src style file references? I did experiment with turning off the source maps on the css-loader and less-loaders which did change things a bit but nothing gets the same output as not using the optimize css plugin.

Here is a snippet of the webpack config (extractCSS and genSourceMaps are true):

     {
        test: /\.less$/,
        include: props.srcRoot,
        use: [
          {loader: extractCSS ? MiniCssExtractPlugin.loader : "style-loader"},
          {loader: "css-loader", options: {sourceMap: genSourceMaps}},
          {loader: "less-loader", options: {sourceMap: genSourceMaps}}
        ]
      },

Related Issues:

38
optimize css assets webpack plugin Source Maps not working with Webpack 4.8
Have you read PostCSS sourcemaps options section? For example if you need inline source maps use: If...
166
extract text webpack plugin An error with extract-text-webpack-plugin@3.0.0(throw new _ValidationError2.default(ajv.errors, name))
To @joemcloE's point fallBackLoader was deprecated in a previous major release and removed in the fo...
150
extract text webpack plugin Error: Path variable [contenthash] not implemented in this context: style/[name].[contenthash].css
A temporary solution that you can use until it's fixed is to replace [contenthash] with something li...
101
mini css extract plugin Don't output empty JS files
@tiendq I don't want Webpack to output a JS file for CSS It seems strange to me for it to do that At...
99
uglifyjs webpack plugin Es6 parsing errors
Just adding to summarize what worked for me: webpack 3.10.0 internally uses UglifyJsPlugin 0.4.6 whi...
84
extract text webpack plugin Webpack 2: How to extract Sass and convert to css file
This works for me (using extract-text-webpack-plugin v2.0.0-beta.4): Hi Trying to use your module to...
76
mini css extract plugin No module factory available for dependency type: CssDependency
Fixed this issue I was missing plugin (see set plugins sections below) Operating System: Mac OS X 10...
63
copy webpack plugin New files are not being copied in watch-mode
I found the root cause after reading thru change log and code of clean-webpack-plugin Since clean-we...
62
clean webpack plugin clean-webpack-plugin: /Users/user/.../ must be inside the project root. Skipping...
@fr-ench Give a try root: process.cwd() It did worked for me! I get this error after updating to 0.1...
48
extract text webpack plugin feat: extract multiple css files based on pattern
@bebraw I've changed my configuration entry to: Indeed it works (however it's confusing because in l...
44
copy webpack plugin Does not copy files to actual output folder when webpack-dev-server is used
I had the same problem with v4.0.1 (files not copied to output folder) After seeing the Breaking Cha...
43
extract text webpack plugin TypeError thrown when trying to generate source map
Same happens with: when you forget about sourceMap: true when passing options to UglifyJsPlugin Now ...
42
fork ts checker webpack plugin Type checking for node_modules
For me the solution was to add skipLibCheck: true to tsconfig.json I'm seeing a whole bunch of error...
40
uglifyjs webpack plugin switch to uglify-es
@skorunka Hmm I've been using a similar workaround (see below) while waiting for this issue and it s...
37
webpack.js.org Old documentations (3.8)
for other who try to get v3 documentation running locally instruction are: note should be start not ...
33
clean webpack plugin Error: ENOTEMPTY: directory not empty
One reason could be if you have live server extension installed ??? When I disable it the error goes...
32
extract text webpack plugin Webpack 2: How to extract CSS/LESS modules into CSS files?
it's work for me webpack: 2.2.1 and extract-text-webpack-plugin: 2.0.0-rc.3 ...
32
mini css extract plugin Too much console output information
Here's a slightly less horrible workaround (not a fix obviously) Hi there ...
31
extract text webpack plugin webpack 2: Error in ... doesn't export content
It turns out that the problem was that I had my rule set up as: instead of Basically the code breaks...
27
compression webpack plugin TypeError: Cannot read property 'tapPromise' of undefined for webpack 5.6.0
For anyone running into this issue using create-react-app version 4 it uses webpack 4 so compression...
27
webpack.js.org API - Document When a Plugin Should Call `doResolve()`
Hi all -- I'm someone who has also been spelunking through a lot of Webpack's code Specifically Webp...
24
mini css extract plugin mini-css-extract-plugin with SSR.
My experiments with SSR have shown that you can skip the requireEnsure hook on the server side ...
24
uglifyjs webpack plugin Turn off inlining in optimization until UglifyJS issue is fixed.
People just an insight: I spent 15 hours (literally) trying to resolve a problem on my build ...
22
uglifyjs webpack plugin requestShortener.shorten is not a function
我也碰到了同样的问题,但是上周五还是好好的。于是我对比了之前的 package.json,发现 uglifyjs-webpack-plugin 的版本是 0.4.6,但现在已经是1.1.4了。于是我又...
20
prerender spa plugin vue-cli v3, can't get it to work.. no errors but pre-rendered routes don't contain static html
找到方法了 prerender-spa-plugin 在dist目录起了一个服务 资源的引用路径是 根目录/baseUrl/* 但是实际上资源的路径为 根目录/* 所以prerender-spa-pl...
20
extract text webpack plugin publicPath parameter doesn't work?
Solved similar problem just by disabling of url(...) processing in css-loader by setting url option ...
20
extract text webpack plugin How to properly use multiple loaders with this plugin?
I was running in to a similar issue when moving to webpack 2 from 1 Hello! I am using webpack@2.2.0-...
19
mini css extract plugin Webpack 5 support
The capitalisation issue mentioned by @stupidmonke was my problem too when running from Windows My c...
18
webpack.js.org output.chunkFilename cannot be a function
Question: if this is true how can you determine if you need one chunk to skip the hash ...
17
mini css extract plugin Misleading error, when used with html-webpack-plugin
CSS-related issues in html-webpack-plugin: it's probably mini-css-extract-plugin issue Issues in min...
16
extract text webpack plugin [webpack v3.0.0] generates CSS in wrong order
Closing this as all issues reported have been resolved & regression tests added ...
16
uglifyjs webpack plugin Webpack's removes classnames when minifying/uglifying ES6 code with inheritance
Why is this issue closed? Using constructor.name is perfectly valid in JavaScript ...
16
uglifyjs webpack plugin Production build hangs at 92%
I just upgraded to webpack 4 (4.5.0) and I'm experiencing the same It takes ages to finish the build...
15
react refresh webpack plugin Migrate plugin for Webpack dev server v4
0.5.0-rc.4 should work with WDS v4 by default the socket path however would need a bit of re-work - ...
14
react refresh webpack plugin Multiple entry points not working correctly
You can use multiple entry points on a single page but make sure to use optimization.runtimeChunk: s...
13
copy webpack plugin [Feature] Support manifest file
I do thank you a lot for the code that removes the hash (see under this text) from the file names ...
12
mini css extract plugin [Windows only] - ModuleNotFoundError: Module not found: Error: Can't resolve...
Just ran into this myself In my own case a css directive like background-image: url('../images/someI...
11
svg sprite loader Exception: 2 rules applies to svg
@vercoelenmike thx. i found myself forget to add 'exclude'. lol Do you want to request a feature rep...
10
purgecss Purgecss breaks with nuxt and vuetify
I managed to remove a lot of unused CSS in my Nuxt + Vuetify + Tailwind app I followed the instructi...
9
mini css extract plugin publicPath not doing anything
Despite I landed here for the same reason described by @HoldYourWaffle This might be related to #222...
8
uglifyjs webpack plugin SyntaxError: Cannot declare a let variable twice
SyntaxError: Cannot declare a let variable twice This is an ES6 bug in Safari 10: https://bugs.webki...
6
react refresh webpack plugin Try integrating into Create React App
facebook/create-react-app#8582 has been merged but some API naming work still has to be done so I'll...
5
workerize loader Empty Worker returned after hot-reloading
Now I found the root fo the problem: the __workerizeExports property is not persisted on the compila...
4
offline plugin SWs & Webpack
(text may have a lot of type because I wasn't re-reading/reviewing it) I actually been thinking abou...
4
react refresh webpack plugin Component modifications are not applied
DevTools (and React Refresh) initialises global development hooks where the development build of Rea...
3
offline plugin How to exclude a specific path and all the paths underneath from being cached?
/admin and all the paths underneath are not part of my app so I want to avoid the SW from caching th...
3
webpack.js.org bundle.js:47 Uncaught SyntaxError: Unexpected token import
Thanks for your issue This probably has to do with the Getting Started guide not pointing to the web...