我正在运行VS Code,目前正在尝试在我的打字稿项目中设置一些别名。
我的开发设置基于nodemon和ts-node,代码被编译到dist文件夹中。
到目前为止,我成功获得Typescript Hero来使用别名管理导入:
到目前为止,我的文件夹结构是:
.
└─┬ src
├──modules
├────Category
├────Ressource
├──shared
├────debug
// tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"moduleResolution": "node",
"pretty": true,
"sourceMap": true,
"target": "es6",
"outDir": "./dist",
"baseUrl": "./src",
"paths": {
"@shared/*": [
"shared/*"
],
"@modules/*": [
"modules/*"
]
},
"resolveJsonModule": true,
"esModuleInterop": true
},
"include": [
"src/**/*.ts"
],
"exclude": [
"node_modules",
"**/*.spec.ts",
"**/*.test.ts",
]
}
这是第一个别名导入失败。
//Server.ts file
import Print from '@shared/debug/Print.class';
import App from './App';
const MyApp: App = new App();
MyApp.ExpressApp.listen(MyApp.Config.ExpressPort, () => {
Print.Log('Express server listening on port ' + MyApp.Config.ExpressPort);
});
但是,我得到一个错误:“跨环境NODE_ENV =开发节点mon ts-node ./src/server.ts”上的“找不到模块'@ shared / debug / Print.class' ”。
这就是我的立场。
现在,我已经阅读了一些关于SO的问答,而且似乎即使我设法使别名在dev中工作时也可以在生产中失败,因为我是从Typescript src文件夹运行的,而我的可交付成果则是在dist中构建的?如果是这样,有什么办法可以补救?非常感谢
问题出在运行时的节点路径别名解析上。即使打字稿是由ts-node在运行时执行的,别名也无法按原样解析。(我认为)
但这只是冰山一角。我稍后会在jest设置中和JS运行时遇到它。
对于每个运行时,我都必须找到一种解释别名的方法。有一些npm软件包,但是很多需要更多的声明。
而且我不想在我拥有的每个配置文件中声明别名,而只依赖于tsconfig文件。
经过大量测试后,只有两个节点模块可以安装tsconfig-paths以便在ts-node上执行打字稿运行时。然后@ ef-carbon / tspm将我的别名转换为构建目标。
npm i -D tsconfig-paths @ef-carbon/tspm
对于ts-node,脚本被修改为:
ts-node -r tsconfig-paths/register ./src/server.ts
对于您的js编译,只需运行:
ef-tspm
就开玩笑而言,ts-jest是必需的,我已经有了它,但配置不正确。我使用内置的助手来设置我的路径。我的笑话配置文件现在看起来像这样:
//jest.config.js
const { pathsToModuleNameMapper } = require('ts-jest/utils');
const { compilerOptions } = require('./tsconfig');
module.exports = {
roots: ['<rootDir>/src'],
globals: {
'ts-jest': {
tsConfig: 'tsconfig.json',
diagnostics: {
warnOnly: true,
},
},
},
clearMocks: true,
coverageDirectory: 'coverage',
testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$',
moduleFileExtensions: ['js', 'json', 'jsx', 'node', 'ts', 'tsx'],
testEnvironment: 'node',
moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths, { prefix: '<rootDir>/src/' }),
pathToJest: 'npm test',
preset: 'ts-jest',
testMatch: null,
};
这是我的脚本在package.json中的样子
"scripts": {
"dev:ts": "cross-env NODE_ENV=development nodemon",
"dev:js": "cross-env NODE_ENV=development npm run start:js",
"staging": "cross-env NODE_ENV=staging npm run start:js",
"production": "cross-env NODE_ENV=production npm run start:js",
"test": "cross-env NODE_ENV=testing jest --runInBand",
"test:debug": "npm run test --detectOpenHandles",
"start:js": "npm run build && nodemon --config nodemon-js.json",
"build": "npm run compile && npm run post:compile && npm run copyAssets",
"compile": "tsc",
"post:compile": "ef-tspm",
"copyAssets": "copyfiles -e ./src/**/*.ts -e ./src/**/*sample* -e ./src/**/*.json -u 1 ./src/**/* ./dist/"
},
看看进展如何,之后我可能会添加一个咕unt咕gu的解决方案。但是就目前而言,这已经足够了。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句