安装自定义用的插件
npm i -D @angular-builders/custom-webpack @angular-builders/dev-server postcss-px-to-viewport
检查一下@angular-builders的主版本号(7.x.x)是不是和我们的@angular/cli主版本一致,这里用angular7来示范。
修改angular.json文件,全局搜索
@angular-devkit/build-angular:browser
替换为
@angular-builders/custom-webpack:browser
在@angular-builders/custom-webpack:browser
同级的options选项里添加
"customWebpackConfig": {
"path": "./webpack.config.js"
},
全局搜索
@angular-devkit/build-angular:dev-server
替换为
@angular-builders/dev-server:generic
在angular.json同级目录下新增webpack.config.js,内容如下
var pxtoviewport = require('postcss-px-to-viewport');
function regexEquals(firstValue,secondValue){
return firstValue+'' == secondValue +'';
}
const addPostCssPlugins = [//自定义的postcss插件
pxtoviewport({
viewportWidth: 750,
viewportHeight: 1334,
unitPrecision: 5,
viewportUnit: 'vw',
selectorBlackList: [],
minPixelValue: 1,
mediaQuery: false
})
]
module.exports = (config, options) => {
// console.log(config.module.rules);
let rules = config.module.rules;
let styleRules = rules.filter(rule => {
let test = rule.test;
return regexEquals(test,/\.css$/)|| regexEquals(test,/\.scss$|\.sass$/)|| regexEquals(test,/\.less$/)|| regexEquals(test,/\.styl$/);
});
console.log(styleRules)
styleRules.forEach(rule => {
// console.log(rule);
let currentPostCssLoader = rule.use.find(loader => loader.loader==='postcss-loader');
let getPluginsFn = currentPostCssLoader.options.plugins;
let getPluginsAddedFn = (loader)=>{
return [...getPluginsFn(loader),...addPostCssPlugins];
}
currentPostCssLoader.options.plugins = getPluginsAddedFn;
// console.log(typeof currentPostCssLoader.options.plugins)
// console.log(currentPostCssLoader.options.plugins())
// currentPostCssLoader.options.plugins.push(...addPostCssPlugins);
})
return config;
};
然后,运行npm start,运行ng build --prod试验下效果,你会看到我们自定义的postcss插件已经起作用了。
附录:https://github.com/angular/angular-cli/blob/master/packages/angular_devkit/build_angular/src/angular-cli-files/models/webpack-configs/styles.ts