angularangular-cliangular-jit

How can I configure my Angular app to use CLI for production and JIT for development?


goal

With one unified code base, I want to be able to...

  1. compile with CLI and serve the entire app with the resulting bundled files
  2. use JIT compilation and serve the app with each file having it's own network request (no bundling)

current attempt

So far, I have created separate tsconfig files for each build.

My primary difficulty is setting paths for templateUrl in components.

CLI uses relative paths for templateUrl by default, while JIT needs the moduleId set on the component to use relative paths.

e.g.

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

... works for dev mode (commonjs), but fails for prod mode (CLI) with the following error:

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

While removing the module.id works with the CLI, but not the commonjs. In that case, the browser can not find the html file because it is looking in the source root.

I have tried..

and all have failed for different reasons.

Any suggestion on this approach or a new approach will be most appreciated.


Solution

  • In the end, I found that vsCode was being more restrictive than tsc or CLI for that matter, and I was able to just

    1. declare module in a .d.ts file,
    2. add it to the to my types in the tsconfig for the CLI (prod) version and
    3. exclude it in the tsconfig for the JIT (dev) version..

    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"
        ]
    }