首页 > 解决方案 > SyntaxError: 不能在模块外使用 import 语句来导入“reflect-metadata”;

问题描述

这是typegraphql中一个简单API的代码,typeorm

我在某些语法中遇到了问题,因为目前这完全基于导入失败而失败。

我在我的index.ts文件中做了非常简单的事情

  1. 连接到 postgres 数据库
  2. 使用我构建的一些解析器设置 apollo 服务器

这是我的 index.ts

// src/index.ts

import "reflect-metadata";
import { createConnection } from "typeorm";
import { ApolloServer } from "apollo-server";
import {buildSchema} from 'type-graphql'

async function main() {
  try {
    const connection = await createConnection({
      name: "PostgresDB",
      type: "postgres",
      host: "",
      port: 5432,
      username: "",
      password: "",
      database: "",
      synchronize: true,
      ssl: {
        rejectUnauthorized:false
      },
      logging: true,
      entities: ["src/entity/*.*"]
    })
    const schema = await buildSchema({
      resolvers: [
        CoordinateResolver,
        CarrierLiveLocationResolver,
        CurrentRoutesResolver,
        DepotsOnPlatformResolver
      ]
    })
    const server = new ApolloServer({ schema })
    await server.listen(4000)
    console.log("Server has started!")
  } catch (error) {
    console.log(error)
    console.log('life is hard')
  }
}
main()

这是我的 tsconfig.json

{
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "strict": true,
        "esModuleInterop": true,
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true,
        "strictPropertyInitialization": false,
        "baseUrl": "./",
        "paths": {
            "@entity/*": ["./src/entity/*"],
            "@resolvers/*": ["./src/resolvers/*"],
            "@inputs/*": ["./src/inputs/*"]
        }
    }
}

这是我的 package.json

{
  "name": "typegraphql-api",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon -w src --ext ts --exec ts-node src/index.ts"
  },
  "repository": {
    "type": "git",
    "url": "git+https://TRFDCYUIJNKL.git"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "bugs": {
    "url": "https://TRFDCYUIJNKL/issues"
  },
  "homepage": "https://TRFDCYUIJNKL#readme",
  "dependencies": {
    "apollo-server": "^3.4.0",
    "class-validator": "^0.13.1",
    "graphql": "^15.6.1",
    "pg": "^8.7.1",
    "reflect-metadata": "^0.1.13",
    "type-graphql": "^1.1.1",
    "typeorm": "^0.2.38"
  },
  "devDependencies": {
    "ts-node": "^10.3.0",
    "typescript": "^4.4.4"
  }
}

标签: javascripttypescriptgraphqltypeormtypegraphql

解决方案


推荐阅读