使用带有Angular 13和Webpack的ifdef加载程序进行条件编译



我有一个Ionic应用程序,它严重依赖于条件编译,在条件编译中,我基于一组类似于m4工作方式的配置值来包含或排除代码块。

我一直在使用https://github.com/nippur72/ifdef-loader成功地实现了这一目的。

我现在面临着将这个应用程序从Angular 10升级到13(Ionic 5到6(的问题。

ifdef加载程序在Angular 10中并不是开箱即用的,而是一个补丁(https://gist.github.com/tristanidoux/892469f2c345bd6c6551eb19c705a016)到@angular dev-kit允许它运行。

这个补丁不适用于Angular 13,因为所有的文件都已经更改,并且我已经尽可能多地浏览了源代码。我还不知道如何为Angular 13创建类似的补丁。

所以我一直在尝试使用"@angular builders/custom webpack":"13.0.0〃;使用https://medium.com/angular-in-depth/customizing-angular-cli-build-an-alternative-to-ng-eject-v2-c655768b48cc作为向导。

我有以下基于ifdef加载器文档的custom.webpack.config.js文件:

// ifdef-loader config
const opts = {
APP: false,
WEB: true,
DEBUG: true,
version: 3,
"ifdef-verbose": true,                 // add this for verbose output
"ifdef-triple-slash": true,           // add this to use double slash comment instead of default triple slash
"ifdef-fill-with-blanks": true,         // add this to remove code with blank spaces instead of "//" comments
"ifdef-uncomment-prefix": "// #code "  // add this to uncomment code starting with "// #code "
};
module.exports = {
module: {
rules: [
{
test: /.tsx?$/,
exclude: /node_modules/,
use: [
{ loader: 'ts-loader' },
{ loader: 'ifdef-loader', options: opts }
]
}
]
},

不幸的是,如果没有调用def加载程序,这似乎就不起作用。

所以三个问题:

  1. 我在配置中是否犯了一些明显的错误?

  2. 有人让ifdef加载程序与Angular 13一起工作吗?如果是,如何?

  3. 或者,对于Angular 13项目中有条件地包含/排除代码块,是否有其他解决方案?

如有任何意见或建议,我们将不胜感激。

如果将webpack配置导出为webpack.config.js中的函数,则有效:

module.exports = (config, options, targetOptions) => {
const ifdef_opts = {
DEBUG: config.mode === 'development',
version: 3,
"ifdef-verbose": true,                 // add this for verbose output
"ifdef-triple-slash": false,           // add this to use double slash comment instead of default triple slash
"ifdef-fill-with-blanks": true,         // add this to remove code with blank spaces instead of "//" comments
"ifdef-uncomment-prefix": "// #code "  // add this to uncomment code starting with "// #code "
};
config.module.rules.some(({test, use}) => {
if (use && test && 'dummy.ts'.match(test)) {
use.push({
loader: "ifdef-loader",
options: ifdef_opts
})
return true;
}
return false;
})
return config;
};

一周后,我一直无法确定如何在Angular的webpack实现中的typescript编译管道中插入模块,所以我选择为@Angular devkit/build-Angular/@ngtools/webpack创建一个补丁,直接调用ifdef-loader。

此处的补丁:Angular Webpack补丁

它很难看,但很管用。

最新更新