11import * as webpack from 'webpack' ;
22import * as path from 'path' ;
3+ import { oneLineTrim } from 'common-tags' ;
34import {
45 SuppressExtractedTextChunksWebpackPlugin
56} from '../../plugins/suppress-entry-chunks-webpack-plugin' ;
@@ -8,6 +9,7 @@ import { WebpackConfigOptions } from '../webpack-config';
89import { pluginArgs } from '../../tasks/eject' ;
910
1011const cssnano = require ( 'cssnano' ) ;
12+ const postcssUrl = require ( 'postcss-url' ) ;
1113const autoprefixer = require ( 'autoprefixer' ) ;
1214const ExtractTextPlugin = require ( 'extract-text-webpack-plugin' ) ;
1315
@@ -39,11 +41,30 @@ export function getStylesConfig(wco: WebpackConfigOptions) {
3941 // https://github.com/webpack-contrib/style-loader#recommended-configuration
4042 const cssSourceMap = buildOptions . extractCss && buildOptions . sourcemap ;
4143
42- // minify/optimize css in production
43- // autoprefixer is always run separately so disable here
44- const extraPostCssPlugins = buildOptions . target === 'production'
45- ? [ cssnano ( { safe : true , autoprefixer : false } ) ]
46- : [ ] ;
44+ // Minify/optimize css in production.
45+ const cssnanoPlugin = cssnano ( { safe : true , autoprefixer : false } ) ;
46+
47+ // Convert absolute resource URLs to account for base-href and deploy-url.
48+ const urlPlugin = postcssUrl ( {
49+ url : ( URL : string ) => {
50+ // Only convert absolute URLs, which CSS-Loader won't process into require().
51+ if ( ! URL . startsWith ( '/' ) ) {
52+ return URL ;
53+ }
54+ // Join together base-href, deploy-url and the original URL.
55+ // Also dedupe multiple slashes into single ones.
56+ return oneLineTrim `
57+ /${ wco . buildOptions . baseHref || '' }
58+ /${ wco . buildOptions . deployUrl || '' }
59+ /${ URL }
60+ ` . replace ( / \/ \/ + / g, '/' ) ;
61+ }
62+ } ) ;
63+
64+ // PostCSS plugins.
65+ const postCssPlugins = [ autoprefixer ( ) , urlPlugin ] . concat (
66+ buildOptions . target === 'production' ? [ cssnanoPlugin ] : [ ]
67+ ) ;
4768
4869 // determine hashing format
4970 const hashFormat = getOutputHashFormat ( buildOptions . outputHashing ) ;
@@ -141,7 +162,7 @@ export function getStylesConfig(wco: WebpackConfigOptions) {
141162 new webpack . LoaderOptionsPlugin ( {
142163 sourceMap : cssSourceMap ,
143164 options : {
144- postcss : [ autoprefixer ( ) ] . concat ( extraPostCssPlugins ) ,
165+ postcss : postCssPlugins ,
145166 // css-loader, stylus-loader don't support LoaderOptionsPlugin properly
146167 // options are in query instead
147168 sassLoader : { sourceMap : cssSourceMap , includePaths } ,
0 commit comments