![](/img/trans.png)
[英]Wrong build in dist/ folder when server imports module from external folder
[英]Built TypeScript application imports from wrong, src instead of dist, folder
TLDR; 应用程序构建但尝试从 src 文件夹而不是 dist 导入文件
我有一个使用 TypeScript 构建的 Express 应用程序。
这是 tsconfig.json
{
"compilerOptions": {
"target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
"sourceMap": true, /* Generates corresponding '.map' file. */
"outDir": "dist", /* Redirect output structure to the directory. */
"strict": false, /* Enable all strict type-checking options. */
"noImplicitAny": false, /* Raise error on expressions and declarations with an implied 'any' type. */
"moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
"baseUrl": "./dist", /* Base directory to resolve non-absolute module names. */
"paths": {
"*": [
"node_modules/*"
]
}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
"experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
"emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
},
"include": [
"src/**/*",
"custom.d.ts"
]
}
这些是我的 npm 脚本:
"scripts": {
"clean": "rimraf dist/*",
"dev": "nodemon",
"tsc": "tsc",
"start": "node dist/index.js",
"build": "npm-run-all clean tsc",
},
npm run build
工作正常,一切看起来都很好,但当我运行npm run start
时,出现以下错误:
/app/server/src/entity/Category.ts:1
import {Entity, PrimaryGeneratedColumn, Column, ManyToMany, BaseEntity} from "typeorm";
^^^^^^
SyntaxError: Cannot use import statement outside a module
错误似乎是我的构建出于某种原因似乎是从 src 文件夹而不是构建文件夹导入的。 我不知道出了什么问题,感谢任何指导或想法,以帮助我走得更远。
好的,这样做"start": "node build/index.js"
会导致上述行为,但是如果我在命令行上执行以下操作:
cd build
node index.js
有用。 所以我猜在应用程序的某些模块中某些路径是错误的。 如果我找到一种使用 NPM 脚本的好方法,将会更新更多内容。
对于使用 Typescript + TypeORM 遇到此问题的任何其他人,我也遇到过。 我解决它的方法是使用__dirname
来帮助解析我的 TypeORM 配置中的路径。
例如,而不是做
const connection: DataSourceOptions = {
...
entities: ['src/entities/*.ts', 'dist/entities/*{.ts,.js}'],
}
我修改为
const connection: DataSourceOptions = {
...
entities: [`${__dirname}/../../entities/*{.ts,.js}`],
migrations: [`${__dirname}/migrations/*{.ts,.js}`],
}
希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.