Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 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
46 changes: 46 additions & 0 deletions packages/vite/src/node/__tests__/plugins/completeAmdWrap.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { describe, expect, test } from 'vitest'
import { completeAmdWrapPlugin } from '../../plugins/completeAmdWrap'

async function createCompleteAmdWrapPluginRenderChunk() {
const instance = completeAmdWrapPlugin()

return async (code: string) => {
// @ts-expect-error transform.handler should exist
const result = await instance.renderChunk.call(instance, code, 'foo.ts', {
format: 'amd',
})
return result?.code || result
}
}

describe('completeAmdWrapPlugin', async () => {
const renderChunk = await createCompleteAmdWrapPluginRenderChunk()

describe('adds require parameter', async () => {
test('without other dependencies', async () => {
expect(
await renderChunk('define((function() { } ))'),
).toMatchInlineSnapshot(`"define(["require"], (function(require) { } ))"`)
})

test('with other dependencies', async () => {
expect(
await renderChunk(
'define(["vue", "vue-router"], function(vue, vueRouter) { } ))',
),
).toMatchInlineSnapshot(
`"define(["require", "vue", "vue-router"], (function(require, vue, vueRouter) { } ))"`,
)
})

test("only if require isn't injected already", async () => {
expect(
await renderChunk('define(["require"], function(require) { } ))'),
).toMatchInlineSnapshot(`"define(["require"], (function(require) { } ))"`)

expect(
await renderChunk(`define(['require'], function(require) { } ))`),
).toMatchInlineSnapshot(`"define(['require'], (function(require) { } ))"`)
})
})
})
2 changes: 2 additions & 0 deletions packages/vite/src/node/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ import {
resolveChokidarOptions,
resolveEmptyOutDir,
} from './watch'
import { completeAmdWrapPlugin } from './plugins/completeAmdWrap'
import { completeSystemWrapPlugin } from './plugins/completeSystemWrap'
import { webWorkerPostPlugin } from './plugins/worker'
import { getHookHandler } from './plugins'
Expand Down Expand Up @@ -466,6 +467,7 @@ export async function resolveBuildPlugins(config: ResolvedConfig): Promise<{
}> {
return {
pre: [
completeAmdWrapPlugin(),
completeSystemWrapPlugin(),
...(!config.isWorker ? [prepareOutDirPlugin()] : []),
perEnvironmentPlugin('commonjs', (environment) => {
Expand Down
30 changes: 30 additions & 0 deletions packages/vite/src/node/plugins/completeAmdWrap.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import type { Plugin } from '../plugin'

/**
* ensure amd bundles request `require` to be injected
*/
export function completeAmdWrapPlugin(): Plugin {
const AmdWrapRE =
/\bdefine\((?:\s*\[([^\]]*)\],)?\s*(?:\(\s*)?function\s*\(([^)]*)\)\s*\{/g

return {
name: 'vite:force-amd-wrap-require',
renderChunk(code, _chunk, opts) {
if (opts.format !== 'amd') return

return {
code: code.replace(AmdWrapRE, (_, deps, params) => {
if (deps?.includes(`"require"`) || deps?.includes(`'require'`)) {
return `define([${deps}], (function(${params}) {`
}

const newDeps = deps ? `"require", ${deps}` : '"require"'
const newParams = params.trim() ? `require, ${params}` : 'require'

return `define([${newDeps}], (function(${newParams}) {`
}),
map: null, // no need to generate sourcemap as no mapping exists for the wrapper
}
},
}
}
1 change: 1 addition & 0 deletions playground/amd/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# amd
21 changes: 21 additions & 0 deletions playground/amd/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>amd</title>
</head>
<body>
<script src="node_modules/requirejs/require.js"></script>
<script type="text/javascript">
requirejs(
['plugin/dist/js/plugin.js'],
(plugin) => {
console.log('Plugin loaded', plugin())
},
(err) => {
console.error('Error loading plugin', err)
},
)
</script>
</body>
</html>
5 changes: 5 additions & 0 deletions playground/amd/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"dependencies": {
"requirejs": "^2.3.7"
}
}
1 change: 1 addition & 0 deletions playground/amd/plugin/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<html />
6 changes: 6 additions & 0 deletions playground/amd/plugin/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import workerUrl from './worker?url&no-inline'

export default function pluginMain() {
console.log('workerUrl', workerUrl)
return 'OK'
}
5 changes: 5 additions & 0 deletions playground/amd/plugin/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"scripts": {
"build": "vite build"
}
}
35 changes: 35 additions & 0 deletions playground/amd/plugin/vite.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { join } from 'node:path'
import { defineConfig } from 'vite'

export default defineConfig((config) => {
const isProduction = false // config.mode === 'production'
return {
base: './',
build: {
outDir: './dist',
minify: isProduction,
rollupOptions: {
preserveEntrySignatures: 'strict',
input: {
plugin: './index.ts',
},
output: {
format: 'amd',
assetFileNames: join(
'assets',
`[name]${isProduction ? '-[hash]' : ''}[extname]`,
),
chunkFileNames: join(
'js',
'chunks',
`[name]${isProduction ? '-[hash]' : ''}.mjs`,
),
entryFileNames: join(
'js',
`[name]${isProduction ? '-[hash]' : ''}.js`,
),
},
},
},
}
})
1 change: 1 addition & 0 deletions playground/amd/plugin/worker.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
console.log("I'm a worker")
Loading