Skip to content

Commit 5007a19

Browse files
alan-agius4alexeagle
authored andcommitted
refactor(@angular-devkit/build-angular): clean up style webpack config
Clean up several parts of the styles config and also removed the dependency on `postcss-url`
1 parent ee7603f commit 5007a19

File tree

5 files changed

+81
-148
lines changed

5 files changed

+81
-148
lines changed

packages/angular_devkit/build_angular/package.json

-1
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,6 @@
3434
"postcss": "^6.0.22",
3535
"postcss-import": "^11.1.0",
3636
"postcss-loader": "^2.1.5",
37-
"postcss-url": "^7.3.2",
3837
"raw-loader": "^0.5.1",
3938
"rxjs": "~6.2.0",
4039
"sass-loader": "^7.1.0",

packages/angular_devkit/build_angular/src/angular-cli-files/models/webpack-configs/styles.ts

+43-125
Original file line numberDiff line numberDiff line change
@@ -5,24 +5,21 @@
55
* Use of this source code is governed by an MIT-style license that can be
66
* found in the LICENSE file at https://angular.io/license
77
*/
8-
// tslint:disable
9-
// TODO: cleanup this file, it's copied as is from Angular CLI.
108

11-
import * as webpack from 'webpack';
129
import * as path from 'path';
13-
import { SuppressExtractedTextChunksWebpackPlugin } from '../../plugins/webpack';
14-
import { getOutputHashFormat } from './utils';
10+
import * as webpack from 'webpack';
11+
import {
12+
PostcssCliResources,
13+
RawCssLoader,
14+
RemoveHashPlugin,
15+
SuppressExtractedTextChunksWebpackPlugin,
16+
} from '../../plugins/webpack';
1517
import { WebpackConfigOptions } from '../build-options';
16-
import { findUp } from '../../utilities/find-up';
17-
import { RawCssLoader } from '../../plugins/webpack';
18-
import { normalizeExtraEntryPoints } from './utils';
19-
import { RemoveHashPlugin } from '../../plugins/remove-hash-plugin';
18+
import { getOutputHashFormat, normalizeExtraEntryPoints } from './utils';
2019

21-
const postcssUrl = require('postcss-url');
2220
const autoprefixer = require('autoprefixer');
2321
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
2422
const postcssImports = require('postcss-import');
25-
const PostcssCliResources = require('../../plugins/webpack').PostcssCliResources;
2623

2724
/**
2825
* Enumerate loaders and their dependencies from this file to let the dependency validator
@@ -38,19 +35,11 @@ const PostcssCliResources = require('../../plugins/webpack').PostcssCliResources
3835
* require('sass-loader')
3936
*/
4037

41-
interface PostcssUrlAsset {
42-
url: string;
43-
hash: string;
44-
absolutePath: string;
45-
}
46-
4738
export function getStylesConfig(wco: WebpackConfigOptions) {
48-
const { root, projectRoot, buildOptions } = wco;
49-
50-
// const appRoot = path.resolve(projectRoot, appConfig.root);
39+
const { root, buildOptions } = wco;
5140
const entryPoints: { [key: string]: string[] } = {};
5241
const globalStylePaths: string[] = [];
53-
const extraPlugins: any[] = [];
42+
const extraPlugins = [];
5443
const cssSourceMap = buildOptions.sourceMap;
5544

5645
// Determine hashing format.
@@ -62,80 +51,25 @@ export function getStylesConfig(wco: WebpackConfigOptions) {
6251
const postcssPluginCreator = function (loader: webpack.loader.LoaderContext) {
6352
return [
6453
postcssImports({
65-
resolve: (url: string, context: string) => {
66-
return new Promise<string>((resolve, reject) => {
67-
let hadTilde = false;
68-
if (url && url.startsWith('~')) {
69-
url = url.substr(1);
70-
hadTilde = true;
71-
}
72-
loader.resolve(context, (hadTilde ? '' : './') + url, (err: Error, result: string) => {
73-
if (err) {
74-
if (hadTilde) {
75-
reject(err);
76-
return;
77-
}
78-
loader.resolve(context, url, (err: Error, result: string) => {
79-
if (err) {
80-
reject(err);
81-
} else {
82-
resolve(result);
83-
}
84-
});
85-
} else {
86-
resolve(result);
87-
}
88-
});
89-
});
90-
},
54+
resolve: (url: string) => url.startsWith('~') ? url.substr(1) : url,
9155
load: (filename: string) => {
9256
return new Promise<string>((resolve, reject) => {
9357
loader.fs.readFile(filename, (err: Error, data: Buffer) => {
9458
if (err) {
9559
reject(err);
60+
9661
return;
9762
}
9863

9964
const content = data.toString();
10065
resolve(content);
10166
});
10267
});
103-
}
104-
}),
105-
postcssUrl({
106-
filter: ({ url }: PostcssUrlAsset) => url.startsWith('~'),
107-
url: ({ url }: PostcssUrlAsset) => {
108-
// Note: This will only find the first node_modules folder.
109-
const nodeModules = findUp('node_modules', projectRoot);
110-
if (!nodeModules) {
111-
throw new Error('Cannot locate node_modules directory.')
112-
}
113-
const fullPath = path.join(nodeModules, url.substr(1));
114-
return path.relative(loader.context, fullPath).replace(/\\/g, '/');
115-
}
68+
},
11669
}),
117-
postcssUrl([
118-
{
119-
// Only convert root relative URLs, which CSS-Loader won't process into require().
120-
filter: ({ url }: PostcssUrlAsset) => url.startsWith('/') && !url.startsWith('//'),
121-
url: ({ url }: PostcssUrlAsset) => {
122-
if (deployUrl.match(/:\/\//) || deployUrl.startsWith('/')) {
123-
// If deployUrl is absolute or root relative, ignore baseHref & use deployUrl as is.
124-
return `${deployUrl.replace(/\/$/, '')}${url}`;
125-
} else if (baseHref.match(/:\/\//)) {
126-
// If baseHref contains a scheme, include it as is.
127-
return baseHref.replace(/\/$/, '') +
128-
`/${deployUrl}/${url}`.replace(/\/\/+/g, '/');
129-
} else {
130-
// Join together base-href, deploy-url and the original URL.
131-
// Also dedupe multiple slashes into single ones.
132-
return `/${baseHref}/${deployUrl}/${url}`.replace(/\/\/+/g, '/');
133-
}
134-
}
135-
}
136-
]),
13770
PostcssCliResources({
138-
deployUrl: loader.loaders[loader.loaderIndex].options.ident == 'extracted' ? '' : deployUrl,
71+
baseHref,
72+
deployUrl,
13973
loader,
14074
filename: `[name]${hashFormat.file}.[ext]`,
14175
}),
@@ -164,12 +98,11 @@ export function getStylesConfig(wco: WebpackConfigOptions) {
16498

16599
normalizeExtraEntryPoints(buildOptions.styles, 'styles').forEach(style => {
166100
const resolvedPath = path.resolve(root, style.input);
167-
168101
// Add style entry points.
169102
if (entryPoints[style.bundleName]) {
170-
entryPoints[style.bundleName].push(resolvedPath)
103+
entryPoints[style.bundleName].push(resolvedPath);
171104
} else {
172-
entryPoints[style.bundleName] = [resolvedPath]
105+
entryPoints[style.bundleName] = [resolvedPath];
173106
}
174107

175108
// Add lazy styles to the list.
@@ -189,18 +122,20 @@ export function getStylesConfig(wco: WebpackConfigOptions) {
189122

190123
let dartSass: {} | undefined;
191124
try {
125+
// tslint:disable-next-line:no-implicit-dependencies
192126
dartSass = require('sass');
193127
} catch { }
194128

195129
let fiber: {} | undefined;
196130
if (dartSass) {
197131
try {
132+
// tslint:disable-next-line:no-implicit-dependencies
198133
fiber = require('fibers');
199134
} catch { }
200135
}
201136

202137
// set base rules to derive final rules from
203-
const baseRules: webpack.Rule[] = [
138+
const baseRules: webpack.RuleSetRule[] = [
204139
{ test: /\.css$/, use: [] },
205140
{
206141
test: /\.scss$|\.sass$/,
@@ -212,9 +147,9 @@ export function getStylesConfig(wco: WebpackConfigOptions) {
212147
sourceMap: cssSourceMap,
213148
// bootstrap-sass requires a minimum precision of 8
214149
precision: 8,
215-
includePaths
216-
}
217-
}]
150+
includePaths,
151+
},
152+
}],
218153
},
219154
{
220155
test: /\.less$/,
@@ -224,23 +159,23 @@ export function getStylesConfig(wco: WebpackConfigOptions) {
224159
sourceMap: cssSourceMap,
225160
javascriptEnabled: true,
226161
...lessPathOptions,
227-
}
228-
}]
162+
},
163+
}],
229164
},
230165
{
231166
test: /\.styl$/,
232167
use: [{
233168
loader: 'stylus-loader',
234169
options: {
235170
sourceMap: cssSourceMap,
236-
paths: includePaths
237-
}
238-
}]
239-
}
171+
paths: includePaths,
172+
},
173+
}],
174+
},
240175
];
241176

242177
// load component css as raw strings
243-
const rules: webpack.Rule[] = baseRules.map(({ test, use }) => ({
178+
const rules: webpack.RuleSetRule[] = baseRules.map(({ test, use }) => ({
244179
exclude: globalStylePaths,
245180
test,
246181
use: [
@@ -250,50 +185,33 @@ export function getStylesConfig(wco: WebpackConfigOptions) {
250185
options: {
251186
ident: 'embedded',
252187
plugins: postcssPluginCreator,
253-
sourceMap: cssSourceMap ? 'inline' : false
254-
}
188+
sourceMap: cssSourceMap ? 'inline' : false,
189+
},
255190
},
256-
...(use as webpack.Loader[])
257-
]
191+
...(use as webpack.Loader[]),
192+
],
258193
}));
259194

260195
// load global css as css files
261196
if (globalStylePaths.length > 0) {
262197
rules.push(...baseRules.map(({ test, use }) => {
263-
const extractTextPlugin = {
198+
return {
199+
include: globalStylePaths,
200+
test,
264201
use: [
265-
// style-loader still has issues with relative url()'s with sourcemaps enabled;
266-
// even with the convertToAbsoluteUrls options as it uses 'document.location'
267-
// which breaks when used with routing.
268-
// Once style-loader 1.0 is released the following conditional won't be necessary
269-
// due to this 1.0 PR: https://github.com/webpack-contrib/style-loader/pull/219
270-
{ loader: buildOptions.extractCss ? RawCssLoader : 'raw-loader' },
202+
buildOptions.extractCss ? MiniCssExtractPlugin.loader : 'style-loader',
203+
RawCssLoader,
271204
{
272205
loader: 'postcss-loader',
273206
options: {
274207
ident: buildOptions.extractCss ? 'extracted' : 'embedded',
275208
plugins: postcssPluginCreator,
276-
sourceMap: cssSourceMap && !buildOptions.extractCss ? 'inline' : cssSourceMap
277-
}
209+
sourceMap: cssSourceMap && !buildOptions.extractCss ? 'inline' : cssSourceMap,
210+
},
278211
},
279-
...(use as webpack.Loader[])
212+
...(use as webpack.Loader[]),
280213
],
281-
// publicPath needed as a workaround https://github.com/angular/angular-cli/issues/4035
282-
publicPath: ''
283-
};
284-
const ret: any = {
285-
include: globalStylePaths,
286-
test,
287-
use: [
288-
buildOptions.extractCss ? MiniCssExtractPlugin.loader : 'style-loader',
289-
...extractTextPlugin.use,
290-
]
291214
};
292-
// Save the original options as arguments for eject.
293-
// if (buildOptions.extractCss) {
294-
// ret[pluginArgs] = extractTextPlugin;
295-
// }
296-
return ret;
297215
}));
298216
}
299217

@@ -309,6 +227,6 @@ export function getStylesConfig(wco: WebpackConfigOptions) {
309227
return {
310228
entry: entryPoints,
311229
module: { rules },
312-
plugins: extraPlugins
230+
plugins: extraPlugins,
313231
};
314232
}

0 commit comments

Comments
 (0)