node.js - 将 tsconfig 中定义的路径扩展到已编译的 JavaScript 中
我正在使用 TypeScript 编写一个 Node 库,并在我的 tsconfig.json 中启用了路径,如下所示。
当我使用 tsc 编译我的代码(使用 npm run tscompile)时,TypeScript 可以编译,并且我可以在 ./dist/ 文件夹中看到相应的 JS。但 JavaScript 仍然包含路径,例如 const logger_1=__importDefault(require("@logging/logger"));。如果我尝试运行 JavaScript,它会失败,因为它无法识别这些路径。
我在 JavaScript 中扩展路径时,哪里/什么地方遗漏了?
对于我的 Jest 测试,我正在使用模块名称映射器来扩展测试路径,这有效,但我的主线编译代码怎么办?
tsconfig.json:
{
"compileOnSave": true,
"compilerOptions": {
"module": "commonjs",
"target": "ES2020",
"declaration": true,
"outDir": "./dist",
"esModuleInterop": true,
"rootDir": ".",
"baseUrl": ".",
"sourceMap": true,
"paths": {
"@logging/*": ["src/logging/*"],
"@validation/*": ["src/validation/*"],
"@util/*": ["src/util/*"],
"@test-helpers/*": ["test/helpers/*"]
}
},
"include": [
"src/**/*", "test/**/*"
]
}
package.json:
"scripts": {
"test": "jest --coverage",
"lint": "eslint ./src/",
"lint-tests": "eslint ./test/",
"lint-all": "eslint ./src/ && eslint ./test/",
"tscompile": "tsc",
"lic-report-prod": "license-checker --production --json --out ./report/license/license-prod.json"
},
`jest.config.ts:`
const tsconfig = require("./tsconfig.json");
// use tsconfig-paths-jest tool to automatically map modules based on tsconfig.json paths config
const moduleNameMapper = require("tsconfig-paths-jest")(tsconfig);
module.exports = {
transform: {
"^.+\\.ts?$": "ts-jest",
},
testEnvironment: "node",
testRegex: ".*.test.ts$",
moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"],
moduleNameMapper,
};