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}`],
}
希望这能有所帮助!