Learn about our RFC process, Open RFC meetings & more.Join in the discussion! »

typescript_worker_threads

1.2.14 • Public • Published

typescript_worker_threads

How to use?

First

import {Worker, WorkerOptions, isMainThread, MessageChannel, MessagePort, workerData, parentPort, threadId} from 'typescript_worker_threads'

Then

Use it just like native "worker_threads" module

特别说明

做了多次的升级,当前此包内容已与发布时略有不同,具体内容请自行看源码,文档暂时就懒得更新了…

Why I use it?

The native module "worker_threads" just support ".js" file, when I coding typescript program I have to code & import JS file into project, Otherwise I cannot use it. I don't know is anybody met same situation as mine, but this module can help me a lot.

So, I take a brief intro for this module to explain how it works. I just rewrite the class "Worker", to make the first argument "filename" accept module id string, therefore I can get full path of the module I just import, then, I detect the extension name of the module file, general speaking, the directory structure would not changed during ts compiling, therefore, the only thing changed is the file extension, if I import ts module, after compile the name will become .js from .ts, overwritten "Worker" class will execute different procedure for ".js" and ".ts", to make sure threads worker receive pure javascript file path eventually

import {ModuleResolver} from './ModuleResolver'
import {Worker as ThreadsWorker} from 'worker_threads'
import {WorkerOptions} from '../interfaces/WorkerOptions'
import {rm} from 'shelljs'
import path from 'path'

export class Worker extends ThreadsWorker {

	constructor(id: string, options?: WorkerOptions) {
		let jsFilename: string
		super((() => {
			const moduleResolver = new ModuleResolver(id)
			/**
			 * This will return JS file path
			 */
			jsFilename = moduleResolver.resolveModule()
			return jsFilename
		})(), options)
		this.on('online', () => {
			try {
				rm('-rf', path.dirname(jsFilename))
			} catch (e) {
				console.error(e)
			}
		})
	}
}

The file convert class called "ModuleResolver", once it received ".ts" file, it will compile typescript code to javascript code, and return the js file

import os from "os"
import path from "path"
import * as ts from "typescript"
import {MD5} from 'crypto-js'
import {ScriptTarget, ModuleKind, ModuleResolutionKind} from 'typescript'
import {int} from 'random'
import process from 'process'

export class ModuleResolver {
	private readonly outputPath: string
	private readonly callerStrIndex: number = 5
	private readonly TS_EXT: string = '.ts'
	private readonly JS_EXT: string = '.js'
	private readonly id: string
	private filename: string

	constructor(id: string) {
		this.id = id
		const outputDirname: string = `.${MD5(`${Date.now()}-${int(0, 65535)}`).toString()}`
		this.outputPath = path.resolve(process.cwd(), outputDirname)
	}

	private getCallerDirname(): string {
		const stackStr: string = new Error('Caller').stack
		const callerLineStr: string = stackStr.split(os.EOL)[this.callerStrIndex].trim()
		const callerFilePath: string = callerLineStr.split('(')[1].split(')')[0].split(':')[0]
		return path.dirname(callerFilePath)
	}

	public resolveModule(): string {
		if (this.filename) return this.filename
		const moduleFullPath: string = require.resolve(path.join(this.getCallerDirname(), this.id))
		const extension: string = path.extname(moduleFullPath)
		switch (extension) {
			case this.TS_EXT: {
				const _filename: string = `${path.basename(moduleFullPath).split(extension)[0]}${this.JS_EXT}`
				const program = ts.createProgram([moduleFullPath], {
					inlineSourceMap: true,
					sourceMap: true,
					inlineSources: true,
					target: ScriptTarget.ES5,
					module: ModuleKind.CommonJS,
					outDir: this.outputPath,
					moduleResolution: ModuleResolutionKind.NodeJs,
					removeComments: false,
					strict: false,
					esModuleInterop: true,
					experimentalDecorators: true,
					emitDecoratorMetadata: true,
					pretty: true,
					allowJs: true
				})
				program.emit()
				this.filename = path.resolve(this.outputPath, _filename)
			}
				break
			case this.JS_EXT: {
				this.filename = moduleFullPath
			}
				break
			default: {
				throw new Error(`Invalid extension [${extension}]`)
			}
		}
		return this.filename
	}
}

Install

npm i typescript_worker_threads

DownloadsWeekly Downloads

1

Version

1.2.14

License

MIT

Unpacked Size

37.8 kB

Total Files

41

Last publish

Collaborators

  • avatar