Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: handle dynamic require in ESM #628

Merged
merged 3 commits into from
Jan 11, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,8 @@
"node_modules"
],
"moduleNameMapper": {
"bunchee": "<rootDir>/src/index.ts"
"^bunchee$": "<rootDir>/src/index.ts",
"^testing-utils$": "<rootDir>/test/integration/utils.ts"
},
"transform": {
"^.+\\.(t|j)sx?$": [
Expand Down
4 changes: 4 additions & 0 deletions src/rollup/input.ts
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,10 @@ export async function buildInputConfig(
}),
commonjs({
exclude: bundleConfig.external || null,
// Deal with mixed ESM and CJS modules, such as calling require() in ESM.
// For relative paths, the module will be bundled;
// For external libraries, the module will not be bundled.
transformMixedEsModules: true,
}),
]
).filter(isNotNull<Plugin>)
Expand Down
36 changes: 36 additions & 0 deletions test/integration/dynamic-require/dynamic-require.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import fs from 'fs'
import { createIntegrationTest, getFileNamesFromDirectory } from '../utils'

describe('integration - dynamic-require', () => {
it('should work', async () => {
await createIntegrationTest(
{
directory: __dirname,
},
async ({ distDir }) => {
expect(await getFileNamesFromDirectory(distDir)).toEqual([
'foo.cjs',
'foo.js',
'index.cjs',
'index.js',
])
// TODO: add helper of read content of dist file

// For require calls to the relative path, the value should be bundled
expect(fs.readFileSync(`${distDir}/index.cjs`, 'utf-8')).toContain(
`return 'being-required'`,
)
expect(fs.readFileSync(`${distDir}/index.js`, 'utf-8')).toContain(
`return 'being-required'`,
)
// For require calls to the external library, the value should not be bundled
expect(fs.readFileSync(`${distDir}/foo.cjs`, 'utf-8')).not.toContain(
`external-lib-value`,
)
expect(fs.readFileSync(`${distDir}/foo.js`, 'utf-8')).not.toContain(
`external-lib-value`,
)
},
)
})
})

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

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

18 changes: 18 additions & 0 deletions test/integration/dynamic-require/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"name": "dynamic-require",
"main": "./dist/index.js",
"type": "module",
"exports": {
".": {
"import": "./dist/index.js",
"default": "./dist/index.cjs"
},
"./foo": {
"import": "./dist/foo.js",
"default": "./dist/foo.cjs"
}
},
"dependencies": {
"external-lib": "*"
}
}
5 changes: 5 additions & 0 deletions test/integration/dynamic-require/src/foo.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import externalLib from 'external-lib'

export function foo() {
return externalLib.method()
}
3 changes: 3 additions & 0 deletions test/integration/dynamic-require/src/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export function index() {
require('./required-module').method()
}
3 changes: 3 additions & 0 deletions test/integration/dynamic-require/src/required-module.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export function method() {
return 'being-required'
}
12 changes: 10 additions & 2 deletions test/integration/esm-shims/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { createIntegrationTest, assertFilesContent } from '../utils'
import {
createIntegrationTest,
assertFilesContent,
getFileContents,
} from '../utils'

describe('integration esm-shims', () => {
it('should work with ESM shims', async () => {
Expand All @@ -15,7 +19,6 @@ describe('integration esm-shims', () => {
'const __dirname = __node_cjsPath.dirname(__filename)'

await assertFilesContent(distDir, {
'require.mjs': requirePolyfill,
'filename.mjs': filenamePolyfill,
'dirname.mjs': dirnamePolyfill,
'custom-require.mjs': (code) => !code.includes(requirePolyfill),
Expand All @@ -24,6 +27,11 @@ describe('integration esm-shims', () => {
'dirname.js': /__dirname/,
'custom-require.js': (code) => !code.includes(requirePolyfill),
})

const contents = await getFileContents(distDir, ['require.mjs'])
expect(contents['require.mjs']).not.toContain(requirePolyfill)
expect(contents['require.mjs']).toContain('function getRequireModule')
expect(contents['require.mjs']).toContain('import.meta.url')
},
)
})
Expand Down
16 changes: 11 additions & 5 deletions test/integration/unspecified-types-paths/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import fs from 'fs'
import { assertFilesContent, createIntegrationTest } from '../utils'
import {
assertFilesContent,
createIntegrationTest,
getFileNamesFromDirectory,
} from '../utils'

describe('integration tsconfig-override', () => {
describe('integration - tsconfig-override', () => {
it('should not generate js types paths if not specified', async () => {
await createIntegrationTest(
{
Expand All @@ -12,8 +15,11 @@ describe('integration tsconfig-override', () => {
'./dist/subpath/nested.js': 'subpath/nested',
'./dist/subpath/nested.cjs': 'subpath/nested',
})
const subpathTypes = await import(`${dir}/dist/index.js`)
expect(fs.existsSync(subpathTypes)).toBe(false)
// No types files should be generated
expect(await getFileNamesFromDirectory(dir)).toEqual([
'dist/subpath/nested.cjs',
'dist/subpath/nested.js',
])
},
)
})
Expand Down
1 change: 0 additions & 1 deletion test/integration/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import {
function normalizePath(filePath: string) {
return filePath.replace(/\\/g, '/')
}

export * from '../testing-utils'

type IntegrationTestOptions = {
Expand Down
11 changes: 11 additions & 0 deletions test/testing-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,17 @@ export function assertContainFiles(dir: string, filePaths: string[]) {

type FunctionCondition = (content: string) => Boolean

export async function getFileContents(dir: string, filePaths?: string[]) {
const results: Record<string, string> = {}
const files = filePaths || (await fsp.readdir(dir))
for (const file of files) {
const fullPath = path.resolve(dir, file)
const content = await fsp.readFile(fullPath, { encoding: 'utf-8' })
results[file] = content
}
return results
}

export async function assertFilesContent(
dir: string,
conditionMap: Record<string, RegExp | string | FunctionCondition>,
Expand Down
16 changes: 10 additions & 6 deletions test/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,21 @@
"module": "ESNext",
"target": "ESNext",
"strict": false,
"jsx": "preserve",
"baseUrl": "..",
"paths": {
"bunchee": ["./src/index.ts"],
"testing-utils": ["./test/integration/utils.ts"]
"bunchee": ["./src/index.ts"]
}
},
"include": [
"**/*.test.ts",
"**/*.test.tsx",
"../src/**/*.test.ts",
"../src/**/*.test.tsx"
"./test/**/*.test.ts",
"./test**/*.test.tsx",
// TODO: group those internal utils
"./test/utils/*",
"./test/testing-utils.ts",
"./test/integration/utils.ts",
"./src/**/*.test.ts",
"./src/**/*.test.tsx"
],
"references": [{ "path": "../tsconfig.json" }]
}
2 changes: 1 addition & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,5 @@
},
"references": [{ "path": "./test/tsconfig.json" }],
"include": ["src", "*.d.ts", "**/*.json"],
"exclude": ["**/*.test.ts", "**/*.test.tsx"]
"exclude": ["src/**/*.test.ts", "src/**/*.test.tsx"]
}
Loading