Skip to content

Commit

Permalink
refactor(@angular-devkit/build-angular): clean up style webpack config
Browse files Browse the repository at this point in the history
Clean up several parts of the styles config and also removed the dependency on `postcss-url`
  • Loading branch information
alan-agius4 authored and alexeagle committed Sep 6, 2018
1 parent ee7603f commit 5007a19
Show file tree
Hide file tree
Showing 5 changed files with 81 additions and 148 deletions.
1 change: 0 additions & 1 deletion packages/angular_devkit/build_angular/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@
"postcss": "^6.0.22",
"postcss-import": "^11.1.0",
"postcss-loader": "^2.1.5",
"postcss-url": "^7.3.2",
"raw-loader": "^0.5.1",
"rxjs": "~6.2.0",
"sass-loader": "^7.1.0",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,24 +5,21 @@
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// tslint:disable
// TODO: cleanup this file, it's copied as is from Angular CLI.

import * as webpack from 'webpack';
import * as path from 'path';
import { SuppressExtractedTextChunksWebpackPlugin } from '../../plugins/webpack';
import { getOutputHashFormat } from './utils';
import * as webpack from 'webpack';
import {
PostcssCliResources,
RawCssLoader,
RemoveHashPlugin,
SuppressExtractedTextChunksWebpackPlugin,
} from '../../plugins/webpack';
import { WebpackConfigOptions } from '../build-options';
import { findUp } from '../../utilities/find-up';
import { RawCssLoader } from '../../plugins/webpack';
import { normalizeExtraEntryPoints } from './utils';
import { RemoveHashPlugin } from '../../plugins/remove-hash-plugin';
import { getOutputHashFormat, normalizeExtraEntryPoints } from './utils';

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

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

interface PostcssUrlAsset {
url: string;
hash: string;
absolutePath: string;
}

export function getStylesConfig(wco: WebpackConfigOptions) {
const { root, projectRoot, buildOptions } = wco;

// const appRoot = path.resolve(projectRoot, appConfig.root);
const { root, buildOptions } = wco;
const entryPoints: { [key: string]: string[] } = {};
const globalStylePaths: string[] = [];
const extraPlugins: any[] = [];
const extraPlugins = [];
const cssSourceMap = buildOptions.sourceMap;

// Determine hashing format.
Expand All @@ -62,80 +51,25 @@ export function getStylesConfig(wco: WebpackConfigOptions) {
const postcssPluginCreator = function (loader: webpack.loader.LoaderContext) {
return [
postcssImports({
resolve: (url: string, context: string) => {
return new Promise<string>((resolve, reject) => {
let hadTilde = false;
if (url && url.startsWith('~')) {
url = url.substr(1);
hadTilde = true;
}
loader.resolve(context, (hadTilde ? '' : './') + url, (err: Error, result: string) => {
if (err) {
if (hadTilde) {
reject(err);
return;
}
loader.resolve(context, url, (err: Error, result: string) => {
if (err) {
reject(err);
} else {
resolve(result);
}
});
} else {
resolve(result);
}
});
});
},
resolve: (url: string) => url.startsWith('~') ? url.substr(1) : url,
load: (filename: string) => {
return new Promise<string>((resolve, reject) => {
loader.fs.readFile(filename, (err: Error, data: Buffer) => {
if (err) {
reject(err);

return;
}

const content = data.toString();
resolve(content);
});
});
}
}),
postcssUrl({
filter: ({ url }: PostcssUrlAsset) => url.startsWith('~'),
url: ({ url }: PostcssUrlAsset) => {
// Note: This will only find the first node_modules folder.
const nodeModules = findUp('node_modules', projectRoot);
if (!nodeModules) {
throw new Error('Cannot locate node_modules directory.')
}
const fullPath = path.join(nodeModules, url.substr(1));
return path.relative(loader.context, fullPath).replace(/\\/g, '/');
}
},
}),
postcssUrl([
{
// Only convert root relative URLs, which CSS-Loader won't process into require().
filter: ({ url }: PostcssUrlAsset) => url.startsWith('/') && !url.startsWith('//'),
url: ({ url }: PostcssUrlAsset) => {
if (deployUrl.match(/:\/\//) || deployUrl.startsWith('/')) {
// If deployUrl is absolute or root relative, ignore baseHref & use deployUrl as is.
return `${deployUrl.replace(/\/$/, '')}${url}`;
} else if (baseHref.match(/:\/\//)) {
// If baseHref contains a scheme, include it as is.
return baseHref.replace(/\/$/, '') +
`/${deployUrl}/${url}`.replace(/\/\/+/g, '/');
} else {
// Join together base-href, deploy-url and the original URL.
// Also dedupe multiple slashes into single ones.
return `/${baseHref}/${deployUrl}/${url}`.replace(/\/\/+/g, '/');
}
}
}
]),
PostcssCliResources({
deployUrl: loader.loaders[loader.loaderIndex].options.ident == 'extracted' ? '' : deployUrl,
baseHref,
deployUrl,
loader,
filename: `[name]${hashFormat.file}.[ext]`,
}),
Expand Down Expand Up @@ -164,12 +98,11 @@ export function getStylesConfig(wco: WebpackConfigOptions) {

normalizeExtraEntryPoints(buildOptions.styles, 'styles').forEach(style => {
const resolvedPath = path.resolve(root, style.input);

// Add style entry points.
if (entryPoints[style.bundleName]) {
entryPoints[style.bundleName].push(resolvedPath)
entryPoints[style.bundleName].push(resolvedPath);
} else {
entryPoints[style.bundleName] = [resolvedPath]
entryPoints[style.bundleName] = [resolvedPath];
}

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

let dartSass: {} | undefined;
try {
// tslint:disable-next-line:no-implicit-dependencies
dartSass = require('sass');
} catch { }

let fiber: {} | undefined;
if (dartSass) {
try {
// tslint:disable-next-line:no-implicit-dependencies
fiber = require('fibers');
} catch { }
}

// set base rules to derive final rules from
const baseRules: webpack.Rule[] = [
const baseRules: webpack.RuleSetRule[] = [
{ test: /\.css$/, use: [] },
{
test: /\.scss$|\.sass$/,
Expand All @@ -212,9 +147,9 @@ export function getStylesConfig(wco: WebpackConfigOptions) {
sourceMap: cssSourceMap,
// bootstrap-sass requires a minimum precision of 8
precision: 8,
includePaths
}
}]
includePaths,
},
}],
},
{
test: /\.less$/,
Expand All @@ -224,23 +159,23 @@ export function getStylesConfig(wco: WebpackConfigOptions) {
sourceMap: cssSourceMap,
javascriptEnabled: true,
...lessPathOptions,
}
}]
},
}],
},
{
test: /\.styl$/,
use: [{
loader: 'stylus-loader',
options: {
sourceMap: cssSourceMap,
paths: includePaths
}
}]
}
paths: includePaths,
},
}],
},
];

// load component css as raw strings
const rules: webpack.Rule[] = baseRules.map(({ test, use }) => ({
const rules: webpack.RuleSetRule[] = baseRules.map(({ test, use }) => ({
exclude: globalStylePaths,
test,
use: [
Expand All @@ -250,50 +185,33 @@ export function getStylesConfig(wco: WebpackConfigOptions) {
options: {
ident: 'embedded',
plugins: postcssPluginCreator,
sourceMap: cssSourceMap ? 'inline' : false
}
sourceMap: cssSourceMap ? 'inline' : false,
},
},
...(use as webpack.Loader[])
]
...(use as webpack.Loader[]),
],
}));

// load global css as css files
if (globalStylePaths.length > 0) {
rules.push(...baseRules.map(({ test, use }) => {
const extractTextPlugin = {
return {
include: globalStylePaths,
test,
use: [
// style-loader still has issues with relative url()'s with sourcemaps enabled;
// even with the convertToAbsoluteUrls options as it uses 'document.location'
// which breaks when used with routing.
// Once style-loader 1.0 is released the following conditional won't be necessary
// due to this 1.0 PR: https://github.com/webpack-contrib/style-loader/pull/219
{ loader: buildOptions.extractCss ? RawCssLoader : 'raw-loader' },
buildOptions.extractCss ? MiniCssExtractPlugin.loader : 'style-loader',
RawCssLoader,
{
loader: 'postcss-loader',
options: {
ident: buildOptions.extractCss ? 'extracted' : 'embedded',
plugins: postcssPluginCreator,
sourceMap: cssSourceMap && !buildOptions.extractCss ? 'inline' : cssSourceMap
}
sourceMap: cssSourceMap && !buildOptions.extractCss ? 'inline' : cssSourceMap,
},
},
...(use as webpack.Loader[])
...(use as webpack.Loader[]),
],
// publicPath needed as a workaround https://github.com/angular/angular-cli/issues/4035
publicPath: ''
};
const ret: any = {
include: globalStylePaths,
test,
use: [
buildOptions.extractCss ? MiniCssExtractPlugin.loader : 'style-loader',
...extractTextPlugin.use,
]
};
// Save the original options as arguments for eject.
// if (buildOptions.extractCss) {
// ret[pluginArgs] = extractTextPlugin;
// }
return ret;
}));
}

Expand All @@ -309,6 +227,6 @@ export function getStylesConfig(wco: WebpackConfigOptions) {
return {
entry: entryPoints,
module: { rules },
plugins: extraPlugins
plugins: extraPlugins,
};
}
Loading

0 comments on commit 5007a19

Please sign in to comment.