diff --git a/packages/playground/legacy/package.json b/packages/playground/legacy/package.json index 89a5130f8e9eb9..4c65846365eabe 100644 --- a/packages/playground/legacy/package.json +++ b/packages/playground/legacy/package.json @@ -5,6 +5,7 @@ "scripts": { "dev": "vite", "build": "vite build --debug legacy", + "build:custom-filename": "vite --config ./vite.config-custom-filename.js build --debug legacy", "debug": "node --inspect-brk ../../vite/bin/vite", "serve": "vite preview" }, diff --git a/packages/playground/legacy/vite.config-custom-filename.js b/packages/playground/legacy/vite.config-custom-filename.js new file mode 100644 index 00000000000000..9a96133b015588 --- /dev/null +++ b/packages/playground/legacy/vite.config-custom-filename.js @@ -0,0 +1,15 @@ +const legacy = require('@vitejs/plugin-legacy').default + +module.exports = { + plugins: [legacy()], + build: { + manifest: true, + minify: false, + rollupOptions: { + output: { + entryFileNames: `assets/[name].js`, + chunkFileNames: `assets/[name].js` + } + } + } +} diff --git a/packages/plugin-legacy/index.js b/packages/plugin-legacy/index.js index cb21e5f63ec42a..3bba50352367ff 100644 --- a/packages/plugin-legacy/index.js +++ b/packages/plugin-legacy/index.js @@ -165,6 +165,35 @@ function viteLegacyPlugin(options = {}) { return } + /** + * @param {string|((chunkInfo: import('rollup').PreRenderedChunk)=>string)} fileNames + * @param {string?} defaultFileName + */ + const getLegacyOutputFileName = ( + fileNames, + defaultFileName = '[name]-legacy.[hash].js' + ) => { + if (!fileNames) { + return path.posix.join(config.build.assetsDir, defaultFileName) + } + + // does not support custom functions. + if (typeof fileNames === 'function') { + throw new Error( + `@vitejs/plugin-legacy rollupOptions.output.entryFileNames and rollupOptions.output.chunkFileNames` + + ` does not support the function format.` + ) + } + + let fileName = defaultFileName + // Custom string file return format. + if (fileNames && typeof fileNames === 'string') { + fileName = fileNames.replace(/\[name\]/, '[name]-legacy') + } + + return fileName + } + /** * @param {import('rollup').OutputOptions} options * @returns {import('rollup').OutputOptions} @@ -173,14 +202,8 @@ function viteLegacyPlugin(options = {}) { return { ...options, format: 'system', - entryFileNames: path.posix.join( - config.build.assetsDir, - `[name]-legacy.[hash].js` - ), - chunkFileNames: path.posix.join( - config.build.assetsDir, - `[name]-legacy.[hash].js` - ) + entryFileNames: getLegacyOutputFileName(options.entryFileNames), + chunkFileNames: getLegacyOutputFileName(options.chunkFileNames) } }