mirror of
https://github.com/egoist/tsup.git
synced 2025-12-08 20:35:58 +00:00
69 lines
1.7 KiB
TypeScript
69 lines
1.7 KiB
TypeScript
import { builtinModules } from 'module'
|
|
import { dirname } from 'path'
|
|
import { Plugin } from 'rollup'
|
|
import JoyCon from 'joycon'
|
|
import nodeResolvePlugin from '@rollup/plugin-node-resolve'
|
|
import { isExternal } from './utils'
|
|
|
|
const PACKAGE_NAME_RE = /^[@a-z]/
|
|
|
|
const joycon = new JoyCon()
|
|
|
|
export const resolvePlugin = ({
|
|
bundle,
|
|
external,
|
|
dtsBundle,
|
|
}: {
|
|
bundle?: boolean
|
|
external?: string[]
|
|
dtsBundle?: boolean
|
|
}): Plugin => {
|
|
const nodeResolve = nodeResolvePlugin({
|
|
mainFields: dtsBundle ? ['types', 'typings'] : ['module', 'main'],
|
|
extensions: dtsBundle ? ['.d.ts'] : ['.mjs', '.js', '.json', '.node'],
|
|
customResolveOptions: {
|
|
moduleDirectory: dtsBundle
|
|
? ['node_modules/@types', 'node_modules']
|
|
: 'node_modules',
|
|
},
|
|
})
|
|
|
|
return {
|
|
...nodeResolve,
|
|
|
|
async resolveId(source, importer) {
|
|
// Always exclude builtin modules
|
|
if (builtinModules.includes(source)) {
|
|
return false
|
|
}
|
|
|
|
if (bundle) {
|
|
const cwd = importer && dirname(importer)
|
|
if (cwd && PACKAGE_NAME_RE.test(source)) {
|
|
// Exclude specified packages
|
|
if (external && isExternal(external, source, importer)) {
|
|
return false
|
|
}
|
|
|
|
// Exclude "dependencies" in package.json
|
|
const pkg = joycon.loadSync(['package.json'], process.cwd())
|
|
|
|
const deps = Object.keys((pkg.data && pkg.data.dependencies) || {})
|
|
|
|
if (deps.includes(source)) {
|
|
return false
|
|
}
|
|
}
|
|
|
|
const result = await nodeResolve.resolveId!.call(this, source, importer)
|
|
|
|
if (result !== null) {
|
|
return result
|
|
}
|
|
}
|
|
|
|
return null
|
|
},
|
|
}
|
|
}
|