Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
645 views
in Technique[技术] by (71.8m points)

typescript - Angular 2 / 4 / 5 - Ahead-of-time compilation how to

I'm trying to bootstrap my Angular 2 RC5 application following this guide https://angular.io/docs/ts/latest/guide/ngmodule.html Below is my code

import { AppModuleNgFactory } from './app.module.ngfactory';
import {platformBrowser} from "@angular/platform-browser";

platformBrowser().bootstrapModuleFactory(AppModuleNgFactory);

However , when I tried to compile typescript code, I got the following error

appmain.ts(1,36): error TS2307: Cannot find module './app.module.ngfactory'.

How can I generate the app.module.ngfactory file? Which tool should I use?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Both the JIT and AOT compilers generate an AppModuleNgFactory class from the same AppModule source code.

The JIT compiler creates that factory class on the fly, in memory, in the browser. The AOT compiler outputs the factory to a physical file that we're importing here in the static version of main.ts

At a high level, @angular/compiler-cli provides a wrapper around Typescript’s tsc compiler, and both AoT compiles your application’s code, and then transpiles your application’s Typescript to Javascript:

$ ngc -p src

This generates a new file for each component and module ( called an NgFactory )

To run your app in AoT mode, all that’s required is changing your main.ts file from

import {platformBrowserDynamic} from ‘@angular/platform-browser-dynamic’
import {MyAppModule} from ‘./app’
platformBrowserDynamic().bootstrapModule(MyAppModule);

to

import {platformBrowser} from ‘@angular/platform-browser’
import {MyAppModuleNgFactory} from ‘./app.ngfactory’ //generated code
platformBrowser().bootstrapModuleFactory(MyAppModuleNgFactory);

EDIT:

To use ngc command, first install these-

$ npm install @angular/compiler-cli typescript@next @angular/platform-server @angular/compiler

ngc is a drop-in replacement for tsc which you will find it in- ./node_modules/.bin/ngc folder.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...