Reputation: 2235
I'm building a node.js application using worker_threads
under the hood. In the script file, called worker.ts
, I cannot use the import statement because Node throws an error. So I'm importing the needed packages like this:
const { parentPort } = require('worker_threads')
parentPort.on('message', (data) => {
//Non relevant code
})
However, despite the code actually working, the following error is displayed since there is neither an import nor an export statement:
'worker.ts' cannot be compiled under '--isolatedModules' because it is considered a global script file.
How can I solve the issue?
Upvotes: 0
Views: 422
Reputation: 33901
Using the CodeSandbox link that you provided as a reference, I'll explain the changes that need to be made in both TypeScript modules in order for compilation to succeed and for the program to execute successfully:
./src/index.ts
:
// Use import statements: TypeScript will transform them into "require" calls
// because you are targeting CommonJS in your TSConfig
import {Worker} from 'worker_threads';
import * as path from 'path';
const worker = new Worker(path.resolve(__dirname, './worker.js'));
/* ^^^
It is important to use the path of the **COMPILED** file,
and the extension of the compiled file will be ".js" */
worker.on('message', (data) => console.log('Main: ' + data));
worker.postMessage('Hello!');
./src/worker.ts
:
// Again, use import statement
import {parentPort} from 'worker_threads';
parentPort.on('message', (data) => {
console.log('Worker: ' + data);
setTimeout(() => parentPort.postMessage(data), 1000);
});
Run:
# $ cd path/to/project/dir
$ tsc && node dist/index.js
Worker: Hello!
Main: Hello!
Upvotes: 1