在Angular2(TS)中导入模块的选项 [英] Options for importing modules in Angular2 (TS)

查看:100
本文介绍了在Angular2(TS)中导入模块的选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有些进展或至少有计划(#5093 #5728 )以改善打字稿的模块路径映射,但我想知道目前我们有哪些选择( Angular2 beta.1,TypeScript 1.7,VS Code 0.10.5,nodejs 5.4,systemjs 0.19).

I know there's some progress or at least plans (#5093, #5728) to improve typescript's module paths mapping, but I was wondering what are our options at this moment (Angular2 beta.1, TypeScript 1.7, VS Code 0.10.5, nodejs 5.4, systemjs 0.19).

为了使每个人都开心(编译器,编辑器和浏览器),我使用以下语法导入模块:

In order to make everyone happy (compiler, editor and browser) I'm using following syntax to import modules:

// C:/~somepath~/project_name/src/scripts/app/components/search/search.component.ts
import {Component} from 'angular2/core';
import {EmitterService} from '../../../core/services/emitter/emitter.service';
import {SearchService} from '../../../app/services/search/search.service';

编译为

System.register(['angular2/core', '../../../core/services/emitter/emitter.service'], function(exports_1) {

当我使用以下选项时

// tsconfig.json
{
  "compilerOptions": {
    "target": "ES5",
    "module": "system",
    "moduleResolution": "node"
    ...
  }  
}

我想使用没有所有这些点的导入:

I'd like to use imports without all those dots:

import {EmitterService} from 'core/services/emitter/emitter.service';

因为它变得越来越丑陋,难以追踪,并且噩梦四处移动模块.由于systemjs配置,它可以在浏览器中工作:

since it's getting pretty ugly, crazy to track and a nightmare to move modules around. It works in a browser because of the systemjs configuration:

// system.conf.js
System.config({
  map: {
    app: "/scripts/app",
    core: "/scripts/core",
  }
}

并且我可以欺骗"通过在tsconfig.json中添加"isolatedModules": true来编译该编译器(没有此操作会引发错误),但是在Visual Studio Code中,Cannot find module错误仍然存​​在,并且我丢失了代码提示.我听说在node_modules文件夹中有一些键入解决方案,但是找不到任何可行的示例.

and I can "trick" the compiler by adding "isolatedModules": true to tsconfig.json (without this it throws an error), but in Visual Studio Code the Cannot find module error persists and I lose code-hinting. I heard there are some solutions with typings in node_modules folder, but wasn't able to find any working examples.

谢谢.

推荐答案

只是为了跟进将来的访问者,应该在TypeScript 2.0中解决此问题.您要查找的配置是在tsconfig.json中设置baseUrlpaths属性.如果您无条件地希望将所有内容都匹配到scripts中的某个路径,请使用类似以下内容的

Just to follow up to future visitors, this should be fixed in TypeScript 2.0. The configuration that you're looking for is to set the baseUrl or paths properties in your tsconfig.json. If you unconditionally want to match everything to some path in scripts, use something like:

{
    "baseUrl": "./src/scripts"
}

如果您只想专门使用coreapp,请使用

If it's only core and app that you want to use specially, use

{
    "baseUrl": "./src/scripts",
    "paths": {
        "app/*": ["app/*"],
        "core/*": ["core/*"]
    }
}

这篇关于在Angular2(TS)中导入模块的选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆