@AlexeySmk

Как импортировать модули в Web Workers?

При запуске main.ts возвращается следующая ошибка:
import { parentPort } from 'worker_threads';
^^^^^^

SyntaxError: Cannot use import statement outside a module


Проект пишу на Node.js + TypeScript.

tsconfig.json

{
    "compilerOptions": {
        "target": "ES2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
        "module": "CommonJS", /* Specify what module code is generated. */
        "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
        "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
        "strict": true, /* Enable all strict type-checking options. */
        "skipLibCheck": true /* Skip type checking all .d.ts files. */
    },
    "include": [
        "src/**/*"
    ]
}



package.json

{
  "name": "title-bot",
  "version": "1.0.0",
  "description": "",
  "main": "src/server.ts",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@ffmpeg-installer/ffmpeg": "^1.1.0",
    "chalk": "^4.1.2",
    "cors": "^2.8.5",
    "dotenv": "^16.0.3",
    "download": "^8.0.0",
    "express": "^4.18.2",
    "fluent-ffmpeg": "^2.1.2",
    "mongoose": "^6.8.2",
    "node-telegram-bot-api": "^0.60.0",
    "nodemon": "^2.0.20",
    "puppeteer": "^19.4.1",
    "puppeteer-cluster": "^0.23.0",
    "ts-node": "^10.9.1",
    "uuid": "^9.0.0"
  },
  "devDependencies": {
    "@types/cors": "^2.8.13",
    "@types/download": "^8.0.2",
    "@types/express": "^4.17.1",
    "@types/fluent-ffmpeg": "^2.1.20",
    "@types/node": "^18.11.18",
    "@types/node-telegram-bot-api": "^0.57.6",
    "@types/uuid": "^9.0.0",
    "typescript": "^4.9.4"
  }
}



main.ts
import { Worker } from 'worker_threads';

const worker = new Worker('./src/Workers/worker.ts');

worker.on('message', (data) => {
    console.log(data);
})

worker.postMessage('start');


worker.ts
import { parentPort } from 'worker_threads';
import { broadcastService } from '../services/BroadcastService'

parentPort?.on('message', async (data: string) => {
    console.log(data);
    const currentBroadcasts = await broadcastService.startBroadcastsChecking();
    parentPort?.postMessage(currentBroadcasts);
})
  • Вопрос задан
  • 148 просмотров
Пригласить эксперта
Ответы на вопрос 1
dedalik
@dedalik
Веб разработчик
В node.js модули импортируются с помощью require()

const { parentPort } = require('worker_threads');
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы