【问题标题】:How to configure Typescript so it "knows about" my SystemJS paths?如何配置 Typescript 使其“​​了解”我的 SystemJS 路径?
【发布时间】:2017-01-25 08:32:42
【问题描述】:

目前我必须使用相对路径导入我的模块:

import {UserService} from "../../../services/user-service";

但是,我宁愿配置 SystemJS,以便解析从应用程序的根目录开始,除非模块路径以 ./ 开头,然后我可以这样做(services 位于根目录):

import {UserService} from "services/user-service";

如果我想从当前位置导入文件:

import {Something} from "./something";

我可以用 SystemJS 配置第一部分:

System.config({
    defaultJSExtensions: true,
    transpiler: false,
    paths: {
        "*": "dist/*",
        "services": "dist/services/*",
        "models": "dist/models/*",
        "github:*": "jspm_packages/github/*",
        "npm:*": "jspm_packages/npm/*"
    },
    // ...
}

不过……

  1. 我不确定如何让 Typescript 了解我的 SystemJS.paths 配置,并且
  2. 我不知道如何将 SystemJS 配置为“默认从根目录加载内容”。

【问题讨论】:

    标签: javascript typescript systemjs jspm


    【解决方案1】:

    一种解决方案是在 SystemJs 中配置一个包并为 typescript 添加路径映射。

    您可以通过在服务目录下添加一个 index.ts 文件来做到这一点,例如:

    export { UserService } from './user-service';
    export { OrderService } from './order-service';
    ...
    

    将以下内容添加到您的 SystemJs 配置中(参见:SytemJS config-api):

    SystemJS.config({
      ...
      packages: {
        "services": {
          "main": "index.ts"
        }
      }
    });
    

    将此添加到 tsconfig.json(参见:Typescript module resolution):

    {
      "compilerOptions": {
      {
        ...
        "moduleResolution": "Node",
        "baseUrl": ".",
        "paths": {
          "services": [ "services" ]
        }
      }
    }
    

    现在您可以导入如下文件:

    import { UserService } from 'services';
    

    这将在 Visual Studio 中提供智能感知并允许在浏览器中加载模块。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-27
      • 2021-11-23
      • 2017-09-05
      • 1970-01-01
      • 2017-03-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多