Angular - What is the meanings of module.id in com

2019-01-05 08:41发布

In an Angular app, I have seen that @Component has property moduleId. What does it mean?

And when module.id is not defined anywhere, the app still works. How can it still work?

@Component({
  moduleId: module.id,
  selector: 'ng-app',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.css'],
  directives: [AppComponent]
});

8条回答
倾城 Initia
2楼-- · 2019-01-05 09:40

In addition to the great explanations from echonax and Nishchit Dhanani I want to add, that I really hate population of components with module.id. Especially, if you have support for the (Ahead-of-Time) AoT-compilation and for a realistic project this is what you should aim for, there is no place for something like module.id in your component metadata.

From the Docs:

JiT-compiled applications that use the SystemJS loader and component-relative URLs must set the @Component.moduleId property to module.id. The module object is undefined when an AoT-compiled app runs. The app fails with a null reference error unless you assign a global module value in the index.html like this:

<script>window.module = 'aot';</script>

I think having this line in the production version of the index.html file is absolutely not acceptable!

Therefore, the goal is to have have (Just-in-Time) JiT-compilation for development and AoT support for production with the following component metadata definition: (without moduleId: module.id line)

@Component({      
  selector: 'my-component',
  templateUrl: 'my.component.html', <- relative to the components current path
  styleUrls:  ['my.component.css'] <- relative to the components current path
})

At the same time I would like to place styles, like my.component.css and template files, like my.component.html relative to the component my.component.ts file paths.

To achieve all this, the solution I am using is to host web server (lite-server or browser-sync) during development phase from multiple directory sources!

bs-config.json:

{
  "port": 8000,
  "server": ["app", "."]
}

Please take a took at this answer for me details.

The exemplary angular 2 quick start project, which relies on this approach is hosted here.

查看更多
Ridiculous、
3楼-- · 2019-01-05 09:41

As per Angular doc, You should not use @Component({ moduleId: module.id })

Please ref : https://angular.io/docs/ts/latest/guide/change-log.html

Here is the relevant text from that page:

All mention of moduleId removed. "Component relative paths" cookbook deleted (2017-03-13)

We added a new SystemJS plugin (systemjs-angular-loader.js) to our recommended SystemJS configuration. This plugin dynamically converts "component-relative" paths in templateUrl and styleUrls to "absolute paths" for you.

We strongly encourage you to only write component-relative paths. That is the only form of URL discussed in these docs. You no longer need to write @Component({ moduleId: module.id }), nor should you.

查看更多
登录 后发表回答