微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在打字稿中进行模块解析以输出节点?

如何解决如何在打字稿中进行模块解析以输出节点?

tsconfig.json

{
  "compilerOptions": {
    "baseUrl": "./","allowJs": false,"strict": true,"target": "es6","module": "commonjs","lib": ["dom","es6","es5","es2017","esnext.asynciterable"],"sourceMap": true,"moduleResolution": "node","paths": {
      "src/*": ["src/*"]
    },"declaration": true,"rootDir": "./src","outDir": "dist"
  },"exclude": ["dist"],"include": [ "src"]
}

原始文件夹结构

src /
  util/
    getSomething.ts
  index.ts

输出文件夹结构

dist /
  util/
    getSomething.js
  index.js

index.ts

import getSomething from 'src/util/getSomething';

package.json 脚本

{
"build": "tsc && tspath -f","start": "node dist/index.js"
}

构建有效,但是当我开始运行时出现错误。 有没有办法获得基于根的模块解析? 我按照这个例子(只是用 src 替换 ~ ),它给了我这个问题。 除非有替代 tspath 的解决方案。 https://haseebmajid.dev/blog/better-imports-with-babel-tspath

注意:我使用的是 Windows 10。

npm start

错误:找不到模块“./src\util\getSomething” 需要堆栈: c:\apps\example-typescript-node\dist\index.js

解决方法

在这里回答: https://github.com/duffman/tspath/issues/33

我已经解决了我的问题。我必须确保我的 rootDir 是 ./ 不是 src。 然后在 dist/src/ 内定位 index.js,而不是 dist/

tsconfig.json

{
  "compilerOptions": {
    "rootDir": "./"
  }
}

package.json

{
"build": "tsc && tspath -f","start": "node dist/src/index.js"
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。