我正在用打字稿寫一個“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
然后我說"type": "module"在package.json與再次運行,但得到新的錯誤:
node:internal/errors:464
ErrorCaptureStackTrace(err);
^
TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /rabbitmq-demo/src/publisher.ts
那么,問題的根本原因是什么?如何運行我的publisher.ts?
uj5u.com熱心網友回復:
我們要求nodejs執行一個ts檔案,而不是......
- 我們要么要求
nodejs執行js構建源代碼后生成的檔案 - 或者,我們應該要求
ts-node執行ts檔案
我們可以嘗試以下scripts...package.json
{
"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并假設outDir設定tsconfig.json為dist,我們可以通過在終端上發出以下任何命令來執行...
npm run exec<--- 這將通過編譯和運行js檔案執行npm run exec 'arg1' 'arg2' 'arg3'<--- 使用命令列引數運行npm run start<--- 這將通過ts-node使用ts檔案執行npm run start 'arg1' 'arg2' 'arg3'<--- 使用命令列引數運行
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/419267.html
標籤:
