Skip to content
Open
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 src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,9 @@ export default function native(options: PrebundleOptions): Plugin {
}
},
async config(config) {
// Not necessary, since bundle.js is wrapped in an immediately executed closure.
modifyCommonjs(config, options.modules)
// Run build are not necessary.
// Not necessary, since Pre-Bundling is disabled by default in `vite build` command.
modifyOptimizeDeps(config, options.modules)
},
}
Expand Down
28 changes: 22 additions & 6 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,28 @@ export function cjs2esm(id: string, code: string) {
const snippet = libEsm({
exports: Object.getOwnPropertyNames(cjs.require(id)),
})
const commentsStart = '/* [webpack-prebundle]: start */'
const commentsEnd = '/* [webpack-prebundle]: end */'
const sourcemapURL = '//# sourceMappingURL='
const esmStart = [commentsStart, 'const module = { exports: {} }; const exports = module.exports;', commentsEnd].join('')
const esmEnd = [
commentsStart,
'const _M_ = module.exports;',
snippet.exports,
commentsEnd,
].join('\n')

code = esmStart + code
const lines = code.split('\n')
let lastLine = lines[lines.length - 1]

if (lastLine.startsWith(sourcemapURL)) {
lines[lines.length - 1] = `${esmEnd}\n${lastLine}`
code = lines.join('\n')
} else {
code = `${code}\n${esmEnd}`
}

// TODO: generate sourcemap for esm wrap-snippet
return `
const module = { exports: {} };
${code}
const _M_ = module.exports;
${snippet.exports}
`
return code
}