angular - 如何配置我的 Angular 应用程序以使用 CLI 进行生产并使用 JIT 进行开发?

标签 angular angular-cli angular-jit

目标

有了一个统一的代码库,我希望能够...

  1. 使用 CLI 编译并使用生成的捆绑文件为整个应用提供服务
  2. 使用 JIT 编译并为应用程序提供服务,每个文件都有自己的网络请求(无捆绑)

当前尝试

到目前为止,我已经为每个构建创建了单独的 tsconfig 文件。

我的主要困难是在组件中设置 templateUrl 的路径

CLI默认使用templateUrl的相对路径,而JIT需要组件上设置的moduleId才能使用相对路径。

例如

@Component({
  selector: 'app-root',
  moduleId : module.id,
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.less']
})

... 适用于开发模式 (commonjs),但不适用于生产模式 (CLI),并出现以下错误:

Cannot find name 'module'. Do you need to install type definitions for node? Try npm i @types/node.

虽然删除 module.id 适用于 CLI,但不适用于 commonjs。在这种情况下,浏览器无法找到 html 文件,因为它正在源代码根目录中查找。

我试过了..

  • (有保留)安装节点类型
  • 任意转换“模块”
  • “模块”的环境声明,
    • 声明常量模块:{id: any};
  • 将模块包装在一个函数中,该函数仅在 commonjs 场景中有条件地求值
    • moduleId : environment.bundled ?未定义:(() => module.id)()

并且由于不同的原因都失败了。

如有任何关于此方法或新方法的建议,我们将不胜感激。

最佳答案

最后,我发现 vsCode 在这方面比 tsc 或 CLI 更严格,我能够做到这一点

  1. .d.ts 文件中声明模块
  2. 将它添加到 CLI(prod)版本的 tsconfig 中的我的类型中,
  3. 在 JIT(开发)版本的 tsconfig 中排除它..

src/ambient.d.ts

declare var module: {id: string};

tsconfig-cli.json

{
    "compileOnSave": false,
    "compilerOptions": {
        ...
        "module": "es2015",
        "moduleResolution": "node",
        ...
        "types": [
            "src/ambient.d.ts"
        ]
    }
}

tsconfig-dev.json

{
    "compilerOptions": {
        ...
        "module": "commonjs",
        "moduleResolution": "node",
        ...
    },
    ...
    "exclude":[
      "src/main/main.ts",
            "src/ambient.d.ts"
    ]
}

关于angular - 如何配置我的 Angular 应用程序以使用 CLI 进行生产并使用 JIT 进行开发?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55854688/

相关文章:

angular - 基于 angular 9 迁移的 angular 生产问题

javascript - Angular 属性在类型 'Window' 上不存在

angular - 在 express 和 angular 之间共享接口(interface) interface/model 文件

Angular CDK : Apply animations to Angular custom stepper on step change

angular - 您将如何使用 Angular 2 管理用户角色和权限

Angular + Electron - 应用程序在刷新或更改时中断

javascript - 检测单词和句子的完成情况

angular - 缺少 *.ts 文件(由于 `npm link`?)