11import CleanCSS from "clean-css" ;
22import { getOptions } from "loader-utils" ;
33import { validate } from "schema-utils" ;
4-
4+ import type { RawSourceMap } from "source-map" ;
55import type { LoaderContext } from "webpack" ;
66import type { JSONSchema7 } from "schema-utils/declarations/validate" ;
77
@@ -15,6 +15,7 @@ type CleanCSSOptions = Omit<
1515interface LoaderOptions extends CleanCSSOptions {
1616 skipWarn ?: boolean ;
1717 disable ?: boolean ;
18+ sourceMap ?: boolean ;
1819}
1920
2021interface SourceMap {
@@ -32,6 +33,16 @@ interface AdditionalData {
3233 webpackAST : object ;
3334}
3435
36+ function parsePrevSourceMap (
37+ prevSourceMap ?: string | SourceMap
38+ ) : RawSourceMap | string | undefined {
39+ if ( prevSourceMap != null && typeof prevSourceMap === "object" ) {
40+ return JSON . stringify ( prevSourceMap ) ;
41+ }
42+
43+ return undefined ;
44+ }
45+
3546function cleanCssLoader (
3647 this : LoaderContext < LoaderOptions > ,
3748 content : string | Buffer ,
@@ -44,38 +55,42 @@ function cleanCssLoader(
4455 const loaderOptions = getOptions ( this ) || { } ;
4556
4657 validate ( schema as JSONSchema7 , loaderOptions , {
47- name : "group -css-media-queries -loader" ,
58+ name : "clean -css-loader" ,
4859 } ) ;
4960
50- const { disable, skipWarn, ...options } = loaderOptions ;
61+ const { sourceMap, disable, skipWarn, ...options } = loaderOptions ;
62+ const useSourceMap = Boolean ( sourceMap ?? this . sourceMap ) ;
5163
5264 if ( disable ) {
5365 return callback ( null , content , prevSourceMap , additionalData ) ;
5466 }
5567
5668 new CleanCSS ( {
57- returnPromise : true ,
5869 ...options ,
70+ returnPromise : true ,
71+ sourceMap : useSourceMap ,
5972 } )
60- . minify (
61- content ,
62- // @ts -ignore
63- prevSourceMap
64- )
73+ . minify ( content , parsePrevSourceMap ( prevSourceMap ) )
6574 . then ( ( output ) => {
6675 if ( ! skipWarn && Array . isArray ( output . warnings ) ) {
6776 output . warnings . forEach ( ( warning ) => {
6877 this . emitWarning ( new Error ( warning ) ) ;
6978 } ) ;
7079 }
7180
72- return callback (
73- null ,
74- output . styles ,
75- // @ts -ignore
76- output . sourceMap ,
77- additionalData
78- ) ;
81+ let resultSourceMap ;
82+
83+ if ( useSourceMap && output . sourceMap ) {
84+ resultSourceMap = {
85+ ...JSON . parse ( output . sourceMap . toString ( ) ) ,
86+ // @ts -ignore
87+ sources : prevSourceMap ?. sources || [ this . resourcePath ] ,
88+ // @ts -ignore
89+ sourcesContent : prevSourceMap ?. sourcesContent || [ content . toString ( ) ] ,
90+ } ;
91+ }
92+
93+ return callback ( null , output . styles , resultSourceMap , additionalData ) ;
7994 } )
8095 . catch ( callback ) ;
8196}
0 commit comments