Angular Ivy构建环境下实现动态编译的解决方案咨询
Angular 12+ Ivy环境下使用动态编译功能的解决方案
你遇到的报错是Angular官方的强制限制:
Project is attempting to disable the Ivy compiler. Angular versions 12 and higher do not support the deprecated View Engine compiler for applications. The Ivy compiler will be used to build this project.
Angular 12及以上版本已经完全移除了已废弃的View Engine编译器支持,无法通过配置降级到View Engine,可通过以下配置在Ivy环境下保留动态编译的JIT能力,适配你使用的angular-compile包:
操作步骤
- 移除
tsconfig.json中angularCompilerOptions节点下的"enableIvy": false配置,该参数在高版本Angular中强制为true,添加该参数会触发上述警告。 - 确保项目中
@angular/core、@angular/common、@angular/compiler、@angular/platform-browser-dynamic的版本完全一致,避免版本不兼容导致的编译器异常。 - 在应用根模块(通常为
AppModule)的providers数组中添加JIT编译器的全局注入配置:
import { Compiler, COMPILER_OPTIONS, CompilerFactory } from '@angular/core'; import { JitCompilerFactory } from '@angular/platform-browser-dynamic'; export function createCompiler(compilerFactory: CompilerFactory): Compiler { return compilerFactory.createCompiler(); } @NgModule({ // ... 其他原有配置 providers: [ { provide: COMPILER_OPTIONS, useValue: {}, multi: true }, { provide: CompilerFactory, useClass: JitCompilerFactory, deps: [COMPILER_OPTIONS] }, { provide: Compiler, useFactory: createCompiler, deps: [CompilerFactory] } ] }) export class AppModule { }
- 如果需要在生产环境使用动态编译,修改
angular.json配置,在projects.<你的项目名>.architect.build.options.scripts数组中添加编译器依赖:
"scripts": [ "node_modules/@angular/compiler/bundles/compiler.umd.js" ]
- 生产环境构建时,保持默认的AOT编译配置即可,上述配置会在AOT构建产物中注入JIT运行时编译器,不需要全局切换到JIT构建模式。
注意事项
- 引入JIT编译器会使生产包体积增加约2-3M,可根据业务场景按需调整。
- 所有动态编译用到的自定义组件、指令、管道,需要提前在对应的模块中声明或导入,否则Ivy运行时无法识别自定义语法。
- 若使用动态渲染的模板中包含第三方UI库的组件,需要将对应UI库的模块导入到动态编译的模块中,不可省略。
内容的提问来源于stack exchange,提问作者Patrik Laszlo
相关产品推荐
相关产品推荐

