Skip to content

Commit

Permalink
feat: options for nativeModules and transformModules
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Sep 6, 2022
1 parent 000c6ad commit 64151af
Show file tree
Hide file tree
Showing 7 changed files with 65 additions and 7 deletions.
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,22 @@ Return the `.default` export of a module at the top-level.

Custom alias map used to resolve ids.

### `nativeModules`

- Type: Array
- Default: ['typescript`]
- Environment Variable: `JITI_NATIVE_MODULES`

List of modules (within `node_modules`) to always use native require for them.

### `transformModules`

- Type: Array
- Default: []
- Environment Variable: `JITI_TRANSFORM_MODULES`

List of modules (within `node_modules`) to transform them regardless of syntax.

## Development

- Clone Repo
Expand Down
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,11 @@
"acorn": "^8.8.0",
"babel-plugin-dynamic-import-node": "^2.3.3",
"babel-plugin-parameter-decorator": "^1.0.16",
"config": "^3.3.7",
"create-require": "^1.1.1",
"cross-env": "^7.0.3",
"destr": "^1.1.1",
"escape-string-regexp": "^5.0.0",
"eslint": "^8.23.0",
"esm": "^3.2.25",
"estree-walker": "^3.0.1",
Expand Down
16 changes: 16 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

27 changes: 21 additions & 6 deletions src/jiti.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { fileURLToPath, pathToFileURL } from 'url'
import { dirname, join, basename, extname } from 'pathe'
import { sync as mkdirpSync } from 'mkdirp'
import destr from 'destr'
import escapeStringRegexp from 'escape-string-regexp'
import createRequire from 'create-require'
import { lt } from 'semver'
import { normalizeAliases, resolveAlias } from 'pathe/utils'
Expand All @@ -22,6 +23,8 @@ const _EnvESMResolve = destr(process.env.JITI_ESM_RESOLVE)
const _EnvRequireCache = destr(process.env.JITI_REQUIRE_CACHE)
const _EnvSourceMaps = destr(process.env.JITI_SOURCE_MAPS)
const _EnvAlias = destr(process.env.JITI_ALIAS)
const _EnvTransform = destr(process.env.JITI_TRANSFORM_MODULES)
const _EnvNative = destr(process.env.JITI_NATIVE_MODULES)

const isWindows = platform() === 'win32'

Expand All @@ -35,7 +38,9 @@ const defaults: JITIOptions = {
cacheVersion: '7',
legacy: lt(process.version || '0.0.0', '14.0.0'),
extensions: ['.js', '.mjs', '.cjs', '.ts'],
alias: _EnvAlias
alias: _EnvAlias,
nativeModules: _EnvNative || [],
transformModules: _EnvTransform || []
}

type Require = typeof require
Expand All @@ -60,6 +65,12 @@ export default function createJITI (_filename: string, opts: JITIOptions = {}, p
? normalizeAliases(opts.alias || {})
: null

// List of modules to force transform or native
const nativeModules = ['typescript', 'jiti'].concat(opts.nativeModules || [])
const transformModules = ([] as string[]).concat(opts.transformModules || [])
const isNativeRe = new RegExp(`node_modules/(${nativeModules.map(m => escapeStringRegexp(m)).join('|')})/`)
const isTransformRe = new RegExp(`node_modules/(${transformModules.map(m => escapeStringRegexp(m)).join('|')})/`)

function debug (...args: string[]) {
if (opts.debug) {
// eslint-disable-next-line no-console
Expand Down Expand Up @@ -227,6 +238,12 @@ export default function createJITI (_filename: string, opts: JITIOptions = {}, p
return nativeRequire(id)
}

// Force native modules
if (isNativeRe.test(filename)) {
debug('[native]', filename)
return nativeRequire(id)
}

// Check for CJS cache
if (opts.requireCache && nativeRequire.cache[filename]) {
return _interopDefault(nativeRequire.cache[filename]?.exports)
Expand All @@ -243,12 +260,10 @@ export default function createJITI (_filename: string, opts: JITIOptions = {}, p
const needsTranspile = !isCommonJS && (
isTypescript ||
isNativeModule ||
isTransformRe.test(filename) ||
hasESMSyntax(source) ||
(opts.legacy && detectLegacySyntax(source)) ||
// https://github.com/unjs/jiti/issues/56
filename.includes('node_modules/config/')
) &&
!filename.includes('node_modules/typescript/')
(opts.legacy && detectLegacySyntax(source))
)

const start = performance.now()
if (needsTranspile) {
Expand Down
2 changes: 2 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,6 @@ export type JITIOptions = {
extensions?: string[]
transformOptions?: Omit<TransformOptions, 'source'>
alias?: Record<string, string>
nativeModules?: string[]
transformModules?: string[]
}
5 changes: 4 additions & 1 deletion test/__snapshots__/fixtures.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,10 @@ exports[`fixtures > esm > stdout 1`] = `
}"
`;
exports[`fixtures > exotic > stdout 1`] = `"Typescript: true"`;
exports[`fixtures > exotic > stdout 1`] = `
"Typescript: true
Config: true"
`;
exports[`fixtures > hashbang > stdout 1`] = `"1"`;
Expand Down
4 changes: 4 additions & 0 deletions test/fixtures/exotic/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@

import * as ts from 'typescript'

console.log('Typescript:', 'mapEntries' in ts)

// https://github.com/unjs/jiti/issues/56
console.log('Config:', 'getFilesOrder' in require('config/parser'))

0 comments on commit 64151af

Please sign in to comment.