Skip to content

Commit 82f9c85

Browse files
committed
fix: do not use IIFE for contents scripts without imports
Motivation: wrapping in IIFE may delay script injection, which is a needless tradeoff if the script has no (ES module) imports inspired by https://github.com/samrum/vite-plugin-web-extension/blob/main/src/utils/loader.ts#L57-L66
1 parent fe60de0 commit 82f9c85

File tree

1 file changed

+24
-7
lines changed

1 file changed

+24
-7
lines changed

Diff for: packages/vite-plugin/src/node/plugin-contentScripts.ts

+24-7
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,7 @@ export const pluginContentScripts: CrxPluginFn = () => {
135135
},
136136
}
137137
},
138-
generateBundle() {
138+
generateBundle(_options, bundle) {
139139
// emit content script loaders
140140
for (const [key, script] of contentScripts)
141141
if (key === script.refId) {
@@ -145,12 +145,29 @@ export const pluginContentScripts: CrxPluginFn = () => {
145145
} else if (script.type === 'loader') {
146146
const fileName = this.getFileName(script.refId)
147147
script.fileName = fileName
148-
const refId = this.emitFile({
149-
type: 'asset',
150-
name: getFileName({ type: 'loader', id: basename(script.id) }),
151-
source: createProLoader({ fileName }),
152-
})
153-
script.loaderName = this.getFileName(refId)
148+
149+
const bundleFileInfo = bundle[fileName]
150+
// the loader uses IIFE which in this case needlessly
151+
// delays content script execution which may not be desired
152+
const shouldUseLoader = !(
153+
bundleFileInfo.type === 'chunk' &&
154+
bundleFileInfo.imports.length === 0 &&
155+
bundleFileInfo.dynamicImports.length === 0 &&
156+
bundleFileInfo.exports.length === 0
157+
)
158+
159+
if (shouldUseLoader) {
160+
const refId = this.emitFile({
161+
type: 'asset',
162+
name: getFileName({
163+
type: 'loader',
164+
id: basename(script.id),
165+
}),
166+
source: createProLoader({ fileName }),
167+
})
168+
169+
script.loaderName = this.getFileName(refId)
170+
}
154171
} else if (script.type === 'iife') {
155172
throw new Error('IIFE content scripts are not implemented')
156173
}

0 commit comments

Comments
 (0)