fix(lib): esbuild helper functions injection not working with named exports (#14539)

This commit is contained in:
翠 / green 2023-10-09 17:10:39 +09:00 committed by GitHub
parent 27bffc4641
commit 5004d004e7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 39 additions and 2 deletions

View File

@ -25,9 +25,10 @@ import type { Plugin } from '../plugin'
const debug = createDebugger('vite:esbuild')
// IIFE content looks like `var MyLib = function() {`. Spaces are removed when minified
// IIFE content looks like `var MyLib = function() {`.
// Spaces are removed and parameters are mangled when minified
const IIFE_BEGIN_RE =
/(const|var)\s+\S+\s*=\s*function\(\)\s*\{.*"use strict";/s
/(const|var)\s+\S+\s*=\s*function\([^()]*\)\s*\{\s*"use strict";/
const validExtensionRE = /\.\w+$/
const jsxExtensionsRE = /\.(?:j|t)sx\b/

View File

@ -19,11 +19,13 @@ describe.runIf(isBuild)('build', () => {
const noMinifyCode = readFile(
'dist/nominify/my-lib-custom-filename.umd.cjs',
)
const namedCode = readFile('dist/named/my-lib-named.umd.cjs')
// esbuild helpers are injected inside of the UMD wrapper
expect(code).toMatch(/^\(function\(/)
expect(noMinifyCode).toMatch(
/^\(function\(global.+?"use strict";var.+?function\smyLib\(/s,
)
expect(namedCode).toMatch(/^\(function\(/)
})
test('iife', async () => {
@ -32,11 +34,15 @@ describe.runIf(isBuild)('build', () => {
const noMinifyCode = readFile(
'dist/nominify/my-lib-custom-filename.iife.js',
)
const namedCode = readFile('dist/named/my-lib-named.iife.js')
// esbuild helpers are injected inside of the IIFE wrapper
expect(code).toMatch(/^var MyLib=function\(\)\{\s*"use strict";/)
expect(noMinifyCode).toMatch(
/^var MyLib\s*=\s*function\(\)\s*\{\s*"use strict";/,
)
expect(namedCode).toMatch(
/^var MyLibNamed=function\([^()]+\)\{\s*"use strict";/,
)
})
test('restrisct-helpers-injection', async () => {

View File

@ -82,6 +82,12 @@ export async function serve(): Promise<{ close(): Promise<void> }> {
),
})
await build({
root: rootDir,
logLevel: 'warn', // output esbuild warns
configFile: path.resolve(__dirname, '../vite.named-exports.config.js'),
})
// start static file server
const serve = sirv(path.resolve(rootDir, 'dist'))
const httpServer = http.createServer((req, res) => {

View File

@ -0,0 +1,4 @@
export const foo = 'foo'
// Force esbuild spread helpers
console.log({ ...foo })

View File

@ -0,0 +1,20 @@
import path from 'node:path'
import { defineConfig } from 'vite'
export default defineConfig({
esbuild: {
supported: {
// Force esbuild inject helpers to test regex
'object-rest-spread': false,
},
},
build: {
lib: {
entry: path.resolve(__dirname, 'src/main-named.js'),
name: 'MyLibNamed',
formats: ['umd', 'iife'],
fileName: 'my-lib-named',
},
outDir: 'dist/named',
},
})