Angular2:模块未正确导入

时间:2016-04-21 09:57:26

标签: typescript angular

我遵循Tour of Heroes教程,一切正常,除了一件事:当我导入自定义模块时,我必须使用.js扩展名声明导入,否则我得到了404:

//This works fine
import {Component} from 'angular2/core';

//This gives me a 404 module not found (http://localhost:3000/assets/html/app/hero)
import {HeroDetailComponent } from './hero-detail.component';

//This works fine but the editor (VS Code) don't like it
import {HeroDetailComponent } from './hero-detail.component.js';

我错过了什么吗?

2 个答案:

答案 0 :(得分:1)

您可以添加到System.config中的defaultJSExtensions设置。

From the documentation:

System.defaultJSExtensions = true;

// requests ./some/module.js instead
System.import('./some/module');

您还可以设置包的defaultExtension。

Again, from the documentation:

System.config({
  packages: {
    // meaning [baseURL]/local/package when no other rules are present
    // path is normalized using map and paths configuration
    'local/package': {
      main: 'index.js',
      format: 'cjs',
      defaultExtension: 'js',
      map: {
        // use local jquery for all jquery requires in this package
        'jquery': './vendor/local-jquery.js',

        // import '/local/package/custom-import' should route to '/local/package/local/import/file.js'
        './custom-import': './local/import/file.js'
      },
      meta: {
        // sets meta for modules within the package
        'vendor/*': {
          'format': 'global'
        }
      }
    }
  }
});

答案 1 :(得分:0)

感谢@JSess指出我正确的方向,我发现我的配置错误,因为包下的属性实际上是模块的路径:

System.config({
        packages: {
          //THIS IS THE WRONG PATH
          'app': {
            format: 'register',
            defaultExtension: 'js'
          }
        }
      });

我只需要更改包下的属性以反映模块的实际路径:

System.config({
        packages: {
          'assets/html/app': {
            format: 'register',
            defaultExtension: 'js'
          }
        }
      });