Skip to content

Commit

Permalink
feat: 编译后的文件加上 .js 后缀以支持原生 ESM
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Jan 29, 2024
1 parent 57e5a56 commit 1f336aa
Showing 1 changed file with 26 additions and 1 deletion.
27 changes: 26 additions & 1 deletion haoma-compile.config.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import fs from 'fs-extra'
import { defineBabelPlugin, getCompileConfig } from 'haoma'
import pa from 'path'

const removeIsTypePlugin = defineBabelPlugin(t => ({
visitor: {
Expand Down Expand Up @@ -27,6 +29,29 @@ const removeIsTypePlugin = defineBabelPlugin(t => ({
},
}))

const addExtensionPlugin = defineBabelPlugin(() => ({
visitor: {
ImportDeclaration: {
exit(path, { filename }) {
const modulePath = path.node.source.value
if (modulePath.startsWith('.')) {
for (const ext of ['.ts', '/index.ts', '.js', '/index.js']) {
const modulePathWithExt = modulePath + ext
const resolvedPath = pa.join(
pa.dirname(filename),
modulePathWithExt,
)
if (fs.pathExistsSync(resolvedPath)) {
path.node.source.value = modulePathWithExt.replace(/\.ts$/, '.js')
break
}
}
}
},
},
},
}))

export default [
getCompileConfig({
name: 'esm',
Expand All @@ -39,7 +64,7 @@ export default [
rollupDtsFiles: ['**/index.d.ts'],
rollupDtsExcludeFiles: ['**/validator/**'],
rollupDtsIncludedPackages: ['type-fest', 'ts-essentials'],
plugins: [removeIsTypePlugin],
plugins: [removeIsTypePlugin, addExtensionPlugin],
}),
getCompileConfig({
name: 'cjs',
Expand Down

0 comments on commit 1f336aa

Please sign in to comment.