Skip to content

Commit

Permalink
fix: incorrect filepath resolution during dynamic import
Browse files Browse the repository at this point in the history
  • Loading branch information
pengzhanbo committed Aug 14, 2024
1 parent 784f1be commit a35ec4f
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 6 deletions.
4 changes: 3 additions & 1 deletion src/core/loadFromCode.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import path from 'node:path'
import fs, { promises as fsp } from 'node:fs'
import { pathToFileURL } from 'node:url'

interface LoadFromCodeOptions {
filepath: string
Expand All @@ -18,9 +19,10 @@ export async function loadFromCode<T = any>({
const fileBase = `${filepath}.timestamp-${Date.now()}`
const ext = isESM ? '.mjs' : '.cjs'
const fileNameTmp = `${fileBase}${ext}`
const fileUrl = pathToFileURL(fileNameTmp).toString()
await fsp.writeFile(fileNameTmp, code, 'utf8')
try {
const result = await import(fileNameTmp)
const result = await import(fileUrl)
return result.default || result
}
finally {
Expand Down
26 changes: 21 additions & 5 deletions tsup.config.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import process from 'node:process'
import { promises as fsp } from 'node:fs'
import path from 'node:path'
import { type Options, defineConfig } from 'tsup'
import fg from 'fast-glob'

const shared: Options = {
dts: true,
Expand All @@ -7,15 +11,27 @@ const shared: Options = {
shims: false,
}

const snippet = 'const result = await Promise.resolve().then(() => _interopRequireWildcard(require(fileUrl)));'

export default defineConfig([{
...shared,
entry: ['src/json5-loader.cts'],
format: 'cjs',
dts: false,
}, {
...shared,
entry: [
'src/{index,rsbuild,helper,server}.ts',
],
format: ['cjs', 'esm'],
}, {
...shared,
entry: ['src/json5-loader.cts'],
format: 'cjs',
dts: false,
onSuccess: async () => {
const files = await fg('dist/chunk-*.cjs', { cwd: process.cwd() })
for (const file of files) {
const filepath = path.join(process.cwd(), file)
const content = await fsp.readFile(filepath, 'utf-8')
if (content.includes(snippet)) {
await fsp.writeFile(filepath, content.replace(snippet, 'const result = await import(fileUrl);'), 'utf-8')
}
}
},
}])

0 comments on commit a35ec4f

Please sign in to comment.