运行 我的打字稿项目时无法在模块外使用 import 语句

Cannot use import statement outside a module when run my typescript project

我正在用打字稿编写一个“Hello world”RabbitMQ 项目。我正在使用 Yarn 作为包管理工具而不是 NPM。

我已经安装了 RabbitMQ 客户端库 amqplib 及其类型定义。我的 package.json 看起来像这样:

{
  "name": "rabbitmq-demo",
  "version": "1.0.0",
  "main": "src/publisher.ts",
  "license": "MIT",
 
  "dependencies": {
    "@types/amqplib": "^0.8.0",
    "amqplib": "^0.8.0"
  },
  "devDependencies": {
    "ts-node": "^10.4.0",
    "typescript": "^4.5.4",
  }
}

我的 tsconfig.json 启用了以下选项:

{
 "compilerOptions": {
   "target": "es2016", 
   "module": "commonjs",
   "rootDir": "./src",
   "outDir": "./dist",
   "esModuleInterop": true,
   "forceConsistentCasingInFileNames": true, 
   "strict": true,  
   "skipLibCheck": true
 }
}

我的./src/publishier.ts,你不需要关心我的问题代码中的逻辑,我只是​​想表明我有我写的这个打字稿文件:

import * as amqp from "amqplib";

const msg = {number: 6};

const connect = async () => {
    try {
        const connection = await amqp.connect("amqp://localhost:5673");
        const channel = await connection.createChannel();
    
        const queue = await channel.assertQueue("jobs"); // create queue named "jobs"
        channel.sendToQueue("jobs", Buffer.from(JSON.stringify(msg)));
        console.log(`Job sent successfully! ${msg.number}`);


    } catch(e) {

    }
    
}

connect();

当我 运行 node src/publisher.ts 时,我得到错误:

import * as amqp from "amqplib";
^^^^^^

SyntaxError: Cannot use import statement outside a module

然后我又在package.json & 运行中添加了"type": "module",但是出现了新的错误:

node:internal/errors:464
    ErrorCaptureStackTrace(err);
    ^

TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /rabbitmq-demo/src/publisher.ts

那么,问题的根本原因是什么?如何 运行 我的 publisher.ts?

我们要求 nodejs 执行 ts 文件,而不是...

  1. 要么我们要求nodejs执行构建源代码后生成的js文件
  2. 或者,我们应该让ts-node执行ts文件

我们可以尝试在 package.json 中遵循 scripts...

{
  "name": "rabbitmq-demo"",
  "version": "1.0.0",
  "main": "dist/publisher.js",
  "license": "MIT",
  "devDependencies": {
    "ts-node": "^10.4.0",
    "typescript": "^4.5.4",
    "@types/amqplib": "^0.8.0",
    "amqplib": "^0.8.0"
  },
  "scripts": {
    "exec": "node dist/publisher.js",
    "preexec": "npm run build",
    "execwithargs": "node dist/publisher.js 'arg1' 'arg2' 'arg3'",
    "preexecwithargs": "npm run build"
    "build": "tsc",
    "start": "ts-node src/publisher.ts",
    "startwithargs": "ts-node src/publisher.ts 'arg1' 'arg2' 'arg3'"
  }
}

将这些脚本放在 package.json 中并假设 tsconfig.json 中设置的 outDirdist,我们可以通过在终端上发出以下任何命令来执行。 .

  1. npm run exec <--- 这将通过编译和 运行 js 文件
  2. 执行
  3. npm run exec 'arg1' 'arg2' 'arg3' <--- 运行 与 command-line args
  4. npm run start <--- 这将通过 ts-node 使用 ts 文件
  5. 执行
  6. npm run start 'arg1' 'arg2' 'arg3' <--- 运行 与 command-line args