Skip to content

Commit

Permalink
fix(register): enforece module option in register/esm (#694)
Browse files Browse the repository at this point in the history
  • Loading branch information
Brooooooklyn authored Feb 15, 2023
1 parent ac2ed69 commit 860d1f6
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 7 deletions.
5 changes: 4 additions & 1 deletion packages/register/esm.mts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down
20 changes: 14 additions & 6 deletions packages/register/register.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand Down Expand Up @@ -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
Expand All @@ -93,7 +97,11 @@ export function compile(
}
}

export function register(options = readDefaultTsConfig(), hookOpts = {}) {
export function register(options: Partial<ts.CompilerOptions> = {}, hookOpts = {}) {
if (!process.env.SWCRC) {
options = readDefaultTsConfig()
}
options.module = ts.ModuleKind.CommonJS
installSourceMapSupport()
return addHook((code, filename) => compile(code, filename, options), {
exts: DEFAULT_EXTENSIONS,
Expand Down

0 comments on commit 860d1f6

Please sign in to comment.