[英]Cannot use import statement outside a module using typescript on backend
[英]Typescript & TypeORM: Cannot use import statement outside a module
我已经使用 TypeORM 设置了 Typescript 项目,但我在编译时遇到了一些问题。
我的 package 结构是这样的:
root
├── db
│ ├── migrations
│ │ ├── a_migration.ts
│ ├── connection
│ │ ├── config.ts <- ormconfig
│ │ ├── encrypt.ts
│ │ ├── index.ts <- creates the connection
├── src
│ ├── card
│ │ ├── entity.ts
├── package.json
├── tsconfig.json
我的 config.ts 是:
export = {
type: 'postgres',
host: POSTGRES_HOST,
port: POSTGRES_PORT,
username: POSTGRES_USER,
password: POSTGRES_PASS,
database: POSTGRES_DB,
synchronize: true,
logging: false,
entities: ['**src/**/*entity.{ts,js}'],
migrations: ['**/migrations/*.{ts,js}'],
cli: {
entitiesDir: 'src/entity',
migrationsDir: 'db/migrations',
},
namingStrategy: new SnakeNamingStrategy(),
};
tsconfig.json:
{
"compilerOptions": {
"baseUrl": ".",
"target": "es6",
"module": "CommonJS",
"allowJs": false,
"esModuleInterop": true,
"noImplicitAny": true,
"resolveJsonModule": true,
"outDir": "./build",
"strict": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true
},
"include": ["./src/*", "./db/*"],
"exclude": ["./**/__tests__/*", "./**/__functionaltests__/*"]
}
我尝试用path.join
+ __dirname
替换实体和迁移中的**
前缀,但 typeorm 无法检测到迁移文件和实体。 我知道这与解析代码最终位于build
文件夹下的路径有关,但我不确定如何解决这个问题。
如果我这样生活,CLI 适用于未编译的代码 (ts),使用类似nodemon
的东西执行应用程序,但不适用于已编译的 (js) 代码。
我从编译的 js 中得到的错误是: SyntaxError: Cannot use import statement outside a module
任何帮助表示赞赏,非常感谢!
你的实体和迁移应该被赋予 build 目录而不是 src 目录。
并且synchronize
应该设置为假。
尝试更新您的config.ts
,如下所示:
export = {
type: 'postgres',
host: POSTGRES_HOST,
port: POSTGRES_PORT,
username: POSTGRES_USER,
password: POSTGRES_PASS,
database: POSTGRES_DB,
synchronize: false,
logging: false,
entities: ['build/src/**/*entity.{ts,js}'],
migrations: ['build/db/migrations/*.{ts,js}'],
cli: {
entitiesDir: 'src/entity',
migrationsDir: 'db/migrations',
},
namingStrategy: new SnakeNamingStrategy(),
};
注意entities
和migrations
属性的变化。 如果这不起作用,很可能是由于我指定的路径不在build
目录中。 在这种情况下,请根据需要进行更改。
希望这对你有帮助! 干杯!!!
为您的部署创建环境变量。 在 config.ts 检查环境,然后相应地设置实体和迁移。
我遇到了类似的问题,也许这对你有帮助。
我正在使用(未编译的) ormconfig.js
(注意, .js )进行这样的迁移(NestJS 应用程序使用另一种方式通过 TypeORM 建立其数据库连接):
const { SnakeNamingStrategy } = require('typeorm-naming-strategies');
module.exports = {
type: 'mysql',
host: 'localhost',
username: 'some user',
database: 'some db',
password: 'some pw',
entities: ['./src/**/model/*.entity.ts'],
migrations: ['migrations/*{.ts,.js}'],
cli: {
migrationsDir: 'src/migrations',
},
namingStrategy: new SnakeNamingStrategy(),
};
我的 IDE 建议将其转换为 ES6 模块,这会将require('typeorm-naming-strategies')
更改为import
语句。 如果我这样做,我会得到:
SyntaxError: 不能在模块外使用 import 语句
错误的附加 output 是:
import { SnakeNamingStrategy } from 'typeorm-naming-strategies';
^^^^^^
因此,也许您可以将SnakeNamingStrategy
的(未显示?) import
替换为require
。
只是一个猜测,不确定它是否真的对你有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.