【问题标题】:tsc - doesn't compile alias pathstsc - 不编译别名路径
【发布时间】:2020-03-29 11:28:42
【问题描述】:

我有打字稿并使用别名。 这是 tsconfig.json 的一部分

"compilerOptions": {
  "baseUrl": "./src",
   ...
},

通过设置base url,我可以改变

import User from "src/models/User.model.ts"

import User from "models/User.model.ts"

问题是 tsc 将 src 文件夹编译为 dist 文件夹,因此用户导入路径应更改为相对路径,如下所示:

"../models/User.model.js"

但它没有改变,所以我收到以下错误:

"models/User.model.js" not found

我搜索了答案,但没有运气。

【问题讨论】:

    标签: typescript tsc tsconfig tsconfig-paths


    【解决方案1】:

    关于这方面的打字稿问题讨论了很长时间,我似乎找不到比这更好的解决方案。

    发展

    npm i -save-dev tsconfig-paths/register
    

    tsconfig.json

    {
     "compilerOptions": {
        "baseUrl": ".",
        "paths": {
          "@src/*": ["src/*"],
        },   
      }
    }
    

    package.json

    "scripts": {
      dev: "ts-node -r tsconfig-paths/register src/index.ts"
    }
    

    构建

    npm i -save-d ttypescript @zerollup/ts-transform-paths
    

    tsconfig.json

    {
     "compilerOptions": {
        "baseUrl": ".",
        "paths": {
          "@src/*": ["src/*"],
        },
        "plugins": [
          {
              "transform": "@zerollup/ts-transform-paths",
          }
        ]
      }
    }
    

    package.json

    "scripts": {
      build: "ttsc -P ./tsconfig.json"
    }
    

    【讨论】:

      【解决方案2】:

      ttypescript

      typescript-transform-paths

      babel-plugin-module-resolver

      package.json 部分

      "build": "ttsc && babel dist -d dist",
      

      ttsc 不是错误,它是 typescript 配置之上的插件,用于更复杂的转译

      tsconfig.json 部分

      "outDir": "dist",
      "baseUrl": "./",
      "paths": {
          "@/*": [
              "./src/*"
          ],
          "$/*": [
              "./tests/unit/*"
          ]
      },
      "plugins": [
          {
              "transform": "typescript-transform-paths",
              "afterDeclarations": true
          }
      ],
      

      .babelrc全部内容

      {
        "compact": false,
        "retainLines": true,
        "minified": false,
        "inputSourceMap": false,
        "sourceMaps": false,
        "plugins": [
          [
            "module-resolver",
            {
              "root": ["./dist"],
              "alias": {
                "@": "./dist"
              }
            }
          ]
        ]
      }
      
      

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-23
      • 1970-01-01
      • 1970-01-01
      • 2019-12-22
      相关资源
      最近更新 更多