Skip to content

Commit

Permalink
fix: allow require and require.cache
Browse files Browse the repository at this point in the history
  • Loading branch information
egoist committed May 15, 2020
1 parent b80ef48 commit 9cedf6c
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 9 deletions.
20 changes: 11 additions & 9 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import dtsPlugin from 'rollup-plugin-dts'
import { sizePlugin, caches } from './size-plugin'
import { resolvePlugin } from './resolve-plugin'
import { isExternal } from './utils'
import { restoreRequirePlugin } from './restore-require-plugin'

type Options = {
bundle?: boolean
Expand Down Expand Up @@ -51,6 +52,16 @@ export async function createRollupConfigs(files: string[], options: Options) {
plugins: [
hashbangPlugin(),
jsonPlugin(),
!dts && restoreRequirePlugin(),
!dts &&
esbuildPlugin({
target: options.target,
watch: options.watch,
minify: options.minify,
jsxFactory: options.jsxFactory,
jsxFragment: options.jsxFragment,
define: options.define,
}),
resolvePlugin({
bundle: options.bundle,
external: options.external,
Expand All @@ -71,15 +82,6 @@ export async function createRollupConfigs(files: string[], options: Options) {
},
}),
dts && dtsPlugin(),
!dts &&
esbuildPlugin({
target: options.target,
watch: options.watch,
minify: options.minify,
jsxFactory: options.jsxFactory,
jsxFragment: options.jsxFragment,
define: options.define,
}),
sizePlugin(),
].filter(Boolean),
},
Expand Down
31 changes: 31 additions & 0 deletions src/restore-require-plugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { PluginImpl } from 'rollup'

const TSUP_REQUIRE_ID = '__TSUP_REQUIRE_ID__'

const JS_RE = /\.[jt]sx?$/

// Prevent @rollup/plugin-commonjs from replacing `require.cache`
export const restoreRequirePlugin: PluginImpl = () => {
return {
name: 'restore-require',

transform(code, id) {
if (JS_RE.test(id)) {
code = code.replace(/require([^\(])/g, `${TSUP_REQUIRE_ID}$1`)

// Dynamic require: `require(file)`
code = code.replace(/require\(([a-zA-Z0-9_]+)\)/g, (_, p1) => {
return `${TSUP_REQUIRE_ID}(${p1})`
})
}
return code
},

renderChunk(code, chunk) {
if (chunk.fileName.endsWith('.js')) {
code = code.replace(/__TSUP_REQUIRE_ID__/g, 'require')
}
return code
},
}
}

0 comments on commit 9cedf6c

Please sign in to comment.