在我的 Express 项目中,我从类似 @common/foo
的路径导入.感谢 paths
在 tsconfig.json
,它只是 ../common/src/foo
的别名.这太棒了,并且可以在 nodemon.json
中使用此脚本进行开发:
{
"watch": ["src", "../common/src"],
"ext": "ts",
"ignore": ["src/public"],
"exec": "ts-node -r tsconfig-paths/register src/index.ts"
}
问题是我不能让它在生产模式下工作。
我用
tsc
构建项目,如果我检查生成的文件,它们会从 @common/
导入内容而不是来自 ../common/src/
.一开始我觉得还好,因为tsconfig-paths
在运行时工作,所以我只需要将它包含在 start
中脚本如下:node -r tsconfig-paths/register dist/index.js
不幸的是它没有用,我得到了那些
Cannot find module '@common/foo
控制台中的错误消息。有什么问题?我配置错了吗?
我的
package.json
(删除所有不相关的部分):{
"main": "index.js",
"scripts": {
"start": "cross-env NODE_ENV=prod node dist/index.js",
"build": "rimraf ./dist/ && cross-env NODE_ENV=prod tsc"
},
"dependencies": {
"express": "^4.17.1"
},
"devDependencies": {
"@types/express": "^4.17.4",
"@types/node": "^13.11.0",
"cross-env": "^6.0.3",
"rimraf": "^3.0.2",
"ts-node": "^8.8.2",
"tsconfig-paths": "^3.9.0",
"typescript": "^3.8.3"
}
}
我的
tsconfig.json
(删除所有不相关的部分):{
"compilerOptions": {
"module": "commonjs",
"baseUrl": "./",
"outDir": "dist",
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"noImplicitAny": false,
"target": "es6",
"emitDecoratorMetadata": true,
"moduleResolution": "node",
"importHelpers": true,
"types": [
"node"
],
"typeRoots": [
"node_modules/@types"
],
"paths": {
"@common/*": [
"../common/src/*"
]
}
},
"include": [
"./src/**/*.ts"
],
"exclude": [
"./src/dist/"
],
"references": [
{
"path": "../common"
}
]
}
最佳答案
对于仍然坚持这一点的人:
node -r ts-node/register/transpile-only -r tsconfig-paths/register dist/index.js
这是你需要做的。
关于node.js - tsc 后来自 tsconfig.json 的路径不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61342753/