From 860d1f6f5f7ece197e92a822470a093ae7a7a68a Mon Sep 17 00:00:00 2001 From: LongYinan Date: Wed, 15 Feb 2023 14:00:02 +0800 Subject: [PATCH] fix(register): enforece module option in register/esm (#694) --- packages/register/esm.mts | 5 ++++- packages/register/register.ts | 20 ++++++++++++++------ 2 files changed, 18 insertions(+), 7 deletions(-) diff --git a/packages/register/esm.mts b/packages/register/esm.mts index 7897d1539..8c4d26cb7 100644 --- a/packages/register/esm.mts +++ b/packages/register/esm.mts @@ -2,6 +2,8 @@ import { promises as fs, constants as FSConstants } from 'fs' import { join, parse, isAbsolute } from 'path' import { fileURLToPath, pathToFileURL } from 'url' +import ts from 'typescript' + // @ts-expect-error import { readDefaultTsConfig } from '../lib/read-default-tsconfig.js' // @ts-expect-error @@ -93,7 +95,8 @@ type LoadFn = ( export const load: LoadFn = async (url, context, defaultLoad) => { const filePath = TRANSFORM_MAP.get(url) if (filePath) { - const tsconfig = readDefaultTsConfig() + const tsconfig: ts.CompilerOptions = readDefaultTsConfig() + tsconfig.module = ts.ModuleKind.ESNext const code = await compile(await fs.readFile(filePath, 'utf8'), filePath, tsconfig, true) return { format: context.format, diff --git a/packages/register/register.ts b/packages/register/register.ts index 327a8612d..194afa557 100644 --- a/packages/register/register.ts +++ b/packages/register/register.ts @@ -1,7 +1,7 @@ import { platform } from 'os' import { resolve } from 'path' -import { transform, transformSync } from '@swc-node/core' +import { transform, transformSync, Options } from '@swc-node/core' import { SourcemapMap, installSourceMapSupport } from '@swc-node/sourcemap-support' import { addHook } from 'pirates' import * as ts from 'typescript' @@ -77,12 +77,16 @@ export function compile( return code }) } else { - const swcRegisterConfig = tsCompilerOptionsToSwcConfig(options, filename) - if (process.env.SWCRC === 'true') { + let swcRegisterConfig: Options + if (process.env.SWCRC) { // when SWCRC environment variable is set to true it will use swcrc file - swcRegisterConfig.swc = { - swcrc: true, + swcRegisterConfig = { + swc: { + swcrc: true, + }, } + } else { + swcRegisterConfig = tsCompilerOptionsToSwcConfig(options, filename) } const { code, map } = transformSync(sourcecode, filename, swcRegisterConfig) // in case of map is undefined @@ -93,7 +97,11 @@ export function compile( } } -export function register(options = readDefaultTsConfig(), hookOpts = {}) { +export function register(options: Partial = {}, hookOpts = {}) { + if (!process.env.SWCRC) { + options = readDefaultTsConfig() + } + options.module = ts.ModuleKind.CommonJS installSourceMapSupport() return addHook((code, filename) => compile(code, filename, options), { exts: DEFAULT_EXTENSIONS,