Ts-node : SyntaxError : 모듈 외부에서 import 문을 사용할 수 없습니다.

Sep 13 2020

나는 프로젝트에서 최상위 레벨을 사용하려고했고 모듈을 tscofnig에서 esnext 또는 system으로 변경해야한다는 것을 알았습니다. 그러나 어떤 이유로 내 ts-node의 오류가 발생했습니다. 그리고 나는 이미 type : module을 넣었습니다 .-- experimental-modules 플래그를 사용하려고 시도했지만 오류는 여전히 해결 방법을 모릅니다.

package.json :

{
  "name": "micro-hr",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "type": "module",
  "scripts": {
    "commit": "git-cz",
    "build": "babel src --extensions \".js,.ts\" --out-dir dist --copy-files --no-copy-ignored",
    "start:dev": "ts-node-dev --experimental-modules --inspect --respawn --transpile-only --ignore-watch node_modules -r tsconfig-paths/register src/index.ts",
    "start:debug": "node start --debug --watch",
    "start:prod": "node dist/index.ts",
    "test": "jest",
    "lint": "eslint --fix",
    "lint2": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
    "typeorm": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js --config ./ormconfig.ts",
    "migration:generate": "ts-node ./node_modules/typeorm/cli.js migration:generate -n"
  },
  "devDependencies": {
    "@babel/cli": "^7.11.5",
    "@babel/core": "^7.11.5",
    "@babel/node": "^7.10.5",
    "@babel/preset-env": "^7.11.5",
    "@babel/preset-typescript": "^7.10.4",
    "@commitlint/cli": "^9.1.2",
    "@commitlint/config-conventional": "^9.1.2",
    "@types/bcryptjs": "^2.4.2",
    "@types/cookie-parser": "^1.4.2",
    "@types/cors": "^2.8.7",
    "@types/express": "^4.17.8",
    "@types/helmet": "^0.0.48",
    "@types/jest": "^26.0.13",
    "@types/node": "^14.6.4",
    "@types/pino": "^6.3.0",
    "@types/pino-http": "^5.0.5",
    "@types/supertest": "^2.0.10",
    "@typescript-eslint/eslint-plugin": "^4.0.1",
    "@typescript-eslint/parser": "^4.0.1",
    "babel-plugin-module-resolver": "^4.0.0",
    "commitizen": "^4.2.1",
    "cz-conventional-changelog": "^3.3.0",
    "eslint": "^7.8.1",
    "eslint-config-airbnb-base": "^14.2.0",
    "eslint-config-prettier": "^6.11.0",
    "eslint-config-standard": "^14.1.1",
    "eslint-import-resolver-typescript": "^2.3.0",
    "eslint-plugin-import": "^2.22.0",
    "eslint-plugin-node": "^11.1.0",
    "eslint-plugin-prettier": "^3.1.4",
    "eslint-plugin-promise": "^4.2.1",
    "eslint-plugin-standard": "^4.0.1",
    "husky": "^4.2.5",
    "jest": "^26.4.2",
    "pino-pretty": "^4.2.0",
    "prettier": "^2.1.1",
    "supertest": "^4.0.2",
    "ts-jest": "^26.3.0",
    "ts-node": "^9.0.0",
    "ts-node-dev": "^1.0.0-pre.62",
    "tsconfig-paths": "^3.9.0",
    "tscpaths": "^0.0.9",
    "typescript": "^4.0.2"
  },
  "dependencies": {
    "amqplib": "^0.6.0",
    "assert": "^2.0.0",
    "bcryptjs": "^2.4.3",
    "class-transformer": "^0.3.1",
    "cors": "^2.8.5",
    "dotenv": "^8.2.0",
    "envalid": "^6.0.2",
    "express": "^4.17.1",
    "extendable-error": "^0.1.7",
    "helmet": "^4.1.0",
    "nabbitmq": "^1.0.0",
    "pg": "^8.3.3",
    "pino": "^6.5.1",
    "pino-http": "^5.2.0",
    "reflect-metadata": "^0.1.13",
    "spt-rabbit-helpers": "^1.0.6",
    "tsyringe": "^4.3.0",
    "typeorm": "^0.2.25"
  },
  "config": {
    "commitizen": {
      "path": "cz-conventional-changelog"
    }
  }
}

tsconfig :

{
  "compilerOptions": {
    "target": "es2020",
    "module": "esnext",
    "allowJs": true,
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "strictPropertyInitialization": false,
    "moduleResolution": "node",
    "baseUrl": "./src",
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "forceConsistentCasingInFileNames": true,
    "noImplicitAny": true,
    "typeRoots": ["node_modules/@types", "@types"]
  },
  "include": ["src", "__tests__"],
  "exclude": ["node_modules"]
}

본관:

import 'reflect-metadata';
import express from 'express';
import { RabbitServer } from 'spt-rabbit-helpers';
import validateEnv from 'utils/validateEnvs';
import {
  RabbitMqConnectionFactory,
  ConsumerFactory,
  PublisherFactory,
  RabbitMqConnection,
} from 'nabbitmq';
import { container, singleton } from 'tsyringe';

const factory = new RabbitMqConnectionFactory();
factory.setUri('amqp://localhost:5672');
const ConsumerConnection = await factory.newConnection();
const PublisherConnection = await factory.newConnection();
container.registerInstance('Consumer_Connection', ConsumerConnection);
container.registerInstance('Publisher_Connection', PublisherConnection);

답변

2 EliasSchablowski Sep 18 2020 at 21:55

ts-node (또는 해당 문제에 대한 일반 노드)를 실행하려면를 사용해야합니다 "module": "commons", "target": "ES2017". 그렇지 않으면 import/ export문이 IIFE에 불법적으로 배치됩니다.

따라서 다음 내용으로 node.tsconfig.json 이라는 다른 파일을 사용하는 것이 좋습니다 .

{
    "extends": "./tsconfig.json",
    "compilerOptions": {
        "target": "ES2017" // For NodeJS 8 compat, see https://www.typescriptlang.org/tsconfig#target for more info
    }
}

그런 다음 ts-node를 실행하십시오. --project ./node.tsconfig.json

1 AbhyudayaSharma Dec 16 2020 at 06:25

저도 같은 문제를했고 나는를 변경하여 고정 module에 tsconfig.json로 commonjs와 제거 module에 키를 package.json:

// tsconfig.json
{
    "module": "CommonJS",
}
JoshuaDyck Sep 18 2020 at 21:45

바벨을 사용하여 타이프 스크립트 코드를 트랜스 파일하는 경우 transform-es2015-modules-commonjs플러그인 을 추가해야 할 수 있습니다.

npm으로 설치하고 바벨 구성에 추가 할 수 있습니다.

npm install --save-dev babel-plugin-transform-es2015-modules-commonjs

// Add the following to your Babel config. This could be in your package.json, .babelrc, of babel.config.js

plugins: [
  "transform-es2015-modules-commonjs"
]