diff --git a/src/index.ts b/src/index.ts index b9f9c0a..adb231f 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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) }, } diff --git a/src/utils.ts b/src/utils.ts index 5df84e8..ca014cf 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -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 }