【问题标题】:baseUrl of tsconfig.json does not worktsconfig.json 的 baseUrl 不起作用
【发布时间】:2018-03-23 04:21:45
【问题描述】:

我的项目结构是 源/ 客户/ 模块/ 服务器/ app.ts


src/
  client/
  modules/
    DB/
  server/
    app.ts
tsconfig.json

我在 app.ts 文件中使用非相对导入来导入模块

import * as DB from '@modules/DB';

因为我不想使用from "../modules/DB"

我的 tsconfig.json 是

{
"compileOnSave": true,
"compilerOptions": {
    "module": "commonjs",
    "target": "ES6",
    "noImplicitAny": true,
    "sourceMap": true,
    "preserveConstEnums": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": true,
    "traceResolution": true,
    "rootDir": "./src",
    "outDir": "./dist",
    "declaration": true,
    "typeRoots": [
        "/"
    ],
    "baseUrl": "./src",
    "paths": {
        "@modules/*": [
            "modules/*"
        ]
    }
},
"exclude": [
    "src/client/"
]

}

当我跟踪分辨率时,得到了这个

======== Module name '@modules/DB' was successfully resolved to '/Users/pengju/projects/pomelo-ts-starter/src/modules/DB/index.ts'. ========

好像导入成功了

但是编译的时候vscode还是出错了

[ts] Cannot find module '@modules/DB'. 

import * as DB from '@modules/DB'; 在 app.ts 中

然后我检查编译的 app.js, 找到const DB = require("@modules/DB");

baseUrl 和路径选项,不能将“@modules/DB”更改为“../modules/DB”吗?那么,他们是做什么的呢?

【问题讨论】:

    标签: typescript tsconfig


    【解决方案1】:

    这里的问题是 TypeScript 编译器不会更新您的 JS 文件中的路径,并且 JavaScript 引擎对您的 TypeScript 配置一无所知,您在 tsconfig 中指定的内容仅在您编译时使用“编译时间” TypeScript 到 JS 你需要做和 TS 编译器一样的工作,但是把解析的路径保存在 JS 文件中。

    简单地说,所有的JS文件都需要处理,别名替换为“真实”路径。

    人们经常建议 WebPack 这是一个怪物,有一个非常简单的工具叫做 tspath 你在你的项目目录中运行它,它会读取你的 tsconfig.json 并相应地更新 JS 源文件!

    安装 tspath 一个用于解析 ts 路径的 npm 工具注意:tspath 需要最新版本的节点!

    npm install -g tspath
    

    运行 TypeScript 编译器后,从项目目录运行:

    tspath
    

    tspath -f
    

    跳过提示!

    阅读更多:https://www.npmjs.com/package/tspath

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-27
      • 2021-11-05
      • 2018-07-26
      • 1970-01-01
      • 2018-01-21
      • 2018-11-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多