diff --git a/.eslintrc.cjs b/.eslintrc.cjs index 59a3579c80fc2e..bfdcd3d4f71cb8 100644 --- a/.eslintrc.cjs +++ b/.eslintrc.cjs @@ -8,13 +8,13 @@ module.exports = defineConfig({ 'eslint:recommended', 'plugin:node/recommended', 'plugin:@typescript-eslint/recommended', - 'plugin:regexp/recommended' + 'plugin:regexp/recommended', ], plugins: ['import', 'regexp'], parser: '@typescript-eslint/parser', parserOptions: { sourceType: 'module', - ecmaVersion: 2021 + ecmaVersion: 2021, }, rules: { eqeqeq: ['warn', 'always', { null: 'never' }], @@ -25,36 +25,36 @@ module.exports = defineConfig({ 'prefer-const': [ 'warn', { - destructuring: 'all' - } + destructuring: 'all', + }, ], 'node/no-missing-import': [ 'error', { allowModules: ['types', 'estree', 'less', 'sass', 'stylus'], - tryExtensions: ['.ts', '.js', '.jsx', '.tsx', '.d.ts'] - } + tryExtensions: ['.ts', '.js', '.jsx', '.tsx', '.d.ts'], + }, ], 'node/no-missing-require': [ 'error', { // for try-catching yarn pnp allowModules: ['pnpapi', 'vite'], - tryExtensions: ['.ts', '.js', '.jsx', '.tsx', '.d.ts'] - } + tryExtensions: ['.ts', '.js', '.jsx', '.tsx', '.d.ts'], + }, ], 'node/no-extraneous-import': [ 'error', { - allowModules: ['vite', 'less', 'sass', 'vitest'] - } + allowModules: ['vite', 'less', 'sass', 'vitest'], + }, ], 'node/no-extraneous-require': [ 'error', { - allowModules: ['vite'] - } + allowModules: ['vite'], + }, ], 'node/no-deprecated-api': 'off', 'node/no-unpublished-import': 'off', @@ -65,11 +65,11 @@ module.exports = defineConfig({ '@typescript-eslint/ban-types': 'off', // TODO: we should turn this on in a new PR '@typescript-eslint/explicit-module-boundary-types': [ 'error', - { allowArgumentsExplicitlyTypedAsAny: true } + { allowArgumentsExplicitlyTypedAsAny: true }, ], '@typescript-eslint/no-empty-function': [ 'error', - { allow: ['arrowFunctions'] } + { allow: ['arrowFunctions'] }, ], '@typescript-eslint/no-empty-interface': 'off', '@typescript-eslint/no-explicit-any': 'off', // maybe we should turn this on in a new PR @@ -80,12 +80,12 @@ module.exports = defineConfig({ '@typescript-eslint/no-var-requires': 'off', '@typescript-eslint/consistent-type-imports': [ 'error', - { prefer: 'type-imports' } + { prefer: 'type-imports' }, ], 'import/no-nodejs-modules': [ 'error', - { allow: builtinModules.map((mod) => `node:${mod}`) } + { allow: builtinModules.map((mod) => `node:${mod}`) }, ], 'import/no-duplicates': 'error', 'import/order': 'error', @@ -96,19 +96,24 @@ module.exports = defineConfig({ ignoreDeclarationSort: true, ignoreMemberSort: false, memberSyntaxSortOrder: ['none', 'all', 'multiple', 'single'], - allowSeparatedGroups: false - } + allowSeparatedGroups: false, + }, ], - 'regexp/no-contradiction-with-assertion': 'error' + 'regexp/no-contradiction-with-assertion': 'error', }, overrides: [ { files: ['packages/**'], excludedFiles: '**/__tests__/**', rules: { - 'no-restricted-globals': ['error', 'require', '__dirname', '__filename'] - } + 'no-restricted-globals': [ + 'error', + 'require', + '__dirname', + '__filename', + ], + }, }, { files: 'packages/vite/**/*.*', @@ -116,36 +121,36 @@ module.exports = defineConfig({ 'node/no-restricted-require': [ 'error', Object.keys( - require('./packages/vite/package.json').devDependencies + require('./packages/vite/package.json').devDependencies, ).map((d) => ({ name: d, message: `devDependencies can only be imported using ESM syntax so ` + `that they are included in the rollup bundle. If you are trying to ` + - `lazy load a dependency, use (await import('dependency')).default instead.` - })) - ] - } + `lazy load a dependency, use (await import('dependency')).default instead.`, + })), + ], + }, }, { files: ['packages/vite/src/node/**'], rules: { - 'no-console': ['error'] - } + 'no-console': ['error'], + }, }, { files: ['packages/vite/src/types/**', '*.spec.ts'], rules: { - 'node/no-extraneous-import': 'off' - } + 'node/no-extraneous-import': 'off', + }, }, { files: ['packages/create-vite/template-*/**', '**/build.config.ts'], rules: { 'no-undef': 'off', 'node/no-missing-import': 'off', - '@typescript-eslint/explicit-module-boundary-types': 'off' - } + '@typescript-eslint/explicit-module-boundary-types': 'off', + }, }, { files: ['playground/**'], @@ -158,17 +163,17 @@ module.exports = defineConfig({ 'node/no-unsupported-features/es-builtins': [ 'error', { - version: '^14.18.0 || >=16.0.0' - } + version: '^14.18.0 || >=16.0.0', + }, ], 'node/no-unsupported-features/node-builtins': [ 'error', { - version: '^14.18.0 || >=16.0.0' - } + version: '^14.18.0 || >=16.0.0', + }, ], - '@typescript-eslint/explicit-module-boundary-types': 'off' - } + '@typescript-eslint/explicit-module-boundary-types': 'off', + }, }, { files: ['playground/**'], @@ -177,21 +182,21 @@ module.exports = defineConfig({ 'no-undef': 'off', 'no-empty': 'off', 'no-constant-condition': 'off', - '@typescript-eslint/no-empty-function': 'off' - } + '@typescript-eslint/no-empty-function': 'off', + }, }, { files: ['*.js', '*.mjs', '*.cjs'], rules: { - '@typescript-eslint/explicit-module-boundary-types': 'off' - } + '@typescript-eslint/explicit-module-boundary-types': 'off', + }, }, { files: ['*.d.ts'], rules: { - '@typescript-eslint/triple-slash-reference': 'off' - } - } + '@typescript-eslint/triple-slash-reference': 'off', + }, + }, ], - reportUnusedDisableDirectives: true + reportUnusedDisableDirectives: true, }) diff --git a/.github/renovate.json5 b/.github/renovate.json5 index 0014c768519180..ce03a1811793e8 100644 --- a/.github/renovate.json5 +++ b/.github/renovate.json5 @@ -8,8 +8,8 @@ "packageRules": [ { "depTypeList": ["peerDependencies"], - "enabled": false - } + "enabled": false, + }, ], "ignoreDeps": [ // manually bumping @@ -22,6 +22,6 @@ "source-map", // `source-map:v0.7.0+` needs more investigation "dotenv-expand", // `dotenv-expand:6.0.0+` has breaking changes (#6858) "kill-port", // `kill-port:^2.0.0 has perf issues (#8392) - "miniflare" // `miniflare:v2.0.0+` only supports node 16.7 - ] + "miniflare", // `miniflare:v2.0.0+` only supports node 16.7 + ], } diff --git a/.prettierrc.json b/.prettierrc.json index 3a87ddf358fad4..568ce1a24732d8 100644 --- a/.prettierrc.json +++ b/.prettierrc.json @@ -3,7 +3,7 @@ "tabWidth": 2, "singleQuote": true, "printWidth": 80, - "trailingComma": "none", + "trailingComma": "all", "overrides": [ { "files": ["*.json5"], diff --git a/docs/.vitepress/config.ts b/docs/.vitepress/config.ts index 513378a37488b2..19dda3841c7031 100644 --- a/docs/.vitepress/config.ts +++ b/docs/.vitepress/config.ts @@ -36,19 +36,19 @@ const versionLinks = ((): DefaultTheme.NavItemWithLink[] => { return [ { text: 'Vite 3 Docs (release)', - link: 'https://vitejs.dev' + link: 'https://vitejs.dev', }, { text: 'Vite 2 Docs', - link: 'https://v2.vitejs.dev' - } + link: 'https://v2.vitejs.dev', + }, ] case 'release': return [ { text: 'Vite 2 Docs', - link: 'https://v2.vitejs.dev' - } + link: 'https://v2.vitejs.dev', + }, ] } })() @@ -73,13 +73,13 @@ export default defineConfig({ src: 'https://cdn.usefathom.com/script.js', 'data-site': 'CBDFBSLI', 'data-spa': 'auto', - defer: '' - } - ] + defer: '', + }, + ], ], vue: { - reactivityTransform: true + reactivityTransform: true, }, themeConfig: { @@ -87,13 +87,13 @@ export default defineConfig({ editLink: { pattern: 'https://github.com/vitejs/vite/edit/main/docs/:path', - text: 'Suggest changes to this page' + text: 'Suggest changes to this page', }, socialLinks: [ { icon: 'twitter', link: 'https://twitter.com/vite_js' }, { icon: 'discord', link: 'https://chat.vitejs.dev' }, - { icon: 'github', link: 'https://github.com/vitejs/vite' } + { icon: 'github', link: 'https://github.com/vitejs/vite' }, ], algolia: { @@ -101,13 +101,13 @@ export default defineConfig({ apiKey: 'deaab78bcdfe96b599497d25acc6460e', indexName: 'vitejs', searchParameters: { - facetFilters: ['tags:en'] - } + facetFilters: ['tags:en'], + }, }, carbonAds: { code: 'CEBIEK3N', - placement: 'vitejsdev' + placement: 'vitejsdev', }, localeLinks: { @@ -115,13 +115,13 @@ export default defineConfig({ items: [ { text: '简体中文', link: 'https://cn.vitejs.dev' }, { text: '日本語', link: 'https://ja.vitejs.dev' }, - { text: 'Español', link: 'https://es.vitejs.dev' } - ] + { text: 'Español', link: 'https://es.vitejs.dev' }, + ], }, footer: { message: `Released under the MIT License. (${commitRef})`, - copyright: 'Copyright © 2019-present Evan You & Vite Contributors' + copyright: 'Copyright © 2019-present Evan You & Vite Contributors', }, nav: [ @@ -136,36 +136,36 @@ export default defineConfig({ items: [ { text: 'Twitter', - link: 'https://twitter.com/vite_js' + link: 'https://twitter.com/vite_js', }, { text: 'Discord Chat', - link: 'https://chat.vitejs.dev' + link: 'https://chat.vitejs.dev', }, { text: 'Awesome Vite', - link: 'https://github.com/vitejs/awesome-vite' + link: 'https://github.com/vitejs/awesome-vite', }, { text: 'DEV Community', - link: 'https://dev.to/t/vite' + link: 'https://dev.to/t/vite', }, { text: 'Rollup Plugins Compat', - link: 'https://vite-rollup-plugins.patak.dev/' + link: 'https://vite-rollup-plugins.patak.dev/', }, { text: 'Changelog', - link: 'https://github.com/vitejs/vite/blob/main/packages/vite/CHANGELOG.md' - } - ] - } - ] + link: 'https://github.com/vitejs/vite/blob/main/packages/vite/CHANGELOG.md', + }, + ], + }, + ], }, { text: 'Version', - items: versionLinks - } + items: versionLinks, + }, ], sidebar: { @@ -175,87 +175,87 @@ export default defineConfig({ items: [ { text: 'Why Vite', - link: '/guide/why' + link: '/guide/why', }, { text: 'Getting Started', - link: '/guide/' + link: '/guide/', }, { text: 'Features', - link: '/guide/features' + link: '/guide/features', }, { text: 'CLI', - link: '/guide/cli' + link: '/guide/cli', }, { text: 'Using Plugins', - link: '/guide/using-plugins' + link: '/guide/using-plugins', }, { text: 'Dependency Pre-Bundling', - link: '/guide/dep-pre-bundling' + link: '/guide/dep-pre-bundling', }, { text: 'Static Asset Handling', - link: '/guide/assets' + link: '/guide/assets', }, { text: 'Building for Production', - link: '/guide/build' + link: '/guide/build', }, { text: 'Deploying a Static Site', - link: '/guide/static-deploy' + link: '/guide/static-deploy', }, { text: 'Env Variables and Modes', - link: '/guide/env-and-mode' + link: '/guide/env-and-mode', }, { text: 'Server-Side Rendering (SSR)', - link: '/guide/ssr' + link: '/guide/ssr', }, { text: 'Backend Integration', - link: '/guide/backend-integration' + link: '/guide/backend-integration', }, { text: 'Comparisons', - link: '/guide/comparisons' + link: '/guide/comparisons', }, { text: 'Troubleshooting', - link: '/guide/troubleshooting' + link: '/guide/troubleshooting', }, { text: 'Migration from v2', - link: '/guide/migration' - } - ] + link: '/guide/migration', + }, + ], }, { text: 'APIs', items: [ { text: 'Plugin API', - link: '/guide/api-plugin' + link: '/guide/api-plugin', }, { text: 'HMR API', - link: '/guide/api-hmr' + link: '/guide/api-hmr', }, { text: 'JavaScript API', - link: '/guide/api-javascript' + link: '/guide/api-javascript', }, { text: 'Config Reference', - link: '/config/' - } - ] - } + link: '/config/', + }, + ], + }, ], '/config/': [ { @@ -263,39 +263,39 @@ export default defineConfig({ items: [ { text: 'Configuring Vite', - link: '/config/' + link: '/config/', }, { text: 'Shared Options', - link: '/config/shared-options' + link: '/config/shared-options', }, { text: 'Server Options', - link: '/config/server-options' + link: '/config/server-options', }, { text: 'Build Options', - link: '/config/build-options' + link: '/config/build-options', }, { text: 'Preview Options', - link: '/config/preview-options' + link: '/config/preview-options', }, { text: 'Dep Optimization Options', - link: '/config/dep-optimization-options' + link: '/config/dep-optimization-options', }, { text: 'SSR Options', - link: '/config/ssr-options' + link: '/config/ssr-options', }, { text: 'Worker Options', - link: '/config/worker-options' - } - ] - } - ] - } - } + link: '/config/worker-options', + }, + ], + }, + ], + }, + }, }) diff --git a/docs/.vitepress/theme/components/AsideSponsors.vue b/docs/.vitepress/theme/components/AsideSponsors.vue index 789f1e0e8addbf..6e8e9c464a70f3 100644 --- a/docs/.vitepress/theme/components/AsideSponsors.vue +++ b/docs/.vitepress/theme/components/AsideSponsors.vue @@ -10,7 +10,7 @@ const sponsors = computed(() => { data?.value.map((sponsor) => { return { size: sponsor.size === 'big' ? 'mini' : 'xmini', - items: sponsor.items + items: sponsor.items, } }) ?? [] ) diff --git a/docs/.vitepress/theme/composables/sponsor.ts b/docs/.vitepress/theme/composables/sponsor.ts index b6a98ce18622bb..976dbcfb75103e 100644 --- a/docs/.vitepress/theme/composables/sponsor.ts +++ b/docs/.vitepress/theme/composables/sponsor.ts @@ -34,7 +34,7 @@ export function useSponsor() { }) return { - data + data, } } @@ -43,19 +43,19 @@ function mapSponsors(sponsors: Sponsors) { { tier: 'Platinum Sponsor', size: 'big', - items: mapImgPath(sponsors['platinum']) + items: mapImgPath(sponsors['platinum']), }, { tier: 'Gold Sponsors', size: 'medium', - items: mapImgPath(sponsors['gold']) - } + items: mapImgPath(sponsors['gold']), + }, ] } function mapImgPath(sponsors: Sponsor[]) { return sponsors.map((sponsor) => ({ ...sponsor, - img: `${dataHost}/images/${sponsor.img}` + img: `${dataHost}/images/${sponsor.img}`, })) } diff --git a/docs/.vitepress/theme/index.ts b/docs/.vitepress/theme/index.ts index 39f1f2ffcae120..bef729b777e7c3 100644 --- a/docs/.vitepress/theme/index.ts +++ b/docs/.vitepress/theme/index.ts @@ -10,10 +10,10 @@ export default { Layout() { return h(Theme.Layout, null, { 'home-features-after': () => h(HomeSponsors), - 'aside-ads-before': () => h(AsideSponsors) + 'aside-ads-before': () => h(AsideSponsors), }) }, enhanceApp({ app }) { app.component('SvgImage', SvgImage) - } + }, } diff --git a/docs/_data/team.js b/docs/_data/team.js index fd386685af6bc1..8c01844f6cdc3f 100644 --- a/docs/_data/team.js +++ b/docs/_data/team.js @@ -8,9 +8,9 @@ export const core = [ desc: 'Independent open source developer, creator of Vue.js and Vite.', links: [ { icon: 'github', link: 'https://github.com/yyx990803' }, - { icon: 'twitter', link: 'https://twitter.com/youyuxi' } + { icon: 'twitter', link: 'https://twitter.com/youyuxi' }, ], - sponsor: 'https://github.com/sponsors/yyx990803' + sponsor: 'https://github.com/sponsors/yyx990803', }, { avatar: 'https://www.github.com/patak-dev.png', @@ -21,9 +21,9 @@ export const core = [ desc: 'Core team member of Vite. Team member of Vue.', links: [ { icon: 'github', link: 'https://github.com/patak-dev' }, - { icon: 'twitter', link: 'https://twitter.com/patak_dev' } + { icon: 'twitter', link: 'https://twitter.com/patak_dev' }, ], - sponsor: 'https://github.com/sponsors/patak-dev' + sponsor: 'https://github.com/sponsors/patak-dev', }, { avatar: 'https://www.github.com/antfu.png', @@ -34,9 +34,9 @@ export const core = [ desc: 'Core team member of Vite & Vue. Working at NuxtLabs.', links: [ { icon: 'github', link: 'https://github.com/antfu' }, - { icon: 'twitter', link: 'https://twitter.com/antfu7' } + { icon: 'twitter', link: 'https://twitter.com/antfu7' }, ], - sponsor: 'https://github.com/sponsors/antfu' + sponsor: 'https://github.com/sponsors/antfu', }, { avatar: 'https://github.com/sodatea.png', @@ -47,9 +47,9 @@ export const core = [ desc: 'Vite/Vite core team member. Full-time open sourcerer.', links: [ { icon: 'github', link: 'https://github.com/sodatea' }, - { icon: 'twitter', link: 'https://twitter.com/haoqunjiang' } + { icon: 'twitter', link: 'https://twitter.com/haoqunjiang' }, ], - sponsor: 'https://github.com/sponsors/sodatea' + sponsor: 'https://github.com/sponsors/sodatea', }, { avatar: 'https://github.com/Shinigami92.png', @@ -60,9 +60,9 @@ export const core = [ desc: 'Passionate TypeScript enthusiast working extensively with Vue SPA and pug.', links: [ { icon: 'github', link: 'https://github.com/Shinigami92' }, - { icon: 'twitter', link: 'https://twitter.com/Shini_92' } + { icon: 'twitter', link: 'https://twitter.com/Shini_92' }, ], - sponsor: 'https://github.com/sponsors/Shinigami92' + sponsor: 'https://github.com/sponsors/Shinigami92', }, { avatar: 'https://i.imgur.com/KMed6rQ.jpeg', @@ -71,9 +71,9 @@ export const core = [ desc: 'Dabbling in social ecommerce, meta frameworks, and board games', links: [ { icon: 'github', link: 'https://github.com/aleclarson' }, - { icon: 'twitter', link: 'https://twitter.com/retropragma' } + { icon: 'twitter', link: 'https://twitter.com/retropragma' }, ], - sponsor: 'https://github.com/sponsors/aleclarson' + sponsor: 'https://github.com/sponsors/aleclarson', }, { avatar: 'https://github.com/bluwy.png', @@ -82,9 +82,9 @@ export const core = [ desc: 'Svelte and Vite team member. Something something opinions.', links: [ { icon: 'github', link: 'https://github.com/bluwy' }, - { icon: 'twitter', link: 'https://twitter.com/bluwyoo' } + { icon: 'twitter', link: 'https://twitter.com/bluwyoo' }, ], - sponsor: 'https://bjornlu.com/sponsor' + sponsor: 'https://bjornlu.com/sponsor', }, { avatar: 'https://github.com/poyoho.png', @@ -93,8 +93,8 @@ export const core = [ desc: 'Frontend. Vite team member.', links: [ { icon: 'github', link: 'https://github.com/poyoho' }, - { icon: 'twitter', link: 'https://twitter.com/yoho_po' } - ] + { icon: 'twitter', link: 'https://twitter.com/yoho_po' }, + ], }, { avatar: 'https://github.com/sapphi-red.png', @@ -103,9 +103,9 @@ export const core = [ desc: 'Vite team member. Call me sapphi or green or midori ;)', links: [ { icon: 'github', link: 'https://github.com/sapphi-red' }, - { icon: 'twitter', link: 'https://twitter.com/sapphi_red' } + { icon: 'twitter', link: 'https://twitter.com/sapphi_red' }, ], - sponsor: 'https://github.com/sponsors/sapphi-red' + sponsor: 'https://github.com/sponsors/sapphi-red', }, { avatar: 'https://github.com/ygj6.png', @@ -114,8 +114,8 @@ export const core = [ desc: 'Web Developer. Vue & Vite team member', links: [ { icon: 'github', link: 'https://github.com/ygj6' }, - { icon: 'twitter', link: 'https://twitter.com/ygj_66' } - ] + { icon: 'twitter', link: 'https://twitter.com/ygj_66' }, + ], }, { avatar: 'https://github.com/Niputi.png', @@ -125,9 +125,9 @@ export const core = [ desc: 'weeb/javascript lover.', links: [ { icon: 'github', link: 'https://github.com/Niputi' }, - { icon: 'twitter', link: 'https://twitter.com/Niputi_' } - ] - } + { icon: 'twitter', link: 'https://twitter.com/Niputi_' }, + ], + }, ] export const emeriti = [ @@ -135,18 +135,18 @@ export const emeriti = [ avatar: 'https://github.com/underfin.png', name: 'underfin', title: 'Developer', - links: [{ icon: 'github', link: 'https://github.com/underfin' }] + links: [{ icon: 'github', link: 'https://github.com/underfin' }], }, { avatar: 'https://github.com/GrygrFlzr.png', name: 'GrygrFlzr', title: 'Developer', - links: [{ icon: 'github', link: 'https://github.com/GrygrFlzr' }] + links: [{ icon: 'github', link: 'https://github.com/GrygrFlzr' }], }, { avatar: 'https://github.com/nihalgonsalves.png', name: 'Nihal Gonsalves', title: 'Senior Software Engineer', - links: [{ icon: 'github', link: 'https://github.com/nihalgonsalves' }] - } + links: [{ icon: 'github', link: 'https://github.com/nihalgonsalves' }], + }, ] diff --git a/docs/config/build-options.md b/docs/config/build-options.md index 2c60c838fa54ee..ce80c6cf1aaf94 100644 --- a/docs/config/build-options.md +++ b/docs/config/build-options.md @@ -42,7 +42,7 @@ type ResolveModulePreloadDependenciesFn = ( deps: string[], context: { importer: string - } + }, ) => (string | { runtime?: string })[] ``` diff --git a/docs/config/dep-optimization-options.md b/docs/config/dep-optimization-options.md index 729b6df7cac3f9..d4b74f26ec327e 100644 --- a/docs/config/dep-optimization-options.md +++ b/docs/config/dep-optimization-options.md @@ -22,8 +22,8 @@ CommonJS dependencies should not be excluded from optimization. If an ESM depend ```js export default defineConfig({ optimizeDeps: { - include: ['esm-dep > cjs-dep'] - } + include: ['esm-dep > cjs-dep'], + }, }) ``` diff --git a/docs/config/index.md b/docs/config/index.md index 965d5bdf60133b..56fbd4be10d853 100644 --- a/docs/config/index.md +++ b/docs/config/index.md @@ -98,8 +98,8 @@ export default defineConfig(({ command, mode }) => { return { // vite config define: { - __APP_ENV__: env.APP_ENV - } + __APP_ENV__: env.APP_ENV, + }, } }) ``` diff --git a/docs/config/preview-options.md b/docs/config/preview-options.md index 3604afb9576d42..2b4b9841b46bda 100644 --- a/docs/config/preview-options.md +++ b/docs/config/preview-options.md @@ -29,11 +29,11 @@ Specify server port. Note if the port is already being used, Vite will automatic ```js export default defineConfig({ server: { - port: 3030 + port: 3030, }, preview: { - port: 8080 - } + port: 8080, + }, }) ``` diff --git a/docs/config/server-options.md b/docs/config/server-options.md index 89287fe53cf98a..ebcbcbe95a3521 100644 --- a/docs/config/server-options.md +++ b/docs/config/server-options.md @@ -68,8 +68,8 @@ Automatically open the app in the browser on server start. When the value is a s ```js export default defineConfig({ server: { - open: '/docs/index.html' - } + open: '/docs/index.html', + }, }) ``` @@ -97,13 +97,13 @@ export default defineConfig({ '/api': { target: 'http://jsonplaceholder.typicode.com', changeOrigin: true, - rewrite: (path) => path.replace(/^\/api/, '') + rewrite: (path) => path.replace(/^\/api/, ''), }, // with RegEx: http://localhost:5173/fallback/ -> http://jsonplaceholder.typicode.com/ '^/fallback/.*': { target: 'http://jsonplaceholder.typicode.com', changeOrigin: true, - rewrite: (path) => path.replace(/^\/fallback/, '') + rewrite: (path) => path.replace(/^\/fallback/, ''), }, // Using the proxy instance '/api': { @@ -111,15 +111,15 @@ export default defineConfig({ changeOrigin: true, configure: (proxy, options) => { // proxy will be an instance of 'http-proxy' - } + }, }, // Proxying websockets or socket.io: ws://localhost:5173/socket.io -> ws://localhost:5174/socket.io '/socket.io': { target: 'ws://localhost:5174', - ws: true - } - } - } + ws: true, + }, + }, + }, }) ``` @@ -177,14 +177,14 @@ The Vite server watcher skips `.git/` and `node_modules/` directories by default export default defineConfig({ server: { watch: { - ignored: ['!**/node_modules/your-package-name/**'] - } + ignored: ['!**/node_modules/your-package-name/**'], + }, }, // The watched package must be excluded from optimization, // so that it can appear in the dependency graph and trigger hot reload. optimizeDeps: { - exclude: ['your-package-name'] - } + exclude: ['your-package-name'], + }, }) ``` @@ -222,7 +222,7 @@ async function createServer() { // Create Vite server in middleware mode const vite = await createViteServer({ server: { middlewareMode: true }, - appType: 'custom' // don't include Vite's default HTML handling middlewares + appType: 'custom', // don't include Vite's default HTML handling middlewares }) // Use vite's connect instance as middleware app.use(vite.middlewares) @@ -271,9 +271,9 @@ export default defineConfig({ server: { fs: { // Allow serving files from one level up to the project root - allow: ['..'] - } - } + allow: ['..'], + }, + }, }) ``` @@ -289,10 +289,10 @@ export default defineConfig({ // search up for workspace root searchForWorkspaceRoot(process.cwd()), // your custom rules - '/path/to/custom/allow' - ] - } - } + '/path/to/custom/allow', + ], + }, + }, }) ``` @@ -312,7 +312,7 @@ Defines the origin of the generated asset URLs during development. ```js export default defineConfig({ server: { - origin: 'http://127.0.0.1:8080' - } + origin: 'http://127.0.0.1:8080', + }, }) ``` diff --git a/docs/config/shared-options.md b/docs/config/shared-options.md index 671ef6be8f9924..fe04872a8770e4 100644 --- a/docs/config/shared-options.md +++ b/docs/config/shared-options.md @@ -69,7 +69,7 @@ Example: ```js const obj = { __NAME__, // Don't define object shorthand property names - __KEY__: value // Don't define object key + __KEY__: value, // Don't define object key } ``` @@ -233,13 +233,13 @@ export default defineConfig({ css: { preprocessorOptions: { scss: { - additionalData: `$injectedColor: orange;` + additionalData: `$injectedColor: orange;`, }, styl: { - additionalData: `$injectedColor ?= orange` - } - } - } + additionalData: `$injectedColor ?= orange`, + }, + }, + }, }) ``` @@ -277,8 +277,8 @@ Enabling this disables named imports. export default defineConfig({ esbuild: { jsxFactory: 'h', - jsxFragment: 'Fragment' - } + jsxFragment: 'Fragment', + }, }) ``` @@ -289,8 +289,8 @@ In addition, you can also use `esbuild.jsxInject` to automatically inject JSX he ```js export default defineConfig({ esbuild: { - jsxInject: `import React from 'react'` - } + jsxInject: `import React from 'react'`, + }, }) ``` @@ -315,7 +315,7 @@ The built-in asset type list can be found [here](https://github.com/vitejs/vite/ ```js export default defineConfig({ - assetsInclude: ['**/*.gltf'] + assetsInclude: ['**/*.gltf'], }) ``` diff --git a/docs/guide/api-hmr.md b/docs/guide/api-hmr.md index e160810301dcf8..1f23fdf8626a67 100644 --- a/docs/guide/api-hmr.md +++ b/docs/guide/api-hmr.md @@ -25,7 +25,7 @@ interface ViteHotContext { accept(dep: string, cb: (mod: ModuleNamespace | undefined) => void): void accept( deps: readonly string[], - cb: (mods: Array) => void + cb: (mods: Array) => void, ): void dispose(cb: (data: any) => void): void @@ -35,7 +35,7 @@ interface ViteHotContext { // `InferCustomEventPayload` provides types for built-in Vite events on( event: T, - cb: (payload: InferCustomEventPayload) => void + cb: (payload: InferCustomEventPayload) => void, ): void send(event: T, data?: InferCustomEventPayload): void } @@ -95,7 +95,7 @@ if (import.meta.hot) { ([newFooModule, newBarModule]) => { // The callback receives an array where only the updated module is non null // If the update was not succeful (syntax error for ex.), the array is empty - } + }, ) } ``` diff --git a/docs/guide/api-javascript.md b/docs/guide/api-javascript.md index 199507bc85b29e..935f509c5c1062 100644 --- a/docs/guide/api-javascript.md +++ b/docs/guide/api-javascript.md @@ -24,8 +24,8 @@ const __dirname = fileURLToPath(new URL('.', import.meta.url)) configFile: false, root: __dirname, server: { - port: 1337 - } + port: 1337, + }, }) await server.listen() @@ -102,7 +102,7 @@ interface ViteDevServer { */ transformRequest( url: string, - options?: TransformOptions + options?: TransformOptions, ): Promise /** * Apply Vite built-in HTML transforms and any plugin HTML transforms. @@ -113,7 +113,7 @@ interface ViteDevServer { */ ssrLoadModule( url: string, - options?: { fixStacktrace?: boolean } + options?: { fixStacktrace?: boolean }, ): Promise> /** * Fix ssr error stacktrace. @@ -147,7 +147,7 @@ interface ViteDevServer { ```ts async function build( - inlineConfig?: InlineConfig + inlineConfig?: InlineConfig, ): Promise ``` @@ -167,8 +167,8 @@ const __dirname = fileURLToPath(new URL('.', import.meta.url)) build: { rollupOptions: { // ... - } - } + }, + }, }) })() ``` @@ -190,8 +190,8 @@ import { preview } from 'vite' // any valid user config options, plus `mode` and `configFile` preview: { port: 8080, - open: true - } + open: true, + }, }) previewServer.printUrls() @@ -206,7 +206,7 @@ import { preview } from 'vite' async function resolveConfig( inlineConfig: InlineConfig, command: 'build' | 'serve', - defaultMode = 'development' + defaultMode = 'development', ): Promise ``` @@ -220,7 +220,7 @@ The `command` value is `serve` in dev (in the cli `vite`, `vite dev`, and `vite function mergeConfig( defaults: Record, overrides: Record, - isRoot = true + isRoot = true, ): Record ``` @@ -233,7 +233,7 @@ Deeply merge two Vite configs. `isRoot` represents the level within the Vite con ```ts function searchForWorkspaceRoot( current: string, - root = searchForPackageRoot(current) + root = searchForPackageRoot(current), ): string ``` @@ -254,7 +254,7 @@ Search for the root of the potential workspace if it meets the following conditi function loadEnv( mode: string, envDir: string, - prefixes: string | string[] = 'VITE_' + prefixes: string | string[] = 'VITE_', ): Record ``` @@ -283,7 +283,7 @@ async function transformWithEsbuild( code: string, filename: string, options?: EsbuildTransformOptions, - inMap?: object + inMap?: object, ): Promise ``` @@ -298,7 +298,7 @@ async function loadConfigFromFile( configEnv: ConfigEnv, configFile?: string, configRoot: string = process.cwd(), - logLevel?: LogLevel + logLevel?: LogLevel, ): Promise<{ path: string config: UserConfig diff --git a/docs/guide/api-plugin.md b/docs/guide/api-plugin.md index cd43e14c7200b2..2713a557fbc56b 100644 --- a/docs/guide/api-plugin.md +++ b/docs/guide/api-plugin.md @@ -48,7 +48,7 @@ import vitePlugin from 'vite-plugin-feature' import rollupPlugin from 'rollup-plugin-feature' export default defineConfig({ - plugins: [vitePlugin(), rollupPlugin()] + plugins: [vitePlugin(), rollupPlugin()], }) ``` @@ -72,7 +72,7 @@ import { defineConfig } from 'vite' import framework from 'vite-plugin-framework' export default defineConfig({ - plugins: [framework()] + plugins: [framework()], }) ``` @@ -95,10 +95,10 @@ export default function myPlugin() { if (fileRegex.test(id)) { return { code: compileFileToJS(src), - map: null // provide source map if available + map: null, // provide source map if available } } - } + }, } } ``` @@ -127,7 +127,7 @@ export default function myPlugin() { if (id === resolvedVirtualModuleId) { return `export const msg = "from virtual module"` } - } + }, } } ``` @@ -188,10 +188,10 @@ Vite plugins can also provide hooks that serve Vite-specific purposes. These hoo config: () => ({ resolve: { alias: { - foo: 'bar' - } - } - }) + foo: 'bar', + }, + }, + }), }) // mutate the config directly (use only when merging doesn't work) @@ -201,7 +201,7 @@ Vite plugins can also provide hooks that serve Vite-specific purposes. These hoo if (command === 'build') { config.root = 'foo' } - } + }, }) ``` @@ -237,7 +237,7 @@ Vite plugins can also provide hooks that serve Vite-specific purposes. These hoo } else { // build: plugin invoked by Rollup } - } + }, } } ``` @@ -259,7 +259,7 @@ Vite plugins can also provide hooks that serve Vite-specific purposes. These hoo server.middlewares.use((req, res, next) => { // custom handle request... }) - } + }, }) ``` @@ -278,7 +278,7 @@ Vite plugins can also provide hooks that serve Vite-specific purposes. These hoo // custom handle request... }) } - } + }, }) ``` @@ -298,7 +298,7 @@ Vite plugins can also provide hooks that serve Vite-specific purposes. These hoo if (server) { // use server... } - } + }, } } ``` @@ -323,7 +323,7 @@ Vite plugins can also provide hooks that serve Vite-specific purposes. These hoo // custom handle request... }) } - } + }, }) ``` @@ -349,9 +349,9 @@ Vite plugins can also provide hooks that serve Vite-specific purposes. These hoo transformIndexHtml(html) { return html.replace( /(.*?)<\/title>/, - `<title>Title replaced!` + `Title replaced!`, ) - } + }, } } ``` @@ -367,7 +367,7 @@ Vite plugins can also provide hooks that serve Vite-specific purposes. These hoo server?: ViteDevServer bundle?: import('rollup').OutputBundle chunk?: import('rollup').OutputChunk - } + }, ) => | IndexHtmlTransformResult | void @@ -459,7 +459,7 @@ By default plugins are invoked for both serve and build. In cases where a plugin function myPlugin() { return { name: 'build-only', - apply: 'build' // or 'serve' + apply: 'build', // or 'serve' } } ``` @@ -496,9 +496,9 @@ export default defineConfig({ { ...example(), enforce: 'post', - apply: 'build' - } - ] + apply: 'build', + }, + ], }) ``` @@ -537,9 +537,9 @@ export default defineConfig({ // ... configureServer(server) { server.ws.send('my:greetings', { msg: 'hello' }) - } - } - ] + }, + }, + ], }) ``` @@ -583,9 +583,9 @@ export default defineConfig({ // reply only to the client (if needed) client.send('my:ack', { msg: 'Hi! I got your message!' }) }) - } - } - ] + }, + }, + ], }) ``` diff --git a/docs/guide/backend-integration.md b/docs/guide/backend-integration.md index 535ccbb3e6127b..16ca394ce769a4 100644 --- a/docs/guide/backend-integration.md +++ b/docs/guide/backend-integration.md @@ -16,9 +16,9 @@ If you need a custom integration, you can follow the steps in this guide to conf manifest: true, rollupOptions: { // overwrite default .html entry - input: '/path/to/main.js' - } - } + input: '/path/to/main.js', + }, + }, }) ``` diff --git a/docs/guide/build.md b/docs/guide/build.md index 5b6ac8824c0aa4..3ed66361803fc1 100644 --- a/docs/guide/build.md +++ b/docs/guide/build.md @@ -39,8 +39,8 @@ export default defineConfig({ build: { rollupOptions: { // https://rollupjs.org/guide/en/#big-list-of-options - } - } + }, + }, }) ``` @@ -54,7 +54,7 @@ You can configure how chunks are split using `build.rollupOptions.output.manualC // vite.config.js import { splitVendorChunkPlugin } from 'vite' export default defineConfig({ - plugins: [splitVendorChunkPlugin()] + plugins: [splitVendorChunkPlugin()], }) ``` @@ -70,8 +70,8 @@ export default defineConfig({ build: { watch: { // https://rollupjs.org/guide/en/#watch-options - } - } + }, + }, }) ``` @@ -105,10 +105,10 @@ export default defineConfig({ rollupOptions: { input: { main: resolve(__dirname, 'index.html'), - nested: resolve(__dirname, 'nested/index.html') - } - } - } + nested: resolve(__dirname, 'nested/index.html'), + }, + }, + }, }) ``` @@ -132,7 +132,7 @@ export default defineConfig({ entry: resolve(__dirname, 'lib/main.js'), name: 'MyLib', // the proper extensions will be added - fileName: 'my-lib' + fileName: 'my-lib', }, rollupOptions: { // make sure to externalize deps that shouldn't be bundled @@ -142,11 +142,11 @@ export default defineConfig({ // Provide global variables to use in the UMD build // for externalized deps globals: { - vue: 'Vue' - } - } - } - } + vue: 'Vue', + }, + }, + }, + }, }) ``` diff --git a/docs/guide/dep-pre-bundling.md b/docs/guide/dep-pre-bundling.md index e0cc12ccc41276..5d5d98cac72645 100644 --- a/docs/guide/dep-pre-bundling.md +++ b/docs/guide/dep-pre-bundling.md @@ -47,13 +47,13 @@ However, this requires the linked dep to be exported as ESM. If not, you can add ```js export default defineConfig({ optimizeDeps: { - include: ['linked-dep'] + include: ['linked-dep'], }, build: { commonjsOptions: { - include: [/linked-dep/, /node_modules/] - } - } + include: [/linked-dep/, /node_modules/], + }, + }, }) ``` diff --git a/docs/guide/features.md b/docs/guide/features.md index e0aeff3d9fb86b..60cad69a6ce0be 100644 --- a/docs/guide/features.md +++ b/docs/guide/features.md @@ -140,8 +140,8 @@ import { defineConfig } from 'vite' export default defineConfig({ esbuild: { jsxFactory: 'h', - jsxFragment: 'Fragment' - } + jsxFragment: 'Fragment', + }, }) ``` @@ -155,8 +155,8 @@ import { defineConfig } from 'vite' export default defineConfig({ esbuild: { - jsxInject: `import React from 'react'` - } + jsxInject: `import React from 'react'`, + }, }) ``` @@ -294,7 +294,7 @@ The above will be transformed into the following: // code produced by vite const modules = { './dir/foo.js': () => import('./dir/foo.js'), - './dir/bar.js': () => import('./dir/bar.js') + './dir/bar.js': () => import('./dir/bar.js'), } ``` @@ -322,7 +322,7 @@ import * as __glob__0_0 from './dir/foo.js' import * as __glob__0_1 from './dir/bar.js' const modules = { './dir/foo.js': __glob__0_0, - './dir/bar.js': __glob__0_1 + './dir/bar.js': __glob__0_1, } ``` @@ -340,7 +340,7 @@ The above will be transformed into the following: // code produced by vite const modules = { './dir/foo.js': 'export default "foo"\n', - './dir/bar.js': 'export default "bar"\n' + './dir/bar.js': 'export default "bar"\n', } ``` @@ -365,7 +365,7 @@ const modules = import.meta.glob(['./dir/*.js', '!**/bar.js']) ```js // code produced by vite const modules = { - './dir/foo.js': () => import('./dir/foo.js') + './dir/foo.js': () => import('./dir/foo.js'), } ``` @@ -381,7 +381,7 @@ const modules = import.meta.glob('./dir/*.js', { import: 'setup' }) // code produced by vite const modules = { './dir/foo.js': () => import('./dir/foo.js').then((m) => m.setup), - './dir/bar.js': () => import('./dir/bar.js').then((m) => m.setup) + './dir/bar.js': () => import('./dir/bar.js').then((m) => m.setup), } ``` @@ -397,7 +397,7 @@ import { setup as __glob__0_0 } from './dir/foo.js' import { setup as __glob__0_1 } from './dir/bar.js' const modules = { './dir/foo.js': __glob__0_0, - './dir/bar.js': __glob__0_1 + './dir/bar.js': __glob__0_1, } ``` @@ -406,7 +406,7 @@ Set `import` to `default` to import the default export. ```ts const modules = import.meta.glob('./dir/*.js', { import: 'default', - eager: true + eager: true, }) ``` @@ -416,7 +416,7 @@ import __glob__0_0 from './dir/foo.js' import __glob__0_1 from './dir/bar.js' const modules = { './dir/foo.js': __glob__0_0, - './dir/bar.js': __glob__0_1 + './dir/bar.js': __glob__0_1, } ``` @@ -426,7 +426,7 @@ You can also use the `query` option to provide custom queries to imports for oth ```ts const modules = import.meta.glob('./dir/*.js', { - query: { foo: 'bar', bar: true } + query: { foo: 'bar', bar: true }, }) ``` @@ -436,7 +436,7 @@ const modules = { './dir/foo.js': () => import('./dir/foo.js?foo=bar&bar=true').then((m) => m.setup), './dir/bar.js': () => - import('./dir/bar.js?foo=bar&bar=true').then((m) => m.setup) + import('./dir/bar.js?foo=bar&bar=true').then((m) => m.setup), } ``` @@ -478,8 +478,8 @@ init({ imports: { someFunc: () => { /* ... */ - } - } + }, + }, }).then(() => { /* ... */ }) @@ -506,7 +506,7 @@ The worker constructor also accepts options, which can be used to create "module ```ts const worker = new Worker(new URL('./worker.js', import.meta.url), { - type: 'module' + type: 'module', }) ``` diff --git a/docs/guide/migration.md b/docs/guide/migration.md index c47207686af609..3fa4683a5b4d1f 100644 --- a/docs/guide/migration.md +++ b/docs/guide/migration.md @@ -98,7 +98,7 @@ Since Vite v3, we recommend manually creating your certificates. If you still wa import basicSsl from '@vitejs/plugin-basic-ssl' export default { - plugins: [basicSsl()] + plugins: [basicSsl()], } ``` diff --git a/docs/guide/ssr.md b/docs/guide/ssr.md index b4826d6a45ccfd..b4eee64df7166e 100644 --- a/docs/guide/ssr.md +++ b/docs/guide/ssr.md @@ -107,7 +107,7 @@ app.use('*', async (req, res, next) => { // 1. Read index.html let template = fs.readFileSync( path.resolve(__dirname, 'index.html'), - 'utf-8' + 'utf-8', ) // 2. Apply Vite HTML transforms. This injects the Vite HMR client, and @@ -237,7 +237,7 @@ export function mySSRPlugin() { if (options?.ssr) { // perform ssr-specific transform... } - } + }, } } ``` diff --git a/docs/guide/using-plugins.md b/docs/guide/using-plugins.md index b05c8c9f2223d3..8f6887594a197a 100644 --- a/docs/guide/using-plugins.md +++ b/docs/guide/using-plugins.md @@ -18,9 +18,9 @@ import { defineConfig } from 'vite' export default defineConfig({ plugins: [ legacy({ - targets: ['defaults', 'not IE 11'] - }) - ] + targets: ['defaults', 'not IE 11'], + }), + ], }) ``` @@ -55,9 +55,9 @@ export default defineConfig({ plugins: [ { ...image(), - enforce: 'pre' - } - ] + enforce: 'pre', + }, + ], }) ``` @@ -76,9 +76,9 @@ export default defineConfig({ plugins: [ { ...typescript2(), - apply: 'build' - } - ] + apply: 'build', + }, + ], }) ``` diff --git a/packages/create-vite/__tests__/cli.spec.ts b/packages/create-vite/__tests__/cli.spec.ts index f5d666c3577e28..35239f2707c2c3 100644 --- a/packages/create-vite/__tests__/cli.spec.ts +++ b/packages/create-vite/__tests__/cli.spec.ts @@ -11,7 +11,7 @@ const genPath = join(__dirname, projectName) const run = ( args: string[], - options: SyncOptions = {} + options: SyncOptions = {}, ): ExecaSyncReturnValue => { return execaCommandSync(`node ${CLI_PATH} ${args.join(' ')}`, options) } @@ -59,7 +59,7 @@ test('prompts for the framework on not supplying a value for --template', () => test('prompts for the framework on supplying an invalid template', () => { const { stdout } = run([projectName, '--template', 'unknown']) expect(stdout).toContain( - `"unknown" isn't a valid template. Please choose from below:` + `"unknown" isn't a valid template. Please choose from below:`, ) }) @@ -77,7 +77,7 @@ test('asks to overwrite non-empty current directory', () => { test('successfully scaffolds a project based on vue starter template', () => { const { stdout } = run([projectName, '--template', 'vue'], { - cwd: __dirname + cwd: __dirname, }) const generatedFiles = readdirSync(genPath).sort() @@ -88,7 +88,7 @@ test('successfully scaffolds a project based on vue starter template', () => { test('works with the -t alias', () => { const { stdout } = run([projectName, '-t', 'vue'], { - cwd: __dirname + cwd: __dirname, }) const generatedFiles = readdirSync(genPath).sort() diff --git a/packages/create-vite/build.config.ts b/packages/create-vite/build.config.ts index 2c39d19d427de6..3ec4f99bab2213 100644 --- a/packages/create-vite/build.config.ts +++ b/packages/create-vite/build.config.ts @@ -11,12 +11,12 @@ export default defineBuildConfig({ rollup: { inlineDependencies: true, esbuild: { - minify: true - } + minify: true, + }, }, alias: { // we can always use non-transpiled code since we support 14.18.0+ - prompts: 'prompts/lib/index.js' + prompts: 'prompts/lib/index.js', }, hooks: { 'rollup:options'(ctx, options) { @@ -27,9 +27,9 @@ export default defineBuildConfig({ licensePlugin( path.resolve(__dirname, './LICENSE'), 'create-vite license', - 'create-vite' - ) + 'create-vite', + ), ) - } - } + }, + }, }) diff --git a/packages/create-vite/src/index.ts b/packages/create-vite/src/index.ts index ce800f3eb23a24..f6bae6ebe82407 100755 --- a/packages/create-vite/src/index.ts +++ b/packages/create-vite/src/index.ts @@ -13,7 +13,7 @@ import { magenta, red, reset, - yellow + yellow, } from 'kolorist' // Avoids autoconversion to number of the project name by defining that the args @@ -47,14 +47,14 @@ const FRAMEWORKS: Framework[] = [ { name: 'vanilla', display: 'JavaScript', - color: yellow + color: yellow, }, { name: 'vanilla-ts', display: 'TypeScript', - color: blue - } - ] + color: blue, + }, + ], }, { name: 'vue', @@ -64,26 +64,26 @@ const FRAMEWORKS: Framework[] = [ { name: 'vue', display: 'JavaScript', - color: yellow + color: yellow, }, { name: 'vue-ts', display: 'TypeScript', - color: blue + color: blue, }, { name: 'custom-create-vue', display: 'Customize with create-vue ↗', color: green, - customCommand: 'npm create vue@latest TARGET_DIR' + customCommand: 'npm create vue@latest TARGET_DIR', }, { name: 'custom-nuxt', display: 'Nuxt ↗', color: lightGreen, - customCommand: 'npm exec nuxi init TARGET_DIR' - } - ] + customCommand: 'npm exec nuxi init TARGET_DIR', + }, + ], }, { name: 'react', @@ -93,14 +93,14 @@ const FRAMEWORKS: Framework[] = [ { name: 'react', display: 'JavaScript', - color: yellow + color: yellow, }, { name: 'react-ts', display: 'TypeScript', - color: blue - } - ] + color: blue, + }, + ], }, { name: 'preact', @@ -110,14 +110,14 @@ const FRAMEWORKS: Framework[] = [ { name: 'preact', display: 'JavaScript', - color: yellow + color: yellow, }, { name: 'preact-ts', display: 'TypeScript', - color: blue - } - ] + color: blue, + }, + ], }, { name: 'lit', @@ -127,14 +127,14 @@ const FRAMEWORKS: Framework[] = [ { name: 'lit', display: 'JavaScript', - color: yellow + color: yellow, }, { name: 'lit-ts', display: 'TypeScript', - color: blue - } - ] + color: blue, + }, + ], }, { name: 'svelte', @@ -144,20 +144,20 @@ const FRAMEWORKS: Framework[] = [ { name: 'svelte', display: 'JavaScript', - color: yellow + color: yellow, }, { name: 'svelte-ts', display: 'TypeScript', - color: blue + color: blue, }, { name: 'custom-svelte-kit', display: 'SvelteKit ↗', color: red, - customCommand: 'npm create svelte@latest TARGET_DIR' - } - ] + customCommand: 'npm create svelte@latest TARGET_DIR', + }, + ], }, { name: 'others', @@ -168,18 +168,18 @@ const FRAMEWORKS: Framework[] = [ name: 'create-vite-extra', display: 'create-vite-extra ↗', color: reset, - customCommand: 'npm create vite-extra@latest TARGET_DIR' - } - ] - } + customCommand: 'npm create vite-extra@latest TARGET_DIR', + }, + ], + }, ] const TEMPLATES = FRAMEWORKS.map( - (f) => (f.variants && f.variants.map((v) => v.name)) || [f.name] + (f) => (f.variants && f.variants.map((v) => v.name)) || [f.name], ).reduce((a, b) => a.concat(b), []) const renameFiles: Record = { - _gitignore: '.gitignore' + _gitignore: '.gitignore', } const defaultTargetDir = 'vite-project' @@ -206,7 +206,7 @@ async function init() { initial: defaultTargetDir, onState: (state) => { targetDir = formatTargetDir(state.value) || defaultTargetDir - } + }, }, { type: () => @@ -216,7 +216,7 @@ async function init() { (targetDir === '.' ? 'Current directory' : `Target directory "${targetDir}"`) + - ` is not empty. Remove existing files and continue?` + ` is not empty. Remove existing files and continue?`, }, { type: (_, { overwrite }: { overwrite?: boolean }) => { @@ -225,7 +225,7 @@ async function init() { } return null }, - name: 'overwriteChecker' + name: 'overwriteChecker', }, { type: () => (isValidPackageName(getProjectName()) ? null : 'text'), @@ -233,7 +233,7 @@ async function init() { message: reset('Package name:'), initial: () => toValidPackageName(getProjectName()), validate: (dir) => - isValidPackageName(dir) || 'Invalid package.json name' + isValidPackageName(dir) || 'Invalid package.json name', }, { type: @@ -242,7 +242,7 @@ async function init() { message: typeof argTemplate === 'string' && !TEMPLATES.includes(argTemplate) ? reset( - `"${argTemplate}" isn't a valid template. Please choose from below: ` + `"${argTemplate}" isn't a valid template. Please choose from below: `, ) : reset('Select a framework:'), initial: 0, @@ -250,9 +250,9 @@ async function init() { const frameworkColor = framework.color return { title: frameworkColor(framework.display || framework.name), - value: framework + value: framework, } - }) + }), }, { type: (framework: Framework) => @@ -264,16 +264,16 @@ async function init() { const variantColor = variant.color return { title: variantColor(variant.display || variant.name), - value: variant.name + value: variant.name, } - }) - } + }), + }, ], { onCancel: () => { throw new Error(red('✖') + ' Operation cancelled') - } - } + }, + }, ) } catch (cancelled: any) { console.log(cancelled.message) @@ -322,7 +322,7 @@ async function init() { const [command, ...args] = fullCustomCommand.split(' ') const { status } = spawn.sync(command, args, { - stdio: 'inherit' + stdio: 'inherit', }) process.exit(status ?? 0) } @@ -332,7 +332,7 @@ async function init() { const templateDir = path.resolve( fileURLToPath(import.meta.url), '../..', - `template-${template}` + `template-${template}`, ) const write = (file: string, content?: string) => { @@ -350,7 +350,7 @@ async function init() { } const pkg = JSON.parse( - fs.readFileSync(path.join(templateDir, `package.json`), 'utf-8') + fs.readFileSync(path.join(templateDir, `package.json`), 'utf-8'), ) pkg.name = packageName || getProjectName() @@ -389,7 +389,7 @@ function copy(src: string, dest: string) { function isValidPackageName(projectName: string) { return /^(?:@[a-z\d\-*~][a-z\d\-*._~]*\/)?[a-z\d\-~][a-z\d\-._~]*$/.test( - projectName + projectName, ) } @@ -434,7 +434,7 @@ function pkgFromUserAgent(userAgent: string | undefined) { const pkgSpecArr = pkgSpec.split('/') return { name: pkgSpecArr[0], - version: pkgSpecArr[1] + version: pkgSpecArr[1], } } diff --git a/packages/create-vite/template-lit-ts/vite.config.ts b/packages/create-vite/template-lit-ts/vite.config.ts index 14639f4b1c5178..fe69491e390523 100644 --- a/packages/create-vite/template-lit-ts/vite.config.ts +++ b/packages/create-vite/template-lit-ts/vite.config.ts @@ -5,10 +5,10 @@ export default defineConfig({ build: { lib: { entry: 'src/my-element.ts', - formats: ['es'] + formats: ['es'], }, rollupOptions: { - external: /^lit/ - } - } + external: /^lit/, + }, + }, }) diff --git a/packages/create-vite/template-lit/src/my-element.js b/packages/create-vite/template-lit/src/my-element.js index 7c0c0426e49116..effd159f8b5f2d 100644 --- a/packages/create-vite/template-lit/src/my-element.js +++ b/packages/create-vite/template-lit/src/my-element.js @@ -18,7 +18,7 @@ export class MyElement extends LitElement { /** * The number of times the button has been clicked. */ - count: { type: Number } + count: { type: Number }, } } diff --git a/packages/create-vite/template-lit/vite.config.js b/packages/create-vite/template-lit/vite.config.js index 45cfc00cd01365..3847c1f38466f1 100644 --- a/packages/create-vite/template-lit/vite.config.js +++ b/packages/create-vite/template-lit/vite.config.js @@ -5,10 +5,10 @@ export default defineConfig({ build: { lib: { entry: 'src/my-element.js', - formats: ['es'] + formats: ['es'], }, rollupOptions: { - external: /^lit/ - } - } + external: /^lit/, + }, + }, }) diff --git a/packages/create-vite/template-preact-ts/vite.config.ts b/packages/create-vite/template-preact-ts/vite.config.ts index e3bdaffe854595..29b326faf09c97 100644 --- a/packages/create-vite/template-preact-ts/vite.config.ts +++ b/packages/create-vite/template-preact-ts/vite.config.ts @@ -3,5 +3,5 @@ import preact from '@preact/preset-vite' // https://vitejs.dev/config/ export default defineConfig({ - plugins: [preact()] + plugins: [preact()], }) diff --git a/packages/create-vite/template-preact/vite.config.js b/packages/create-vite/template-preact/vite.config.js index e3bdaffe854595..29b326faf09c97 100644 --- a/packages/create-vite/template-preact/vite.config.js +++ b/packages/create-vite/template-preact/vite.config.js @@ -3,5 +3,5 @@ import preact from '@preact/preset-vite' // https://vitejs.dev/config/ export default defineConfig({ - plugins: [preact()] + plugins: [preact()], }) diff --git a/packages/create-vite/template-react-ts/src/main.tsx b/packages/create-vite/template-react-ts/src/main.tsx index 611e848f1a3e9c..791f139e242c70 100644 --- a/packages/create-vite/template-react-ts/src/main.tsx +++ b/packages/create-vite/template-react-ts/src/main.tsx @@ -6,5 +6,5 @@ import './index.css' ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render( - + , ) diff --git a/packages/create-vite/template-react-ts/vite.config.ts b/packages/create-vite/template-react-ts/vite.config.ts index b1b5f91e5ffd7f..5a33944a9b41b5 100644 --- a/packages/create-vite/template-react-ts/vite.config.ts +++ b/packages/create-vite/template-react-ts/vite.config.ts @@ -3,5 +3,5 @@ import react from '@vitejs/plugin-react' // https://vitejs.dev/config/ export default defineConfig({ - plugins: [react()] + plugins: [react()], }) diff --git a/packages/create-vite/template-react/src/main.jsx b/packages/create-vite/template-react/src/main.jsx index 9af0bb638e42c0..5cc599199a2091 100644 --- a/packages/create-vite/template-react/src/main.jsx +++ b/packages/create-vite/template-react/src/main.jsx @@ -6,5 +6,5 @@ import './index.css' ReactDOM.createRoot(document.getElementById('root')).render( - + , ) diff --git a/packages/create-vite/template-react/vite.config.js b/packages/create-vite/template-react/vite.config.js index b1b5f91e5ffd7f..5a33944a9b41b5 100644 --- a/packages/create-vite/template-react/vite.config.js +++ b/packages/create-vite/template-react/vite.config.js @@ -3,5 +3,5 @@ import react from '@vitejs/plugin-react' // https://vitejs.dev/config/ export default defineConfig({ - plugins: [react()] + plugins: [react()], }) diff --git a/packages/create-vite/template-svelte-ts/src/main.ts b/packages/create-vite/template-svelte-ts/src/main.ts index 5c1f795f9f55a6..8a909a15a0ebff 100644 --- a/packages/create-vite/template-svelte-ts/src/main.ts +++ b/packages/create-vite/template-svelte-ts/src/main.ts @@ -2,7 +2,7 @@ import './app.css' import App from './App.svelte' const app = new App({ - target: document.getElementById('app') + target: document.getElementById('app'), }) export default app diff --git a/packages/create-vite/template-svelte-ts/svelte.config.js b/packages/create-vite/template-svelte-ts/svelte.config.js index 3630bb3963b627..aa911a709460bf 100644 --- a/packages/create-vite/template-svelte-ts/svelte.config.js +++ b/packages/create-vite/template-svelte-ts/svelte.config.js @@ -3,5 +3,5 @@ import sveltePreprocess from 'svelte-preprocess' export default { // Consult https://github.com/sveltejs/svelte-preprocess // for more information about preprocessors - preprocess: sveltePreprocess() + preprocess: sveltePreprocess(), } diff --git a/packages/create-vite/template-svelte-ts/vite.config.ts b/packages/create-vite/template-svelte-ts/vite.config.ts index 401b4d4bd6b143..d70196943d0d24 100644 --- a/packages/create-vite/template-svelte-ts/vite.config.ts +++ b/packages/create-vite/template-svelte-ts/vite.config.ts @@ -3,5 +3,5 @@ import { svelte } from '@sveltejs/vite-plugin-svelte' // https://vitejs.dev/config/ export default defineConfig({ - plugins: [svelte()] + plugins: [svelte()], }) diff --git a/packages/create-vite/template-svelte/src/main.js b/packages/create-vite/template-svelte/src/main.js index 5c1f795f9f55a6..8a909a15a0ebff 100644 --- a/packages/create-vite/template-svelte/src/main.js +++ b/packages/create-vite/template-svelte/src/main.js @@ -2,7 +2,7 @@ import './app.css' import App from './App.svelte' const app = new App({ - target: document.getElementById('app') + target: document.getElementById('app'), }) export default app diff --git a/packages/create-vite/template-svelte/vite.config.js b/packages/create-vite/template-svelte/vite.config.js index 401b4d4bd6b143..d70196943d0d24 100644 --- a/packages/create-vite/template-svelte/vite.config.js +++ b/packages/create-vite/template-svelte/vite.config.js @@ -3,5 +3,5 @@ import { svelte } from '@sveltejs/vite-plugin-svelte' // https://vitejs.dev/config/ export default defineConfig({ - plugins: [svelte()] + plugins: [svelte()], }) diff --git a/packages/create-vite/template-vue-ts/vite.config.ts b/packages/create-vite/template-vue-ts/vite.config.ts index 315212d69a7ba5..05c17402a4a92b 100644 --- a/packages/create-vite/template-vue-ts/vite.config.ts +++ b/packages/create-vite/template-vue-ts/vite.config.ts @@ -3,5 +3,5 @@ import vue from '@vitejs/plugin-vue' // https://vitejs.dev/config/ export default defineConfig({ - plugins: [vue()] + plugins: [vue()], }) diff --git a/packages/create-vite/template-vue/src/components/HelloWorld.vue b/packages/create-vite/template-vue/src/components/HelloWorld.vue index 91f9bfcbcb305d..d3c3f15cde9911 100644 --- a/packages/create-vite/template-vue/src/components/HelloWorld.vue +++ b/packages/create-vite/template-vue/src/components/HelloWorld.vue @@ -2,7 +2,7 @@ import { ref } from 'vue' defineProps({ - msg: String + msg: String, }) const count = ref(0) diff --git a/packages/create-vite/template-vue/vite.config.js b/packages/create-vite/template-vue/vite.config.js index 315212d69a7ba5..05c17402a4a92b 100644 --- a/packages/create-vite/template-vue/vite.config.js +++ b/packages/create-vite/template-vue/vite.config.js @@ -3,5 +3,5 @@ import vue from '@vitejs/plugin-vue' // https://vitejs.dev/config/ export default defineConfig({ - plugins: [vue()] + plugins: [vue()], }) diff --git a/packages/plugin-legacy/README.md b/packages/plugin-legacy/README.md index 708ba6059561f1..2b12552632a5d3 100644 --- a/packages/plugin-legacy/README.md +++ b/packages/plugin-legacy/README.md @@ -21,9 +21,9 @@ import legacy from '@vitejs/plugin-legacy' export default { plugins: [ legacy({ - targets: ['defaults', 'not IE 11'] - }) - ] + targets: ['defaults', 'not IE 11'], + }), + ], } ``` @@ -104,9 +104,9 @@ npm add -D terser modernPolyfills: [ /* ... */ ], - renderLegacyChunks: false - }) - ] + renderLegacyChunks: false, + }), + ], } ``` @@ -141,9 +141,9 @@ export default { plugins: [ legacy({ polyfills: ['es.promise.finally', 'es/map', 'es/set'], - modernPolyfills: ['es.promise.finally'] - }) - ] + modernPolyfills: ['es.promise.finally'], + }), + ], } ``` diff --git a/packages/plugin-legacy/build.config.ts b/packages/plugin-legacy/build.config.ts index 12afbbc54d1efd..db325ecfa3b0a8 100644 --- a/packages/plugin-legacy/build.config.ts +++ b/packages/plugin-legacy/build.config.ts @@ -6,6 +6,6 @@ export default defineBuildConfig({ declaration: true, rollup: { emitCJS: true, - inlineDependencies: true - } + inlineDependencies: true, + }, }) diff --git a/packages/plugin-legacy/src/index.ts b/packages/plugin-legacy/src/index.ts index b131727849f1f0..41f76470d0b13a 100644 --- a/packages/plugin-legacy/src/index.ts +++ b/packages/plugin-legacy/src/index.ts @@ -9,14 +9,14 @@ import type { BuildOptions, HtmlTagDescriptor, Plugin, - ResolvedConfig + ResolvedConfig, } from 'vite' import type { NormalizedOutputOptions, OutputBundle, OutputOptions, PreRenderedChunk, - RenderedChunk + RenderedChunk, } from 'rollup' import type { PluginItem as BabelPlugin } from '@babel/core' import colors from 'picocolors' @@ -40,7 +40,7 @@ function toOutputFilePathInHtml( hostId: string, hostType: 'js' | 'css' | 'html', config: ResolvedConfig, - toRelative: (filename: string, importer: string) => string + toRelative: (filename: string, importer: string) => string, ): string { const { renderBuiltUrl } = config.experimental let relative = config.base === '' || config.base === './' @@ -49,12 +49,12 @@ function toOutputFilePathInHtml( hostId, hostType, type, - ssr: !!config.build.ssr + ssr: !!config.build.ssr, }) if (typeof result === 'object') { if (result.runtime) { throw new Error( - `{ runtime: "${result.runtime}" } is not supported for assets in ${hostType} files: ${filename}` + `{ runtime: "${result.runtime}" } is not supported for assets in ${hostType} files: ${filename}`, ) } if (typeof result.relative === 'boolean') { @@ -76,7 +76,7 @@ function getBaseInHTML(urlRelativePath: string, config: ResolvedConfig) { return config.base === './' || config.base === '' ? path.posix.join( path.posix.relative(urlRelativePath, '').slice(0, -2), - './' + './', ) : config.base } @@ -84,7 +84,7 @@ function getBaseInHTML(urlRelativePath: string, config: ResolvedConfig) { function toAssetPathFromHtml( filename: string, htmlPath: string, - config: ResolvedConfig + config: ResolvedConfig, ): string { const relativeUrlPath = normalizePath(path.relative(config.root, htmlPath)) const toRelative = (filename: string, hostId: string) => @@ -95,7 +95,7 @@ function toAssetPathFromHtml( htmlPath, 'html', config, - toRelative + toRelative, ) } @@ -136,7 +136,7 @@ function viteLegacyPlugin(options: Options = {}): Plugin[] { if (Array.isArray(options.modernPolyfills)) { options.modernPolyfills.forEach((i) => { modernPolyfills.add( - i.includes('/') ? `core-js/${i}` : `core-js/modules/${i}.js` + i.includes('/') ? `core-js/${i}` : `core-js/modules/${i}.js`, ) }) } @@ -146,7 +146,7 @@ function viteLegacyPlugin(options: Options = {}): Plugin[] { legacyPolyfills.add(`regenerator-runtime/runtime.js`) } else { legacyPolyfills.add( - i.includes('/') ? `core-js/${i}` : `core-js/modules/${i}.js` + i.includes('/') ? `core-js/${i}` : `core-js/modules/${i}.js`, ) } }) @@ -186,7 +186,7 @@ function viteLegacyPlugin(options: Options = {}): Plugin[] { 'edge79', 'firefox67', 'chrome64', - 'safari11.1' + 'safari11.1', ] } } @@ -196,19 +196,19 @@ function viteLegacyPlugin(options: Options = {}): Plugin[] { 'import.meta.env.LEGACY': env.command === 'serve' || config.build?.ssr ? false - : legacyEnvVarMarker - } + : legacyEnvVarMarker, + }, } }, configResolved(config) { if (overriddenBuildTarget) { config.logger.warn( colors.yellow( - `plugin-legacy overrode 'build.target'. You should pass 'targets' as an option to this plugin with the list of legacy browsers to support instead.` - ) + `plugin-legacy overrode 'build.target'. You should pass 'targets' as an option to this plugin with the list of legacy browsers to support instead.`, + ), ) } - } + }, } const legacyGenerateBundlePlugin: Plugin = { @@ -227,7 +227,7 @@ function viteLegacyPlugin(options: Options = {}): Plugin[] { isDebug && console.log( `[@vitejs/plugin-legacy] modern polyfills:`, - modernPolyfills + modernPolyfills, ) await buildPolyfillChunk( config.mode, @@ -237,7 +237,7 @@ function viteLegacyPlugin(options: Options = {}): Plugin[] { config.build, 'es', opts, - true + true, ) return } @@ -253,13 +253,13 @@ function viteLegacyPlugin(options: Options = {}): Plugin[] { await detectPolyfills( `Promise.resolve(); Promise.all();`, targets, - legacyPolyfills + legacyPolyfills, ) isDebug && console.log( `[@vitejs/plugin-legacy] legacy polyfills:`, - legacyPolyfills + legacyPolyfills, ) await buildPolyfillChunk( @@ -272,10 +272,10 @@ function viteLegacyPlugin(options: Options = {}): Plugin[] { config.build, 'iife', opts, - options.externalSystemJS + options.externalSystemJS, ) } - } + }, } const legacyPostPlugin: Plugin = { @@ -298,7 +298,7 @@ function viteLegacyPlugin(options: Options = {}): Plugin[] { | string | ((chunkInfo: PreRenderedChunk) => string) | undefined, - defaultFileName = '[name]-legacy-[hash].js' + defaultFileName = '[name]-legacy-[hash].js', ): string | ((chunkInfo: PreRenderedChunk) => string) => { if (!fileNames) { return path.posix.join(config.build.assetsDir, defaultFileName) @@ -321,13 +321,13 @@ function viteLegacyPlugin(options: Options = {}): Plugin[] { } const createLegacyOutput = ( - options: OutputOptions = {} + options: OutputOptions = {}, ): OutputOptions => { return { ...options, format: 'system', entryFileNames: getLegacyOutputFileName(options.entryFileNames), - chunkFileNames: getLegacyOutputFileName(options.chunkFileNames) + chunkFileNames: getLegacyOutputFileName(options.chunkFileNames), } } @@ -367,7 +367,7 @@ function viteLegacyPlugin(options: Options = {}): Plugin[] { ms.overwrite( match.index, match.index + legacyEnvVarMarker.length, - `false` + `false`, ) } } @@ -375,11 +375,11 @@ function viteLegacyPlugin(options: Options = {}): Plugin[] { if (config.build.sourcemap) { return { code: ms.toString(), - map: ms.generateMap({ hires: true }) + map: ms.generateMap({ hires: true }), } } return { - code: ms.toString() + code: ms.toString(), } } @@ -424,18 +424,18 @@ function viteLegacyPlugin(options: Options = {}): Plugin[] { plugins: [ recordAndRemovePolyfillBabelPlugin(legacyPolyfills), replaceLegacyEnvBabelPlugin(), - wrapIIFEBabelPlugin() - ] - }) + wrapIIFEBabelPlugin(), + ], + }), ], [ 'env', createBabelPresetEnvOptions(targets, { needPolyfills, - ignoreBrowserslistConfig: options.ignoreBrowserslistConfig - }) - ] - ] + ignoreBrowserslistConfig: options.ignoreBrowserslistConfig, + }), + ], + ], }) if (code) return { code, map } @@ -457,7 +457,7 @@ function viteLegacyPlugin(options: Options = {}): Plugin[] { // 1. inject modern polyfills const modernPolyfillFilename = facadeToModernPolyfillMap.get( - chunk.facadeModuleId + chunk.facadeModuleId, ) if (modernPolyfillFilename) { @@ -469,13 +469,13 @@ function viteLegacyPlugin(options: Options = {}): Plugin[] { src: toAssetPathFromHtml( modernPolyfillFilename, chunk.facadeModuleId!, - config - ) - } + config, + ), + }, }) } else if (modernPolyfills.size) { throw new Error( - `No corresponding modern polyfill chunk found for ${htmlFilename}` + `No corresponding modern polyfill chunk found for ${htmlFilename}`, ) } @@ -488,12 +488,12 @@ function viteLegacyPlugin(options: Options = {}): Plugin[] { tag: 'script', attrs: { nomodule: true }, children: safari10NoModuleFix, - injectTo: 'body' + injectTo: 'body', }) // 3. inject legacy polyfills const legacyPolyfillFilename = facadeToLegacyPolyfillMap.get( - chunk.facadeModuleId + chunk.facadeModuleId, ) if (legacyPolyfillFilename) { tags.push({ @@ -505,20 +505,20 @@ function viteLegacyPlugin(options: Options = {}): Plugin[] { src: toAssetPathFromHtml( legacyPolyfillFilename, chunk.facadeModuleId!, - config - ) + config, + ), }, - injectTo: 'body' + injectTo: 'body', }) } else if (legacyPolyfills.size) { throw new Error( - `No corresponding legacy polyfill chunk found for ${htmlFilename}` + `No corresponding legacy polyfill chunk found for ${htmlFilename}`, ) } // 4. inject legacy entry const legacyEntryFilename = facadeToLegacyChunkMap.get( - chunk.facadeModuleId + chunk.facadeModuleId, ) if (legacyEntryFilename) { // `assets/foo.js` means importing "named register" in SystemJS @@ -534,15 +534,15 @@ function viteLegacyPlugin(options: Options = {}): Plugin[] { 'data-src': toAssetPathFromHtml( legacyEntryFilename, chunk.facadeModuleId!, - config - ) + config, + ), }, children: systemJSInlineCode, - injectTo: 'body' + injectTo: 'body', }) } else { throw new Error( - `No corresponding legacy entry chunk found for ${htmlFilename}` + `No corresponding legacy entry chunk found for ${htmlFilename}`, ) } @@ -552,19 +552,19 @@ function viteLegacyPlugin(options: Options = {}): Plugin[] { tag: 'script', attrs: { type: 'module' }, children: detectModernBrowserCode, - injectTo: 'head' + injectTo: 'head', }) tags.push({ tag: 'script', attrs: { type: 'module' }, children: dynamicFallbackInlineCode, - injectTo: 'head' + injectTo: 'head', }) } return { html, - tags + tags, } }, @@ -581,7 +581,7 @@ function viteLegacyPlugin(options: Options = {}): Plugin[] { } } } - } + }, } return [legacyConfigPlugin, legacyGenerateBundlePlugin, legacyPostPlugin] @@ -590,7 +590,7 @@ function viteLegacyPlugin(options: Options = {}): Plugin[] { export async function detectPolyfills( code: string, targets: any, - list: Set + list: Set, ): Promise { const babel = await loadBabel() const { ast } = babel.transform(code, { @@ -600,9 +600,11 @@ export async function detectPolyfills( presets: [ [ 'env', - createBabelPresetEnvOptions(targets, { ignoreBrowserslistConfig: true }) - ] - ] + createBabelPresetEnvOptions(targets, { + ignoreBrowserslistConfig: true, + }), + ], + ], }) for (const node of ast!.program.body) { if (node.type === 'ImportDeclaration') { @@ -621,8 +623,8 @@ function createBabelPresetEnvOptions( targets: any, { needPolyfills = true, - ignoreBrowserslistConfig - }: { needPolyfills?: boolean; ignoreBrowserslistConfig?: boolean } + ignoreBrowserslistConfig, + }: { needPolyfills?: boolean; ignoreBrowserslistConfig?: boolean }, ) { return { targets, @@ -633,11 +635,11 @@ function createBabelPresetEnvOptions( corejs: needPolyfills ? { version: _require('core-js/package.json').version, - proposals: false + proposals: false, } : undefined, shippedProposals: true, - ignoreBrowserslistConfig + ignoreBrowserslistConfig, } } @@ -649,7 +651,7 @@ async function buildPolyfillChunk( buildOptions: BuildOptions, format: 'iife' | 'es', rollupOutputOptions: NormalizedOutputOptions, - excludeSystemJS?: boolean + excludeSystemJS?: boolean, ) { let { minify, assetsDir } = buildOptions minify = minify ? 'terser' : false @@ -666,13 +668,13 @@ async function buildPolyfillChunk( assetsDir, rollupOptions: { input: { - polyfills: polyfillId + polyfills: polyfillId, }, output: { format, - entryFileNames: rollupOutputOptions.entryFileNames - } - } + entryFileNames: rollupOutputOptions.entryFileNames, + }, + }, }, // Don't run esbuild for transpilation or minification // because we don't want to transpile code. @@ -683,9 +685,9 @@ async function buildPolyfillChunk( // This limits the input code not to include es2015+ codes. // But core-js is the only dependency which includes commonjs code // and core-js doesn't include es2015+ codes. - target: 'es5' - } - } + target: 'es5', + }, + }, }) const _polyfillChunk = Array.isArray(res) ? res[0] : res if (!('output' in _polyfillChunk)) return @@ -708,7 +710,7 @@ const polyfillId = '\0vite/legacy-polyfills' function polyfillsPlugin( imports: Set, - excludeSystemJS?: boolean + excludeSystemJS?: boolean, ): Plugin { return { name: 'vite:legacy-polyfills', @@ -724,7 +726,7 @@ function polyfillsPlugin( (excludeSystemJS ? '' : `import "systemjs/dist/s.min.js";`) ) } - } + }, } } @@ -734,11 +736,11 @@ function isLegacyChunk(chunk: RenderedChunk, options: NormalizedOutputOptions) { function isLegacyBundle( bundle: OutputBundle, - options: NormalizedOutputOptions + options: NormalizedOutputOptions, ) { if (options.format === 'system') { const entryChunk = Object.values(bundle).find( - (output) => output.type === 'chunk' && output.isEntry + (output) => output.type === 'chunk' && output.isEntry, ) return !!entryChunk && entryChunk.fileName.includes('-legacy') @@ -748,7 +750,7 @@ function isLegacyBundle( } function recordAndRemovePolyfillBabelPlugin( - polyfills: Set + polyfills: Set, ): BabelPlugin { return ({ types: t }): BabelPlugin => ({ name: 'vite-remove-polyfill-import', @@ -760,7 +762,7 @@ function recordAndRemovePolyfillBabelPlugin( p.remove() } }) - } + }, }) } @@ -772,8 +774,8 @@ function replaceLegacyEnvBabelPlugin(): BabelPlugin { if (path.node.name === legacyEnvVarMarker) { path.replaceWith(t.booleanLiteral(true)) } - } - } + }, + }, }) } @@ -788,7 +790,7 @@ function wrapIIFEBabelPlugin(): BabelPlugin { this.isWrapped = true path.replaceWith(t.program(buildIIFE({ body: path.node.body }))) } - } + }, } } } @@ -797,7 +799,7 @@ export const cspHashes = [ createHash('sha256').update(safari10NoModuleFix).digest('base64'), createHash('sha256').update(systemJSInlineCode).digest('base64'), createHash('sha256').update(detectModernBrowserCode).digest('base64'), - createHash('sha256').update(dynamicFallbackInlineCode).digest('base64') + createHash('sha256').update(dynamicFallbackInlineCode).digest('base64'), ] export default viteLegacyPlugin diff --git a/packages/vite/bin/vite.js b/packages/vite/bin/vite.js index 13e9529510e4a3..a9bbb9c3a54716 100755 --- a/packages/vite/bin/vite.js +++ b/packages/vite/bin/vite.js @@ -13,7 +13,7 @@ global.__vite_start_time = performance.now() // check debug mode first before requiring the CLI. const debugIndex = process.argv.findIndex((arg) => /^(?:-d|--debug)$/.test(arg)) const filterIndex = process.argv.findIndex((arg) => - /^(?:-f|--filter)$/.test(arg) + /^(?:-f|--filter)$/.test(arg), ) const profileIndex = process.argv.indexOf('--profile') diff --git a/packages/vite/client.d.ts b/packages/vite/client.d.ts index f3d7436b3fedf2..a7182c8fd454d9 100644 --- a/packages/vite/client.d.ts +++ b/packages/vite/client.d.ts @@ -212,7 +212,7 @@ declare module '*.txt' { // wasm?init declare module '*.wasm?init' { const initWasm: ( - options: WebAssembly.Imports + options: WebAssembly.Imports, ) => Promise export default initWasm } diff --git a/packages/vite/index.cjs b/packages/vite/index.cjs index 525b1b7e59f84d..6854011bce42a1 100644 --- a/packages/vite/index.cjs +++ b/packages/vite/index.cjs @@ -16,7 +16,7 @@ const asyncFunctions = [ 'optimizeDeps', 'formatPostcssSourceMap', 'loadConfigFromFile', - 'preprocessCSS' + 'preprocessCSS', ] asyncFunctions.forEach((name) => { module.exports[name] = (...args) => @@ -28,7 +28,7 @@ const unsupportedCJS = ['resolvePackageEntry', 'resolvePackageData'] unsupportedCJS.forEach((name) => { module.exports[name] = () => { throw new Error( - `"${name}" is not supported in CJS build of Vite 3.\nPlease use ESM or dynamic imports \`const { ${name} } = await import('vite')\`.` + `"${name}" is not supported in CJS build of Vite 3.\nPlease use ESM or dynamic imports \`const { ${name} } = await import('vite')\`.`, ) } }) diff --git a/packages/vite/rollup.config.ts b/packages/vite/rollup.config.ts index e25beca7b2fd6e..80b00b80822ac4 100644 --- a/packages/vite/rollup.config.ts +++ b/packages/vite/rollup.config.ts @@ -11,7 +11,7 @@ import { defineConfig } from 'rollup' import licensePlugin from '../../scripts/rollupLicensePlugin.mjs' const pkg = JSON.parse( - readFileSync(new URL('./package.json', import.meta.url)).toString() + readFileSync(new URL('./package.json', import.meta.url)).toString(), ) const __dirname = fileURLToPath(new URL('.', import.meta.url)) @@ -20,13 +20,13 @@ const envConfig = defineConfig({ input: path.resolve(__dirname, 'src/client/env.ts'), plugins: [ typescript({ - tsconfig: path.resolve(__dirname, 'src/client/tsconfig.json') - }) + tsconfig: path.resolve(__dirname, 'src/client/tsconfig.json'), + }), ], output: { file: path.resolve(__dirname, 'dist/client', 'env.mjs'), - sourcemap: true - } + sourcemap: true, + }, }) const clientConfig = defineConfig({ @@ -34,20 +34,20 @@ const clientConfig = defineConfig({ external: ['./env', '@vite/env'], plugins: [ typescript({ - tsconfig: path.resolve(__dirname, 'src/client/tsconfig.json') - }) + tsconfig: path.resolve(__dirname, 'src/client/tsconfig.json'), + }), ], output: { file: path.resolve(__dirname, 'dist/client', 'client.mjs'), - sourcemap: true - } + sourcemap: true, + }, }) const sharedNodeOptions = defineConfig({ treeshake: { moduleSideEffects: 'no-external', propertyReadSideEffects: false, - tryCatchDeoptimization: false + tryCatchDeoptimization: false, }, output: { dir: path.resolve(__dirname, 'dist'), @@ -56,7 +56,7 @@ const sharedNodeOptions = defineConfig({ exports: 'named', format: 'esm', externalLiveBindings: false, - freeze: false + freeze: false, }, onwarn(warning, warn) { // node-resolve complains a lot about this but seems to still work? @@ -71,13 +71,13 @@ const sharedNodeOptions = defineConfig({ return } warn(warning) - } + }, }) function createNodePlugins( isProduction: boolean, sourceMap: boolean, - declarationDir: string | false + declarationDir: string | false, ): Plugin[] { return [ nodeResolve({ preferBuiltins: true }), @@ -85,7 +85,7 @@ function createNodePlugins( tsconfig: path.resolve(__dirname, 'src/node/tsconfig.json'), sourceMap, declaration: declarationDir !== false, - declarationDir: declarationDir !== false ? declarationDir : undefined + declarationDir: declarationDir !== false ? declarationDir : undefined, }), // Some deps have try...catch require of optional deps, but rollup will @@ -96,38 +96,38 @@ function createNodePlugins( // chokidar -> fsevents 'fsevents-handler.js': { src: `require('fsevents')`, - replacement: `__require('fsevents')` + replacement: `__require('fsevents')`, }, // postcss-import -> sugarss 'process-content.js': { src: 'require("sugarss")', - replacement: `__require('sugarss')` + replacement: `__require('sugarss')`, }, 'lilconfig/dist/index.js': { pattern: /: require,/g, - replacement: `: __require,` + replacement: `: __require,`, }, // postcss-load-config calls require after register ts-node 'postcss-load-config/src/index.js': { pattern: /require(?=\((configFile|'ts-node')\))/g, - replacement: `eval('require')` - } + replacement: `eval('require')`, + }, }), commonjs({ extensions: ['.js'], // Optional peer deps of ws. Native deps that are mostly for performance. // Since ws is not that perf critical for us, just ignore these deps. - ignore: ['bufferutil', 'utf-8-validate'] + ignore: ['bufferutil', 'utf-8-validate'], }), json(), isProduction && licensePlugin( path.resolve(__dirname, 'LICENSE.md'), 'Vite core license', - 'Vite' + 'Vite', ), - cjsPatchPlugin() + cjsPatchPlugin(), ] } @@ -137,24 +137,24 @@ function createNodeConfig(isProduction: boolean) { input: { index: path.resolve(__dirname, 'src/node/index.ts'), cli: path.resolve(__dirname, 'src/node/cli.ts'), - constants: path.resolve(__dirname, 'src/node/constants.ts') + constants: path.resolve(__dirname, 'src/node/constants.ts'), }, output: { ...sharedNodeOptions.output, - sourcemap: !isProduction + sourcemap: !isProduction, }, external: [ 'fsevents', ...Object.keys(pkg.dependencies), - ...(isProduction ? [] : Object.keys(pkg.devDependencies)) + ...(isProduction ? [] : Object.keys(pkg.devDependencies)), ], plugins: createNodePlugins( isProduction, !isProduction, // in production we use api-extractor for dts generation // in development we need to rely on the rollup ts plugin - isProduction ? false : path.resolve(__dirname, 'dist/node') - ) + isProduction ? false : path.resolve(__dirname, 'dist/node'), + ), }) } @@ -162,7 +162,7 @@ function createCjsConfig(isProduction: boolean) { return defineConfig({ ...sharedNodeOptions, input: { - publicUtils: path.resolve(__dirname, 'src/node/publicUtils.ts') + publicUtils: path.resolve(__dirname, 'src/node/publicUtils.ts'), }, output: { dir: path.resolve(__dirname, 'dist'), @@ -172,14 +172,14 @@ function createCjsConfig(isProduction: boolean) { format: 'cjs', externalLiveBindings: false, freeze: false, - sourcemap: false + sourcemap: false, }, external: [ 'fsevents', ...Object.keys(pkg.dependencies), - ...(isProduction ? [] : Object.keys(pkg.devDependencies)) + ...(isProduction ? [] : Object.keys(pkg.devDependencies)), ], - plugins: [...createNodePlugins(false, false, false), bundleSizeLimit(120)] + plugins: [...createNodePlugins(false, false, false), bundleSizeLimit(120)], }) } @@ -191,7 +191,7 @@ export default (commandLineArgs: any): RollupOptions[] => { envConfig, clientConfig, createNodeConfig(isProduction), - createCjsConfig(isProduction) + createCjsConfig(isProduction), ]) } @@ -218,7 +218,7 @@ function shimDepsPlugin(deps: Record): Plugin { const pos = code.indexOf(src) if (pos < 0) { this.error( - `Could not find expected src "${src}" in file "${file}"` + `Could not find expected src "${src}" in file "${file}"`, ) } transformed[file] = true @@ -236,7 +236,7 @@ function shimDepsPlugin(deps: Record): Plugin { } if (!transformed[file]) { this.error( - `Could not find expected pattern "${pattern}" in file "${file}"` + `Could not find expected pattern "${pattern}" in file "${file}"`, ) } console.log(`shimmed: ${file}`) @@ -244,7 +244,7 @@ function shimDepsPlugin(deps: Record): Plugin { return { code: magicString.toString(), - map: magicString.generateMap({ hires: true }) + map: magicString.generateMap({ hires: true }), } } } @@ -254,12 +254,12 @@ function shimDepsPlugin(deps: Record): Plugin { for (const file in deps) { if (!transformed[file]) { this.error( - `Did not find "${file}" which is supposed to be shimmed, was the file renamed?` + `Did not find "${file}" which is supposed to be shimmed, was the file renamed?`, ) } } } - } + }, } } @@ -292,9 +292,9 @@ const __require = require; return { code: s.toString(), - map: s.generateMap() + map: s.generateMap(), } - } + }, } } @@ -311,15 +311,17 @@ function bundleSizeLimit(limit: number): Plugin { Object.values(bundle) .map((i) => ('code' in i ? i.code : '')) .join(''), - 'utf-8' + 'utf-8', ) const kb = size / 1024 if (kb > limit) { throw new Error( - `Bundle size exceeded ${limit}kb, current size is ${kb.toFixed(2)}kb.` + `Bundle size exceeded ${limit}kb, current size is ${kb.toFixed( + 2, + )}kb.`, ) } - } + }, } } diff --git a/packages/vite/scripts/prePatchTypes.ts b/packages/vite/scripts/prePatchTypes.ts index eda006b476209d..daa7463a619ca9 100644 --- a/packages/vite/scripts/prePatchTypes.ts +++ b/packages/vite/scripts/prePatchTypes.ts @@ -14,7 +14,7 @@ rewriteImports(tempDir, (importPath, currentFile) => { if (importPath.startsWith('dep-types/')) { const absoluteTypePath = resolve( depTypesDir, - importPath.slice('dep-types/'.length) + importPath.slice('dep-types/'.length), ) return slash(relative(dirname(currentFile), absoluteTypePath)) } diff --git a/packages/vite/scripts/util.ts b/packages/vite/scripts/util.ts index 9b1fb3d3586e7d..135c701098fc57 100644 --- a/packages/vite/scripts/util.ts +++ b/packages/vite/scripts/util.ts @@ -8,7 +8,7 @@ import MagicString from 'magic-string' export function rewriteImports( fileOrDir: string, - rewrite: (importPath: string, currentFile: string) => string | void + rewrite: (importPath: string, currentFile: string) => string | void, ): void { walkDir(fileOrDir, (file) => { rewriteFileImports(file, (importPath) => { @@ -35,7 +35,7 @@ export function walkDir(dir: string, handleFile: (file: string) => void): void { function rewriteFileImports( file: string, - rewrite: (importPath: string) => string | void + rewrite: (importPath: string) => string | void, ): void { const content = readFileSync(file, 'utf-8') const str = new MagicString(content) @@ -43,7 +43,7 @@ function rewriteFileImports( try { ast = parse(content, { sourceType: 'module', - plugins: ['typescript', 'classProperties'] + plugins: ['typescript', 'classProperties'], }) } catch (e) { console.log(colors.red(`failed to parse ${file}`)) @@ -62,7 +62,7 @@ function rewriteFileImports( str.overwrite( source.start!, source.end!, - JSON.stringify(newImportPath) + JSON.stringify(newImportPath), ) } } diff --git a/packages/vite/src/client/client.ts b/packages/vite/src/client/client.ts index 479f49fea53c98..6935b8e5c3dbaf 100644 --- a/packages/vite/src/client/client.ts +++ b/packages/vite/src/client/client.ts @@ -50,17 +50,17 @@ try { 'your current setup:\n' + ` (browser) ${currentScriptHost} <--[HTTP]--> ${serverHost} (server)\n` + ` (browser) ${socketHost} <--[WebSocket (failing)]--> ${directSocketHost} (server)\n` + - 'Check out your Vite / network configuration and https://vitejs.dev/config/server-options.html#server-hmr .' + 'Check out your Vite / network configuration and https://vitejs.dev/config/server-options.html#server-hmr .', ) }) socket.addEventListener( 'open', () => { console.info( - '[vite] Direct websocket connection fallback. Check out https://vitejs.dev/config/server-options.html#server-hmr to remove the previous connection error.' + '[vite] Direct websocket connection fallback. Check out https://vitejs.dev/config/server-options.html#server-hmr to remove the previous connection error.', ) }, - { once: true } + { once: true }, ) } } @@ -73,7 +73,7 @@ try { function setupWebSocket( protocol: string, hostAndPath: string, - onCloseWithoutOpen?: () => void + onCloseWithoutOpen?: () => void, ) { const socket = new WebSocket(`${protocol}://${hostAndPath}`, 'vite-hmr') let isOpened = false @@ -83,7 +83,7 @@ function setupWebSocket( () => { isOpened = true }, - { once: true } + { once: true }, ) // Listen for messages @@ -115,7 +115,7 @@ function warnFailedFetch(err: Error, path: string | string[]) { console.error( `[hmr] Failed to reload ${path}. ` + `This could be due to syntax errors or importing non-existent ` + - `modules. (see errors above)` + `modules. (see errors above)`, ) } @@ -168,10 +168,10 @@ async function handleMessage(payload: HMRPayload) { // using relative paths so we need to use link.href to grab the full // URL for the include check. const el = Array.from( - document.querySelectorAll('link') + document.querySelectorAll('link'), ).find( (e) => - !outdatedLinkTags.has(e) && cleanUrl(e.href).includes(searchUrl) + !outdatedLinkTags.has(e) && cleanUrl(e.href).includes(searchUrl), ) if (!el) { @@ -200,7 +200,7 @@ async function handleMessage(payload: HMRPayload) { outdatedLinkTags.add(el) el.after(newLinkTag) }) - }) + }), ) notifyListeners('vite:afterUpdate', payload) break @@ -247,7 +247,7 @@ async function handleMessage(payload: HMRPayload) { createErrorOverlay(err) } else { console.error( - `[vite] Internal Server Error\n${err.message}\n${err.stack}` + `[vite] Internal Server Error\n${err.message}\n${err.stack}`, ) } break @@ -261,7 +261,7 @@ async function handleMessage(payload: HMRPayload) { function notifyListeners( event: T, - data: InferCustomEventPayload + data: InferCustomEventPayload, ): void function notifyListeners(event: string, data: any): void { const cbs = customListenersMap.get(event) @@ -311,7 +311,7 @@ async function queueUpdate(p: Promise<(() => void) | undefined>) { async function waitForSuccessfulPing( socketProtocol: string, hostAndPath: string, - ms = 1000 + ms = 1000, ) { const pingHostProtocol = socketProtocol === 'wss' ? 'https' : 'http' @@ -322,7 +322,7 @@ async function waitForSuccessfulPing( // but will reject a networking error. // When running on middleware mode, it returns status 426, and an cors error happens if mode is not no-cors await fetch(`${pingHostProtocol}://${hostAndPath}`, { - mode: 'no-cors' + mode: 'no-cors', }) break } catch (e) { @@ -391,7 +391,7 @@ export function removeStyle(id: string): void { if (style instanceof CSSStyleSheet) { // @ts-expect-error: using experimental API document.adoptedStyleSheets = document.adoptedStyleSheets.filter( - (s: CSSStyleSheet) => s !== style + (s: CSSStyleSheet) => s !== style, ) } else { document.head.removeChild(style) @@ -404,7 +404,7 @@ async function fetchUpdate({ path, acceptedPath, timestamp, - explicitImportRequired + explicitImportRequired, }: Update) { const mod = hotModulesMap.get(path) if (!mod) { @@ -419,7 +419,7 @@ async function fetchUpdate({ // determine the qualified callbacks before we re-import the modules const qualifiedCallbacks = mod.callbacks.filter(({ deps }) => - deps.includes(acceptedPath) + deps.includes(acceptedPath), ) if (isSelfUpdate || qualifiedCallbacks.length > 0) { @@ -496,7 +496,7 @@ export function createHotContext(ownerPath: string): ViteHotContext { if (listeners) { customListenersMap.set( event, - listeners.filter((l) => !staleFns.includes(l)) + listeners.filter((l) => !staleFns.includes(l)), ) } } @@ -508,11 +508,11 @@ export function createHotContext(ownerPath: string): ViteHotContext { function acceptDeps(deps: string[], callback: HotCallback['fn'] = () => {}) { const mod: HotModule = hotModulesMap.get(ownerPath) || { id: ownerPath, - callbacks: [] + callbacks: [], } mod.callbacks.push({ deps, - fn: callback + fn: callback, }) hotModulesMap.set(ownerPath, mod) } @@ -560,7 +560,7 @@ export function createHotContext(ownerPath: string): ViteHotContext { notifyListeners('vite:invalidate', { path: ownerPath, message }) this.send('vite:invalidate', { path: ownerPath, message }) console.debug( - `[vite] invalidate ${ownerPath}${message ? `: ${message}` : ''}` + `[vite] invalidate ${ownerPath}${message ? `: ${message}` : ''}`, ) }, @@ -578,7 +578,7 @@ export function createHotContext(ownerPath: string): ViteHotContext { send(event, data) { messageBuffer.push(JSON.stringify({ type: 'custom', event, data })) sendMessageBuffer() - } + }, } return hot diff --git a/packages/vite/src/node/__tests__/build.spec.ts b/packages/vite/src/node/__tests__/build.spec.ts index b329f91d348959..67cdcdfe60075b 100644 --- a/packages/vite/src/node/__tests__/build.spec.ts +++ b/packages/vite/src/node/__tests__/build.spec.ts @@ -13,7 +13,7 @@ const __dirname = resolve(fileURLToPath(import.meta.url), '..') type FormatsToFileNames = [LibraryFormats, string][] const baseLibOptions: LibraryOptions = { fileName: 'my-lib', - entry: 'mylib.js' + entry: 'mylib.js', } describe('resolveBuildOutputs', () => { @@ -25,8 +25,8 @@ describe('resolveBuildOutputs', () => { expect(resolvedOutputs).toEqual([ { - format: 'es' - } + format: 'es', + }, ]) }) @@ -37,11 +37,11 @@ describe('resolveBuildOutputs', () => { expect(resolvedOutputs).toEqual([ { - format: 'es' + format: 'es', }, { - format: 'umd' - } + format: 'umd', + }, ]) }) @@ -58,14 +58,14 @@ describe('resolveBuildOutputs', () => { const loggerSpy = vi.spyOn(logger, 'warn').mockImplementation(() => {}) const libOptions: LibraryOptions = { ...baseLibOptions, - formats: ['iife'] + formats: ['iife'], } const outputs: OutputOptions[] = [{ format: 'es' }] resolveBuildOutputs(outputs, libOptions, logger) expect(loggerSpy).toHaveBeenCalledWith( - expect.stringContaining('"build.lib.formats" will be ignored because') + expect.stringContaining('"build.lib.formats" will be ignored because'), ) }) @@ -73,7 +73,7 @@ describe('resolveBuildOutputs', () => { const logger = createLogger() const libOptions: LibraryOptions = { ...baseLibOptions, - formats: ['iife'] + formats: ['iife'], } const resolveBuild = () => resolveBuildOutputs(void 0, libOptions, logger) @@ -95,7 +95,7 @@ describe('resolveBuildOutputs', () => { const resolveBuild = () => resolveBuildOutputs(outputs, libOptions, logger) expect(resolveBuild).toThrowError( - /Entries in "build\.rollupOptions\.output" must specify "name"/ + /Entries in "build\.rollupOptions\.output" must specify "name"/, ) }) @@ -106,7 +106,7 @@ describe('resolveBuildOutputs', () => { const resolveBuild = () => resolveBuildOutputs(outputs, libOptions, logger) expect(resolveBuild).toThrowError( - /Entries in "build\.rollupOptions\.output" must specify "name"/ + /Entries in "build\.rollupOptions\.output" must specify "name"/, ) }) }) @@ -116,11 +116,11 @@ describe('resolveLibFilename', () => { const filename = resolveLibFilename( { fileName: (format) => `custom-filename-function.${format}.js`, - entry: 'mylib.js' + entry: 'mylib.js', }, 'es', 'myLib', - resolve(__dirname, 'packages/name') + resolve(__dirname, 'packages/name'), ) expect(filename).toBe('custom-filename-function.es.js') @@ -130,11 +130,11 @@ describe('resolveLibFilename', () => { const filename = resolveLibFilename( { fileName: 'custom-filename', - entry: 'mylib.js' + entry: 'mylib.js', }, 'es', 'myLib', - resolve(__dirname, 'packages/name') + resolve(__dirname, 'packages/name'), ) expect(filename).toBe('custom-filename.mjs') @@ -143,11 +143,11 @@ describe('resolveLibFilename', () => { test('package name as filename', () => { const filename = resolveLibFilename( { - entry: 'mylib.js' + entry: 'mylib.js', }, 'es', 'myLib', - resolve(__dirname, 'packages/name') + resolve(__dirname, 'packages/name'), ) expect(filename).toBe('mylib.mjs') @@ -157,11 +157,11 @@ describe('resolveLibFilename', () => { const filename = resolveLibFilename( { fileName: 'custom-filename', - entry: 'mylib.js' + entry: 'mylib.js', }, 'es', 'myLib', - resolve(__dirname, 'packages/noname') + resolve(__dirname, 'packages/noname'), ) expect(filename).toBe('custom-filename.mjs') @@ -171,11 +171,11 @@ describe('resolveLibFilename', () => { expect(() => { resolveLibFilename( { - entry: 'mylib.js' + entry: 'mylib.js', }, 'es', 'myLib', - resolve(__dirname, 'packages/noname') + resolve(__dirname, 'packages/noname'), ) }).toThrow() }) @@ -185,7 +185,7 @@ describe('resolveLibFilename', () => { ['es', 'my-lib.mjs'], ['umd', 'my-lib.umd.js'], ['cjs', 'my-lib.js'], - ['iife', 'my-lib.iife.js'] + ['iife', 'my-lib.iife.js'], ] for (const [format, expectedFilename] of formatsToFilenames) { @@ -193,7 +193,7 @@ describe('resolveLibFilename', () => { baseLibOptions, format, 'myLib', - resolve(__dirname, 'packages/noname') + resolve(__dirname, 'packages/noname'), ) expect(filename).toBe(expectedFilename) @@ -205,7 +205,7 @@ describe('resolveLibFilename', () => { ['es', 'my-lib.js'], ['umd', 'my-lib.umd.cjs'], ['cjs', 'my-lib.cjs'], - ['iife', 'my-lib.iife.js'] + ['iife', 'my-lib.iife.js'], ] for (const [format, expectedFilename] of formatsToFilenames) { @@ -213,7 +213,7 @@ describe('resolveLibFilename', () => { baseLibOptions, format, 'myLib', - resolve(__dirname, 'packages/module') + resolve(__dirname, 'packages/module'), ) expect(expectedFilename).toBe(filename) @@ -224,8 +224,8 @@ describe('resolveLibFilename', () => { const libOptions: LibraryOptions = { entry: { entryA: 'entryA.js', - entryB: 'entryB.js' - } + entryB: 'entryB.js', + }, } const [fileName1, fileName2] = ['entryA', 'entryB'].map((entryAlias) => @@ -233,8 +233,8 @@ describe('resolveLibFilename', () => { libOptions, 'es', entryAlias, - resolve(__dirname, 'packages/name') - ) + resolve(__dirname, 'packages/name'), + ), ) expect(fileName1).toBe('entryA.mjs') @@ -245,10 +245,10 @@ describe('resolveLibFilename', () => { const libOptions: LibraryOptions = { entry: { entryA: 'entryA.js', - entryB: 'entryB.js' + entryB: 'entryB.js', }, fileName: (format, entryAlias) => - `custom-filename-function.${entryAlias}.${format}.js` + `custom-filename-function.${entryAlias}.${format}.js`, } const [fileName1, fileName2] = ['entryA', 'entryB'].map((entryAlias) => @@ -256,8 +256,8 @@ describe('resolveLibFilename', () => { libOptions, 'es', entryAlias, - resolve(__dirname, 'packages/name') - ) + resolve(__dirname, 'packages/name'), + ), ) expect(fileName1).toBe('custom-filename-function.entryA.es.js') @@ -268,9 +268,9 @@ describe('resolveLibFilename', () => { const libOptions: LibraryOptions = { entry: { entryA: 'entryA.js', - entryB: 'entryB.js' + entryB: 'entryB.js', }, - fileName: 'custom-filename' + fileName: 'custom-filename', } const [fileName1, fileName2] = ['entryA', 'entryB'].map((entryAlias) => @@ -278,8 +278,8 @@ describe('resolveLibFilename', () => { libOptions, 'es', entryAlias, - resolve(__dirname, 'packages/name') - ) + resolve(__dirname, 'packages/name'), + ), ) expect(fileName1).toBe('custom-filename.mjs') @@ -288,7 +288,7 @@ describe('resolveLibFilename', () => { test('multiple entries as array', () => { const libOptions: LibraryOptions = { - entry: ['entryA.js', 'entryB.js'] + entry: ['entryA.js', 'entryB.js'], } const [fileName1, fileName2] = ['entryA', 'entryB'].map((entryAlias) => @@ -296,8 +296,8 @@ describe('resolveLibFilename', () => { libOptions, 'es', entryAlias, - resolve(__dirname, 'packages/name') - ) + resolve(__dirname, 'packages/name'), + ), ) expect(fileName1).toBe('entryA.mjs') @@ -308,7 +308,7 @@ describe('resolveLibFilename', () => { const libOptions: LibraryOptions = { entry: ['entryA.js', 'entryB.js'], fileName: (format, entryAlias) => - `custom-filename-function.${entryAlias}.${format}.js` + `custom-filename-function.${entryAlias}.${format}.js`, } const [fileName1, fileName2] = ['entryA', 'entryB'].map((entryAlias) => @@ -316,8 +316,8 @@ describe('resolveLibFilename', () => { libOptions, 'es', entryAlias, - resolve(__dirname, 'packages/name') - ) + resolve(__dirname, 'packages/name'), + ), ) expect(fileName1).toBe('custom-filename-function.entryA.es.js') @@ -327,7 +327,7 @@ describe('resolveLibFilename', () => { test('multiple entries as array: custom filename string', () => { const libOptions: LibraryOptions = { entry: ['entryA.js', 'entryB.js'], - fileName: 'custom-filename' + fileName: 'custom-filename', } const [fileName1, fileName2] = ['entryA', 'entryB'].map((entryAlias) => @@ -335,8 +335,8 @@ describe('resolveLibFilename', () => { libOptions, 'es', entryAlias, - resolve(__dirname, 'packages/name') - ) + resolve(__dirname, 'packages/name'), + ), ) expect(fileName1).toBe('custom-filename.mjs') @@ -348,41 +348,41 @@ describe('resolveBuildOutputs', () => { test('default format: one entry', () => { const libOptions: LibraryOptions = { entry: 'entryA.js', - name: 'entryA' + name: 'entryA', } expect(resolveBuildOutputs(undefined, libOptions, {} as Logger)).toEqual([ { format: 'es' }, - { format: 'umd' } + { format: 'umd' }, ]) expect( - resolveBuildOutputs({ name: 'A' }, libOptions, {} as Logger) + resolveBuildOutputs({ name: 'A' }, libOptions, {} as Logger), ).toEqual([ { format: 'es', name: 'A' }, - { format: 'umd', name: 'A' } + { format: 'umd', name: 'A' }, ]) expect( - resolveBuildOutputs([{ name: 'A' }], libOptions, {} as Logger) + resolveBuildOutputs([{ name: 'A' }], libOptions, {} as Logger), ).toEqual([{ name: 'A' }]) }) test('default format: multiple entries', () => { const libOptions: LibraryOptions = { - entry: ['entryA.js', 'entryB.js'] + entry: ['entryA.js', 'entryB.js'], } expect(resolveBuildOutputs(undefined, libOptions, {} as Logger)).toEqual([ { format: 'es' }, - { format: 'cjs' } + { format: 'cjs' }, ]) expect( - resolveBuildOutputs({ name: 'A' }, libOptions, {} as Logger) + resolveBuildOutputs({ name: 'A' }, libOptions, {} as Logger), ).toEqual([ { format: 'es', name: 'A' }, - { format: 'cjs', name: 'A' } + { format: 'cjs', name: 'A' }, ]) expect( - resolveBuildOutputs([{ name: 'A' }], libOptions, {} as Logger) + resolveBuildOutputs([{ name: 'A' }], libOptions, {} as Logger), ).toEqual([{ name: 'A' }]) }) @@ -393,12 +393,12 @@ describe('resolveBuildOutputs', () => { undefined, { entry: ['entryA.js', 'entryB.js'], - formats: [format as LibraryFormats] + formats: [format as LibraryFormats], }, - {} as Logger - ) + {} as Logger, + ), ).toThrow( - `Multiple entry points are not supported when output formats include "umd" or "iife".` + `Multiple entry points are not supported when output formats include "umd" or "iife".`, ) }) }) @@ -410,12 +410,12 @@ describe('resolveBuildOutputs', () => { undefined, { entry: 'entryA.js', - formats: [format as LibraryFormats] + formats: [format as LibraryFormats], }, - {} as Logger - ) + {} as Logger, + ), ).toThrow( - `Option "build.lib.name" is required when output formats include "umd" or "iife".` + `Option "build.lib.name" is required when output formats include "umd" or "iife".`, ) }) }) @@ -428,15 +428,15 @@ describe('resolveBuildOutputs', () => { [{ name: 'A' }], { entry: 'entryA.js', - formats: ['es'] + formats: ['es'], }, - log - ) + log, + ), ).toEqual([{ name: 'A' }]) expect(log.warn).toHaveBeenLastCalledWith( colors.yellow( - `"build.lib.formats" will be ignored because "build.rollupOptions.output" is already an array format.` - ) + `"build.lib.formats" will be ignored because "build.rollupOptions.output" is already an array format.`, + ), ) }) }) diff --git a/packages/vite/src/node/__tests__/config.spec.ts b/packages/vite/src/node/__tests__/config.spec.ts index 0b8aaf79e6d47c..606b25fa8e148e 100644 --- a/packages/vite/src/node/__tests__/config.spec.ts +++ b/packages/vite/src/node/__tests__/config.spec.ts @@ -12,19 +12,19 @@ describe('mergeConfig', () => { alias: [ { find: 'foo', - replacement: 'foo-value' - } - ] - } + replacement: 'foo-value', + }, + ], + }, } const newConfig: UserConfigExport = { resolve: { alias: { bar: 'bar-value', - baz: 'baz-value' - } - } + baz: 'baz-value', + }, + }, } const mergedConfig: UserConfigExport = { @@ -32,18 +32,18 @@ describe('mergeConfig', () => { alias: [ { find: 'bar', - replacement: 'bar-value' + replacement: 'bar-value', }, { find: 'baz', - replacement: 'baz-value' + replacement: 'baz-value', }, { find: 'foo', - replacement: 'foo-value' - } - ] - } + replacement: 'foo-value', + }, + ], + }, } expect(mergeConfig(baseConfig, newConfig)).toEqual(mergedConfig) @@ -54,18 +54,18 @@ describe('mergeConfig', () => { resolve: { alias: { bar: 'bar-value', - baz: 'baz-value' - } - } + baz: 'baz-value', + }, + }, } const newConfig = { resolve: { alias: { bar: 'bar-value-2', - foo: 'foo-value' - } - } + foo: 'foo-value', + }, + }, } const mergedConfig = { @@ -73,9 +73,9 @@ describe('mergeConfig', () => { alias: { bar: 'bar-value-2', baz: 'baz-value', - foo: 'foo-value' - } - } + foo: 'foo-value', + }, + }, } expect(mergeConfig(baseConfig, newConfig)).toEqual(mergedConfig) @@ -83,15 +83,15 @@ describe('mergeConfig', () => { test('handles arrays', () => { const baseConfig: UserConfigExport = { - envPrefix: 'string1' + envPrefix: 'string1', } const newConfig: UserConfigExport = { - envPrefix: ['string2', 'string3'] + envPrefix: ['string2', 'string3'], } const mergedConfig: UserConfigExport = { - envPrefix: ['string1', 'string2', 'string3'] + envPrefix: ['string1', 'string2', 'string3'], } expect(mergeConfig(baseConfig, newConfig)).toEqual(mergedConfig) @@ -99,15 +99,15 @@ describe('mergeConfig', () => { test('handles assetsInclude', () => { const baseConfig: UserConfigExport = { - assetsInclude: 'some-string' + assetsInclude: 'some-string', } const newConfig: UserConfigExport = { - assetsInclude: ['some-other-string', /regexp?/] + assetsInclude: ['some-other-string', /regexp?/], } const mergedConfig: UserConfigExport = { - assetsInclude: ['some-string', 'some-other-string', /regexp?/] + assetsInclude: ['some-string', 'some-other-string', /regexp?/], } expect(mergeConfig(baseConfig, newConfig)).toEqual(mergedConfig) @@ -118,18 +118,18 @@ describe('mergeConfig', () => { custom: { alias: { bar: 'bar-value', - baz: 'baz-value' - } - } + baz: 'baz-value', + }, + }, } const newConfig = { custom: { alias: { bar: 'bar-value-2', - foo: 'foo-value' - } - } + foo: 'foo-value', + }, + }, } const mergedConfig = { @@ -137,9 +137,9 @@ describe('mergeConfig', () => { alias: { bar: 'bar-value-2', baz: 'baz-value', - foo: 'foo-value' - } - } + foo: 'foo-value', + }, + }, } expect(mergeConfig(baseConfig, newConfig)).toEqual(mergedConfig) @@ -147,15 +147,15 @@ describe('mergeConfig', () => { test('merge array correctly', () => { const baseConfig = { - foo: null + foo: null, } const newConfig = { - foo: ['bar'] + foo: ['bar'], } const mergedConfig = { - foo: ['bar'] + foo: ['bar'], } expect(mergeConfig(baseConfig, newConfig)).toEqual(mergedConfig) @@ -164,20 +164,20 @@ describe('mergeConfig', () => { test('handles ssr.noExternal', () => { const baseConfig = { ssr: { - noExternal: true - } + noExternal: true, + }, } const newConfig = { ssr: { - noExternal: ['foo'] - } + noExternal: ['foo'], + }, } const mergedConfig = { ssr: { - noExternal: true - } + noExternal: true, + }, } // merging either ways, `ssr.noExternal: true` should take highest priority @@ -213,21 +213,21 @@ describe('preview config', () => { open: true, https: true, headers: { - 'Cache-Control': 'no-store' + 'Cache-Control': 'no-store', }, proxy: { '/foo': 'http://localhost:4567' }, - cors: false + cors: false, }) test('preview inherits server config with default port', async () => { const config: InlineConfig = { - server: serverConfig() + server: serverConfig(), } expect(await resolveConfig(config, 'serve')).toMatchObject({ preview: { ...serverConfig(), - port: undefined - } + port: undefined, + }, }) }) @@ -235,14 +235,14 @@ describe('preview config', () => { const config: InlineConfig = { server: serverConfig(), preview: { - port: 3006 - } + port: 3006, + }, } expect(await resolveConfig(config, 'serve')).toMatchObject({ preview: { ...serverConfig(), - port: 3006 - } + port: 3006, + }, }) }) @@ -253,16 +253,16 @@ describe('preview config', () => { host: false, https: false, proxy: { '/bar': 'http://localhost:3010' }, - cors: true + cors: true, }) test('preview overrides server config', async () => { const config: InlineConfig = { server: serverConfig(), - preview: previewConfig() + preview: previewConfig(), } expect(await resolveConfig(config, 'serve')).toMatchObject({ - preview: previewConfig() + preview: previewConfig(), }) }) }) @@ -273,7 +273,7 @@ describe('resolveConfig', () => { name: 'vite-plugin-keep-screen-merge', config() { return { clearScreen: false } - } + }, } } @@ -282,7 +282,7 @@ describe('resolveConfig', () => { name: 'vite-plugin-keep-screen-override', config(config) { config.clearScreen = false - } + }, } } @@ -290,7 +290,7 @@ describe('resolveConfig', () => { const config1: InlineConfig = { plugins: [keepScreenMergePlugin()] } const config2: InlineConfig = { plugins: [keepScreenMergePlugin()], - clearScreen: true + clearScreen: true, } const results1 = await resolveConfig(config1, 'build') @@ -304,7 +304,7 @@ describe('resolveConfig', () => { const config1: InlineConfig = { plugins: [keepScreenOverridePlugin()] } const config2: InlineConfig = { plugins: [keepScreenOverridePlugin()], - clearScreen: true + clearScreen: true, } const results1 = await resolveConfig(config1, 'build') diff --git a/packages/vite/src/node/__tests__/dev.spec.ts b/packages/vite/src/node/__tests__/dev.spec.ts index 3b3b3d14553da4..1ade6c0adde9ea 100644 --- a/packages/vite/src/node/__tests__/dev.spec.ts +++ b/packages/vite/src/node/__tests__/dev.spec.ts @@ -7,11 +7,11 @@ describe('resolveBuildOptions in dev', () => { { build: { lib: { - entry: './index.js' - } - } + entry: './index.js', + }, + }, }, - 'serve' + 'serve', ) expect(config.build.rollupOptions).not.toHaveProperty('input') diff --git a/packages/vite/src/node/__tests__/plugins/css.spec.ts b/packages/vite/src/node/__tests__/plugins/css.spec.ts index d951178783073b..9fca203593d310 100644 --- a/packages/vite/src/node/__tests__/plugins/css.spec.ts +++ b/packages/vite/src/node/__tests__/plugins/css.spec.ts @@ -8,13 +8,13 @@ import { cssPlugin, cssUrlRE, hoistAtRules } from '../../plugins/css' describe('search css url function', () => { test('some spaces before it', () => { expect( - cssUrlRE.test("list-style-image: url('../images/bullet.jpg');") + cssUrlRE.test("list-style-image: url('../images/bullet.jpg');"), ).toBe(true) }) test('no space after colon', () => { expect(cssUrlRE.test("list-style-image:url('../images/bullet.jpg');")).toBe( - true + true, ) }) @@ -26,23 +26,23 @@ describe('search css url function', () => { expect( cssUrlRE.test(`@function svg-url($string) { @return ""; - }`) + }`), ).toBe(false) }) test('after parenthesis', () => { expect( cssUrlRE.test( - 'mask-image: image(url(mask.png), skyblue, linear-gradient(rgba(0, 0, 0, 1.0), transparent));' - ) + 'mask-image: image(url(mask.png), skyblue, linear-gradient(rgba(0, 0, 0, 1.0), transparent));', + ), ).toBe(true) }) test('after comma', () => { expect( cssUrlRE.test( - 'mask-image: image(skyblue,url(mask.png), linear-gradient(rgba(0, 0, 0, 1.0), transparent));' - ) + 'mask-image: image(skyblue,url(mask.png), linear-gradient(rgba(0, 0, 0, 1.0), transparent));', + ), ).toBe(true) }) }) @@ -56,18 +56,18 @@ describe('css modules', () => { .bar { display: block; background: #f0f; -}` +}`, }, { resolve: { alias: [ { find: '@', - replacement: mockedProjectPath - } - ] - } - } + replacement: mockedProjectPath, + }, + ], + }, + }, ) const result = await transform( @@ -76,7 +76,7 @@ background: #f0f; position: fixed; composes: bar from '@/css/bar.module.css'; }`, - '/css/foo.module.css' + '/css/foo.module.css', ) expect(result.code).toBe( @@ -87,7 +87,7 @@ background: #f0f; } ._foo_86148_1 { position: fixed; -}` +}`, ) resetMock() @@ -97,9 +97,9 @@ position: fixed; const { transform, resetMock } = await createCssPluginTransform(undefined, { css: { modules: { - generateScopedName: 'custom__[hash:base64:5]' - } - } + generateScopedName: 'custom__[hash:base64:5]', + }, + }, }) const css = `\ .foo { @@ -129,7 +129,7 @@ describe('hoist @ rules', () => { const css = `.foo{color:red;}@import url(data:image/png;base64,iRxVB0);` const result = await hoistAtRules(css) expect(result).toBe( - `@import url(data:image/png;base64,iRxVB0);.foo{color:red;}` + `@import url(data:image/png;base64,iRxVB0);.foo{color:red;}`, ) }) @@ -155,7 +155,7 @@ describe('hoist @ rules', () => { const css = `.foo{color:red;}@import "bla";@charset "utf-8";.bar{color:green;}@import "baz";` const result = await hoistAtRules(css) expect(result).toBe( - `@charset "utf-8";@import "bla";@import "baz";.foo{color:red;}.bar{color:green;}` + `@charset "utf-8";@import "bla";@import "baz";.foo{color:red;}.bar{color:green;}`, ) }) @@ -169,7 +169,7 @@ describe('hoist @ rules', () => { const css = `.foo{color:red;}/* @charset "utf-8"; */@charset "utf-8";` const result = await hoistAtRules(css) expect(result).toBe( - `@charset "utf-8";.foo{color:red;}/* @charset "utf-8"; */` + `@charset "utf-8";.foo{color:red;}/* @charset "utf-8"; */`, ) }) @@ -204,7 +204,7 @@ describe('hoist @ rules', () => { async function createCssPluginTransform( files?: Record, - inlineConfig: InlineConfig = {} + inlineConfig: InlineConfig = {}, ) { const config = await resolveConfig(inlineConfig, 'serve') const { transform, buildStart } = cssPlugin(config) @@ -226,14 +226,14 @@ async function createCssPluginTransform( { addWatchFile() { return - } + }, }, code, - id + id, ) }, resetMock() { mockFs.mockReset() - } + }, } } diff --git a/packages/vite/src/node/__tests__/plugins/define.spec.ts b/packages/vite/src/node/__tests__/plugins/define.spec.ts index 932560a749f24d..b1634ef9adcd1a 100644 --- a/packages/vite/src/node/__tests__/plugins/define.spec.ts +++ b/packages/vite/src/node/__tests__/plugins/define.spec.ts @@ -5,7 +5,7 @@ import { resolveConfig } from '../../config' async function createDefinePluginTransform( define: Record = {}, build = true, - ssr = false + ssr = false, ) { const config = await resolveConfig({ define }, build ? 'build' : 'serve') const instance = definePlugin(config) @@ -18,23 +18,23 @@ async function createDefinePluginTransform( describe('definePlugin', () => { test('replaces custom define', async () => { const transform = await createDefinePluginTransform({ - __APP_VERSION__: JSON.stringify('1.0') + __APP_VERSION__: JSON.stringify('1.0'), }) expect(await transform('const version = __APP_VERSION__ ;')).toBe( - 'const version = "1.0" ;' + 'const version = "1.0" ;', ) expect(await transform('const version = __APP_VERSION__;')).toBe( - 'const version = "1.0";' + 'const version = "1.0";', ) }) test('replaces import.meta.env.SSR with false', async () => { const transform = await createDefinePluginTransform() expect(await transform('const isSSR = import.meta.env.SSR ;')).toBe( - 'const isSSR = false ;' + 'const isSSR = false ;', ) expect(await transform('const isSSR = import.meta.env.SSR;')).toBe( - 'const isSSR = false;' + 'const isSSR = false;', ) }) }) diff --git a/packages/vite/src/node/__tests__/plugins/dynamicImportVar/parse.test.ts b/packages/vite/src/node/__tests__/plugins/dynamicImportVar/parse.test.ts index cfd816d00fe8b5..71aadd3366c0d7 100644 --- a/packages/vite/src/node/__tests__/plugins/dynamicImportVar/parse.test.ts +++ b/packages/vite/src/node/__tests__/plugins/dynamicImportVar/parse.test.ts @@ -12,7 +12,7 @@ async function run(input: string) { input, normalizePath(resolve(__dirname, 'index.js')), (id) => id.replace('@', resolve(__dirname, './mods/')), - __dirname + __dirname, )) || {} return `__variableDynamicImportRuntimeHelper(${glob}, \`${rawPattern}\`)` } @@ -52,7 +52,7 @@ describe('parse positives', () => { it('with multi ../ and itself', async () => { expect( - await run('`../../plugins/dynamicImportVar/${name}.js`') + await run('`../../plugins/dynamicImportVar/${name}.js`'), ).toMatchSnapshot() }) }) diff --git a/packages/vite/src/node/__tests__/plugins/esbuild.spec.ts b/packages/vite/src/node/__tests__/plugins/esbuild.spec.ts index 6591ecee8b9876..2cc8c9304450a8 100644 --- a/packages/vite/src/node/__tests__/plugins/esbuild.spec.ts +++ b/packages/vite/src/node/__tests__/plugins/esbuild.spec.ts @@ -3,7 +3,7 @@ import type { ResolvedConfig, UserConfig } from '../../config' import { ESBuildTransformResult, resolveEsbuildTranspileOptions, - transformWithEsbuild + transformWithEsbuild, } from '../../plugins/esbuild' describe('resolveEsbuildTranspileOptions', () => { @@ -12,13 +12,13 @@ describe('resolveEsbuildTranspileOptions', () => { defineResolvedConfig({ build: { target: 'es2020', - minify: 'esbuild' + minify: 'esbuild', }, esbuild: { - keepNames: true - } + keepNames: true, + }, }), - 'es' + 'es', ) expect(options).toEqual({ charset: 'utf8', @@ -29,8 +29,8 @@ describe('resolveEsbuildTranspileOptions', () => { treeShaking: true, supported: { 'dynamic-import': true, - 'import-meta': true - } + 'import-meta': true, + }, }) }) @@ -39,13 +39,13 @@ describe('resolveEsbuildTranspileOptions', () => { defineResolvedConfig({ build: { target: 'esnext', - minify: false + minify: false, }, esbuild: { - keepNames: true - } + keepNames: true, + }, }), - 'es' + 'es', ) expect(options).toEqual(null) }) @@ -54,14 +54,14 @@ describe('resolveEsbuildTranspileOptions', () => { const options = resolveEsbuildTranspileOptions( defineResolvedConfig({ build: { - minify: 'esbuild' + minify: 'esbuild', }, esbuild: { keepNames: true, - minifyIdentifiers: false - } + minifyIdentifiers: false, + }, }), - 'es' + 'es', ) expect(options).toEqual({ charset: 'utf8', @@ -75,8 +75,8 @@ describe('resolveEsbuildTranspileOptions', () => { treeShaking: true, supported: { 'dynamic-import': true, - 'import-meta': true - } + 'import-meta': true, + }, }) }) @@ -85,13 +85,13 @@ describe('resolveEsbuildTranspileOptions', () => { defineResolvedConfig({ build: { target: 'es2020', - minify: false + minify: false, }, esbuild: { - keepNames: true - } + keepNames: true, + }, }), - 'es' + 'es', ) expect(options).toEqual({ charset: 'utf8', @@ -105,8 +105,8 @@ describe('resolveEsbuildTranspileOptions', () => { treeShaking: false, supported: { 'dynamic-import': true, - 'import-meta': true - } + 'import-meta': true, + }, }) }) @@ -116,14 +116,14 @@ describe('resolveEsbuildTranspileOptions', () => { build: { minify: 'esbuild', lib: { - entry: './somewhere.js' - } + entry: './somewhere.js', + }, }, esbuild: { - keepNames: true - } + keepNames: true, + }, }), - 'es' + 'es', ) expect(options).toEqual({ charset: 'utf8', @@ -137,8 +137,8 @@ describe('resolveEsbuildTranspileOptions', () => { treeShaking: true, supported: { 'dynamic-import': true, - 'import-meta': true - } + 'import-meta': true, + }, }) }) @@ -148,14 +148,14 @@ describe('resolveEsbuildTranspileOptions', () => { build: { minify: 'esbuild', lib: { - entry: './somewhere.js' - } + entry: './somewhere.js', + }, }, esbuild: { - keepNames: true - } + keepNames: true, + }, }), - 'cjs' + 'cjs', ) expect(options).toEqual({ charset: 'utf8', @@ -166,8 +166,8 @@ describe('resolveEsbuildTranspileOptions', () => { treeShaking: true, supported: { 'dynamic-import': true, - 'import-meta': true - } + 'import-meta': true, + }, }) }) @@ -177,16 +177,16 @@ describe('resolveEsbuildTranspileOptions', () => { build: { minify: 'esbuild', lib: { - entry: './somewhere.js' - } + entry: './somewhere.js', + }, }, esbuild: { keepNames: true, minifyIdentifiers: true, - minifyWhitespace: true - } + minifyWhitespace: true, + }, }), - 'es' + 'es', ) expect(options).toEqual({ charset: 'utf8', @@ -200,8 +200,8 @@ describe('resolveEsbuildTranspileOptions', () => { treeShaking: true, supported: { 'dynamic-import': true, - 'import-meta': true - } + 'import-meta': true, + }, }) }) @@ -211,17 +211,17 @@ describe('resolveEsbuildTranspileOptions', () => { build: { minify: 'esbuild', lib: { - entry: './somewhere.js' - } + entry: './somewhere.js', + }, }, esbuild: { keepNames: true, minifyIdentifiers: true, minifySyntax: false, - treeShaking: true - } + treeShaking: true, + }, }), - 'cjs' + 'cjs', ) expect(options).toEqual({ charset: 'utf8', @@ -235,8 +235,8 @@ describe('resolveEsbuildTranspileOptions', () => { treeShaking: true, supported: { 'dynamic-import': true, - 'import-meta': true - } + 'import-meta': true, + }, }) }) }) @@ -244,7 +244,7 @@ describe('resolveEsbuildTranspileOptions', () => { describe('transformWithEsbuild', () => { test('not throw on inline sourcemap', async () => { const result = await transformWithEsbuild(`const foo = 'bar'`, '', { - sourcemap: 'inline' + sourcemap: 'inline', }) expect(result?.code).toBeTruthy() expect(result?.map).toBeTruthy() diff --git a/packages/vite/src/node/__tests__/plugins/import.spec.ts b/packages/vite/src/node/__tests__/plugins/import.spec.ts index 6c1f950da4f7f2..792c58515f542e 100644 --- a/packages/vite/src/node/__tests__/plugins/import.spec.ts +++ b/packages/vite/src/node/__tests__/plugins/import.spec.ts @@ -11,21 +11,21 @@ describe('transformCjsImport', () => { 'import { useState, Component } from "react"', url, rawUrl, - 0 - ) + 0, + ), ).toBe( 'import __vite__cjsImport0_react from "./node_modules/.vite/deps/react.js"; ' + 'const useState = __vite__cjsImport0_react["useState"]; ' + - 'const Component = __vite__cjsImport0_react["Component"]' + 'const Component = __vite__cjsImport0_react["Component"]', ) }) test('import default specifier', () => { expect( - transformCjsImport('import React from "react"', url, rawUrl, 0) + transformCjsImport('import React from "react"', url, rawUrl, 0), ).toBe( 'import __vite__cjsImport0_react from "./node_modules/.vite/deps/react.js"; ' + - 'const React = __vite__cjsImport0_react.__esModule ? __vite__cjsImport0_react.default : __vite__cjsImport0_react' + 'const React = __vite__cjsImport0_react.__esModule ? __vite__cjsImport0_react.default : __vite__cjsImport0_react', ) expect( @@ -33,30 +33,30 @@ describe('transformCjsImport', () => { 'import { default as React } from "react"', url, rawUrl, - 0 - ) + 0, + ), ).toBe( 'import __vite__cjsImport0_react from "./node_modules/.vite/deps/react.js"; ' + - 'const React = __vite__cjsImport0_react.__esModule ? __vite__cjsImport0_react.default : __vite__cjsImport0_react' + 'const React = __vite__cjsImport0_react.__esModule ? __vite__cjsImport0_react.default : __vite__cjsImport0_react', ) }) test('import all specifier', () => { expect( - transformCjsImport('import * as react from "react"', url, rawUrl, 0) + transformCjsImport('import * as react from "react"', url, rawUrl, 0), ).toBe( 'import __vite__cjsImport0_react from "./node_modules/.vite/deps/react.js"; ' + - 'const react = __vite__cjsImport0_react' + 'const react = __vite__cjsImport0_react', ) }) test('export all specifier', () => { expect(transformCjsImport('export * from "react"', url, rawUrl, 0)).toBe( - undefined + undefined, ) expect( - transformCjsImport('export * as react from "react"', url, rawUrl, 0) + transformCjsImport('export * as react from "react"', url, rawUrl, 0), ).toBe(undefined) }) @@ -66,13 +66,13 @@ describe('transformCjsImport', () => { 'export { useState, Component } from "react"', url, rawUrl, - 0 - ) + 0, + ), ).toBe( 'import __vite__cjsImport0_react from "./node_modules/.vite/deps/react.js"; ' + 'const __vite__cjsExport_useState = __vite__cjsImport0_react["useState"]; ' + 'const __vite__cjsExport_Component = __vite__cjsImport0_react["Component"]; ' + - 'export { __vite__cjsExport_useState as useState, __vite__cjsExport_Component as Component }' + 'export { __vite__cjsExport_useState as useState, __vite__cjsExport_Component as Component }', ) expect( @@ -80,23 +80,23 @@ describe('transformCjsImport', () => { 'export { useState as useStateAlias, Component as ComponentAlias } from "react"', url, rawUrl, - 0 - ) + 0, + ), ).toBe( 'import __vite__cjsImport0_react from "./node_modules/.vite/deps/react.js"; ' + 'const __vite__cjsExport_useStateAlias = __vite__cjsImport0_react["useState"]; ' + 'const __vite__cjsExport_ComponentAlias = __vite__cjsImport0_react["Component"]; ' + - 'export { __vite__cjsExport_useStateAlias as useStateAlias, __vite__cjsExport_ComponentAlias as ComponentAlias }' + 'export { __vite__cjsExport_useStateAlias as useStateAlias, __vite__cjsExport_ComponentAlias as ComponentAlias }', ) }) test('export default specifier', () => { expect( - transformCjsImport('export { default } from "react"', url, rawUrl, 0) + transformCjsImport('export { default } from "react"', url, rawUrl, 0), ).toBe( 'import __vite__cjsImport0_react from "./node_modules/.vite/deps/react.js"; ' + 'const __vite__cjsExportDefault_0 = __vite__cjsImport0_react.__esModule ? __vite__cjsImport0_react.default : __vite__cjsImport0_react; ' + - 'export default __vite__cjsExportDefault_0' + 'export default __vite__cjsExportDefault_0', ) expect( @@ -104,12 +104,12 @@ describe('transformCjsImport', () => { 'export { default as React} from "react"', url, rawUrl, - 0 - ) + 0, + ), ).toBe( 'import __vite__cjsImport0_react from "./node_modules/.vite/deps/react.js"; ' + 'const __vite__cjsExport_React = __vite__cjsImport0_react.__esModule ? __vite__cjsImport0_react.default : __vite__cjsImport0_react; ' + - 'export { __vite__cjsExport_React as React }' + 'export { __vite__cjsExport_React as React }', ) expect( @@ -117,12 +117,12 @@ describe('transformCjsImport', () => { 'export { Component as default } from "react"', url, rawUrl, - 0 - ) + 0, + ), ).toBe( 'import __vite__cjsImport0_react from "./node_modules/.vite/deps/react.js"; ' + 'const __vite__cjsExportDefault_0 = __vite__cjsImport0_react["Component"]; ' + - 'export default __vite__cjsExportDefault_0' + 'export default __vite__cjsExportDefault_0', ) }) }) diff --git a/packages/vite/src/node/__tests__/plugins/importGlob/fixture-a/index.ts b/packages/vite/src/node/__tests__/plugins/importGlob/fixture-a/index.ts index 452336631be666..49b203c3ae093f 100644 --- a/packages/vite/src/node/__tests__/plugins/importGlob/fixture-a/index.ts +++ b/packages/vite/src/node/__tests__/plugins/importGlob/fixture-a/index.ts @@ -7,32 +7,32 @@ export interface ModuleType { export const basic = import.meta.glob('./modules/*.ts') export const basicEager = import.meta.glob('./modules/*.ts', { - eager: true + eager: true, }) export const ignore = import.meta.glob(['./modules/*.ts', '!**/index.ts']) export const namedEager = import.meta.glob('./modules/*.ts', { eager: true, - import: 'name' + import: 'name', }) export const namedDefault = import.meta.glob('./modules/*.ts', { - import: 'default' + import: 'default', }) export const eagerAs = import.meta.glob( ['./modules/*.ts', '!**/index.ts'], - { eager: true, as: 'raw' } + { eager: true, as: 'raw' }, ) export const rawImportModule = import.meta.glob( ['./modules/*.ts', '!**/index.ts'], - { as: 'raw', import: '*' } + { as: 'raw', import: '*' }, ) export const excludeSelf = import.meta.glob( - './*.ts' + './*.ts', // for test: annotation contain ")" /* * for test: annotation contain ")" @@ -44,25 +44,25 @@ export const customQueryString = import.meta.glob('./*.ts', { query: 'custom' }) export const customQueryObject = import.meta.glob('./*.ts', { query: { foo: 'bar', - raw: true - } + raw: true, + }, }) export const parent = import.meta.glob('../../playground/src/*.ts', { - as: 'url' + as: 'url', }) export const rootMixedRelative = import.meta.glob( ['/*.ts', '../fixture-b/*.ts'], - { as: 'url' } + { as: 'url' }, ) export const cleverCwd1 = import.meta.glob( - './node_modules/framework/**/*.page.js' + './node_modules/framework/**/*.page.js', ) export const cleverCwd2 = import.meta.glob([ './modules/*.ts', '../fixture-b/*.ts', - '!**/index.ts' + '!**/index.ts', ]) diff --git a/packages/vite/src/node/__tests__/plugins/importGlob/fixture.test.ts b/packages/vite/src/node/__tests__/plugins/importGlob/fixture.test.ts index cd6dc7c6fc4deb..22bacfa77edf6e 100644 --- a/packages/vite/src/node/__tests__/plugins/importGlob/fixture.test.ts +++ b/packages/vite/src/node/__tests__/plugins/importGlob/fixture.test.ts @@ -18,7 +18,9 @@ describe('fixture', async () => { ).code expect( - (await transformGlobImport(code, id, root, resolveId, true))?.s.toString() + ( + await transformGlobImport(code, id, root, resolveId, true) + )?.s.toString(), ).toMatchSnapshot() }) @@ -37,8 +39,8 @@ describe('fixture', async () => { import.meta.glob( './*.js' ) - `.trim() - ) + `.trim(), + ), ).toBe(3) }) @@ -46,12 +48,12 @@ describe('fixture', async () => { const root = resolve(__dirname, './fixture-a') const code = [ "import.meta.glob('/modules/*.ts')", - "import.meta.glob(['/../fixture-b/*.ts'])" + "import.meta.glob(['/../fixture-b/*.ts'])", ].join('\n') expect( ( await transformGlobImport(code, 'virtual:module', root, resolveId, true) - )?.s.toString() + )?.s.toString(), ).toMatchSnapshot() try { @@ -60,12 +62,12 @@ describe('fixture', async () => { 'virtual:module', root, resolveId, - true + true, ) expect('no error').toBe('should throw an error') } catch (err) { expect(err).toMatchInlineSnapshot( - "[Error: In virtual modules, all globs must start with '/']" + "[Error: In virtual modules, all globs must start with '/']", ) } }) @@ -79,7 +81,7 @@ describe('fixture', async () => { expect( ( await transformGlobImport(code, id, root, resolveId, true, true) - )?.s.toString() + )?.s.toString(), ).toMatchSnapshot() }) }) diff --git a/packages/vite/src/node/__tests__/plugins/importGlob/parse.test.ts b/packages/vite/src/node/__tests__/plugins/importGlob/parse.test.ts index c6a2a3efa7fa2e..58b357ed357630 100644 --- a/packages/vite/src/node/__tests__/plugins/importGlob/parse.test.ts +++ b/packages/vite/src/node/__tests__/plugins/importGlob/parse.test.ts @@ -6,12 +6,12 @@ async function run(input: string) { input, process.cwd(), process.cwd(), - (id) => id + (id) => id, ) return items.map((i) => ({ globs: i.globs, options: i.options, - start: i.start + start: i.start, })) } @@ -28,7 +28,7 @@ describe('parse positives', async () => { expect( await run(` import.meta.glob(\'./modules/*.ts\') - `) + `), ).toMatchInlineSnapshot(` [ { @@ -46,7 +46,7 @@ describe('parse positives', async () => { expect( await run(` import.meta.glob([\'./modules/*.ts\', './dir/*.{js,ts}\']) - `) + `), ).toMatchInlineSnapshot(` [ { @@ -71,7 +71,7 @@ describe('parse positives', async () => { eager: true, import: 'named' }) - `) + `), ).toMatchInlineSnapshot(` [ { @@ -99,7 +99,7 @@ describe('parse positives', async () => { * for test: annotation contain ")" * */ ) - `) + `), ).toMatchInlineSnapshot(` [ { @@ -125,7 +125,7 @@ describe('parse positives', async () => { } } ) - `) + `), ).toMatchInlineSnapshot(` [ { @@ -149,7 +149,7 @@ describe('parse positives', async () => { await run(` export const pageFiles = { '.page': import.meta.glob('/**/*.page.*([a-zA-Z0-9])') -};`) +};`), ).toMatchInlineSnapshot(` [ { @@ -168,7 +168,7 @@ describe('parse positives', async () => { await run(` export const pageFiles = { '.page': import.meta.glob('/**/*.page.*([a-zA-Z0-9])'), -};`) +};`), ).toMatchInlineSnapshot(` [ { @@ -188,7 +188,7 @@ describe('parse positives', async () => { export const pageFiles = { '.page.client': import.meta.glob('/**/*.page.client.*([a-zA-Z0-9])'), '.page.server': import.meta.glob('/**/*.page.server.*([a-zA-Z0-9])'), -};`) +};`), ).toMatchInlineSnapshot(` [ { @@ -215,7 +215,7 @@ describe('parse positives', async () => { export const pageFiles = [ import.meta.glob('/**/*.page.client.*([a-zA-Z0-9])'), import.meta.glob('/**/*.page.server.*([a-zA-Z0-9])'), - ]`) + ]`), ).toMatchInlineSnapshot(` [ { @@ -240,21 +240,21 @@ describe('parse positives', async () => { describe('parse negatives', async () => { it('syntax error', async () => { expect(await runError('import.meta.glob(')).toMatchInlineSnapshot( - '[SyntaxError: Unexpected token (1:17)]' + '[SyntaxError: Unexpected token (1:17)]', ) }) it('empty', async () => { expect(await runError('import.meta.glob()')).toMatchInlineSnapshot( - '[Error: Invalid glob import syntax: Expected 1-2 arguments, but got 0]' + '[Error: Invalid glob import syntax: Expected 1-2 arguments, but got 0]', ) }) it('3 args', async () => { expect( - await runError('import.meta.glob("", {}, {})') + await runError('import.meta.glob("", {}, {})'), ).toMatchInlineSnapshot( - '[Error: Invalid glob import syntax: Expected 1-2 arguments, but got 3]' + '[Error: Invalid glob import syntax: Expected 1-2 arguments, but got 3]', ) }) @@ -264,15 +264,15 @@ describe('parse negatives', async () => { it('variable', async () => { expect(await runError('import.meta.glob(hey)')).toMatchInlineSnapshot( - '[Error: Invalid glob import syntax: Could only use literals]' + '[Error: Invalid glob import syntax: Could only use literals]', ) }) it('template', async () => { expect( - await runError('import.meta.glob(`hi ${hey}`)') + await runError('import.meta.glob(`hi ${hey}`)'), ).toMatchInlineSnapshot( - '[Error: Invalid glob import syntax: Expected glob to be a string, but got dynamic template literal]' + '[Error: Invalid glob import syntax: Expected glob to be a string, but got dynamic template literal]', ) }) @@ -308,75 +308,75 @@ describe('parse negatives', async () => { it('be string', async () => { expect(await runError('import.meta.glob(1)')).toMatchInlineSnapshot( - '[Error: Invalid glob import syntax: Expected glob to be a string, but got "number"]' + '[Error: Invalid glob import syntax: Expected glob to be a string, but got "number"]', ) }) it('be array variable', async () => { expect(await runError('import.meta.glob([hey])')).toMatchInlineSnapshot( - '[Error: Invalid glob import syntax: Could only use literals]' + '[Error: Invalid glob import syntax: Could only use literals]', ) expect( - await runError('import.meta.glob(["1", hey])') + await runError('import.meta.glob(["1", hey])'), ).toMatchInlineSnapshot( - '[Error: Invalid glob import syntax: Could only use literals]' + '[Error: Invalid glob import syntax: Could only use literals]', ) }) it('options', async () => { expect( - await runError('import.meta.glob("hey", hey)') + await runError('import.meta.glob("hey", hey)'), ).toMatchInlineSnapshot( - '[Error: Invalid glob import syntax: Expected the second argument to be an object literal, but got "Identifier"]' + '[Error: Invalid glob import syntax: Expected the second argument to be an object literal, but got "Identifier"]', ) expect(await runError('import.meta.glob("hey", [])')).toMatchInlineSnapshot( - '[Error: Invalid glob import syntax: Expected the second argument to be an object literal, but got "ArrayExpression"]' + '[Error: Invalid glob import syntax: Expected the second argument to be an object literal, but got "ArrayExpression"]', ) }) it('options props', async () => { expect( - await runError('import.meta.glob("hey", { hey: 1 })') + await runError('import.meta.glob("hey", { hey: 1 })'), ).toMatchInlineSnapshot('[Error: Unknown glob option "hey"]') expect( - await runError('import.meta.glob("hey", { import: hey })') + await runError('import.meta.glob("hey", { import: hey })'), ).toMatchInlineSnapshot( - '[Error: Vite is unable to parse the glob options as the value is not static]' + '[Error: Vite is unable to parse the glob options as the value is not static]', ) expect( - await runError('import.meta.glob("hey", { eager: 123 })') + await runError('import.meta.glob("hey", { eager: 123 })'), ).toMatchInlineSnapshot( - '[Error: Expected glob option "eager" to be of type boolean, but got number]' + '[Error: Expected glob option "eager" to be of type boolean, but got number]', ) }) it('options query', async () => { expect( - await runError('import.meta.glob("./*.js", { as: "raw", query: "hi" })') + await runError('import.meta.glob("./*.js", { as: "raw", query: "hi" })'), ).toMatchInlineSnapshot( - '[Error: Options "as" and "query" cannot be used together]' + '[Error: Options "as" and "query" cannot be used together]', ) expect( - await runError('import.meta.glob("./*.js", { query: 123 })') + await runError('import.meta.glob("./*.js", { query: 123 })'), ).toMatchInlineSnapshot( - '[Error: Expected glob option "query" to be of type object or string, but got number]' + '[Error: Expected glob option "query" to be of type object or string, but got number]', ) expect( - await runError('import.meta.glob("./*.js", { query: { foo: {} } })') + await runError('import.meta.glob("./*.js", { query: { foo: {} } })'), ).toMatchInlineSnapshot( - '[Error: Expected glob option "query.foo" to be of type string, number, or boolean, but got object]' + '[Error: Expected glob option "query.foo" to be of type string, number, or boolean, but got object]', ) expect( - await runError('import.meta.glob("./*.js", { query: { foo: hey } })') + await runError('import.meta.glob("./*.js", { query: { foo: hey } })'), ).toMatchInlineSnapshot( - '[Error: Vite is unable to parse the glob options as the value is not static]' + '[Error: Vite is unable to parse the glob options as the value is not static]', ) expect( await runError( - 'import.meta.glob("./*.js", { query: { foo: 123, ...a } })' - ) + 'import.meta.glob("./*.js", { query: { foo: 123, ...a } })', + ), ).toMatchInlineSnapshot( - '[Error: Vite is unable to parse the glob options as the value is not static]' + '[Error: Vite is unable to parse the glob options as the value is not static]', ) }) }) diff --git a/packages/vite/src/node/__tests__/plugins/importGlob/utils.test.ts b/packages/vite/src/node/__tests__/plugins/importGlob/utils.test.ts index 302df97ec92ede..bd91c6165f798e 100644 --- a/packages/vite/src/node/__tests__/plugins/importGlob/utils.test.ts +++ b/packages/vite/src/node/__tests__/plugins/importGlob/utils.test.ts @@ -10,10 +10,10 @@ describe('getCommonBase()', async () => { }) it('static file', () => { expect( - getCommonBase(['/a/b/**/*.vue', '/a/b/**/*.jsx', '/a/b/foo.js']) + getCommonBase(['/a/b/**/*.vue', '/a/b/**/*.jsx', '/a/b/foo.js']), ).toBe('/a/b') expect(getCommonBase(['/a/b/**/*.vue', '/a/b/**/*.jsx', '/a/foo.js'])).toBe( - '/a' + '/a', ) }) it('correct `scan()`', () => { diff --git a/packages/vite/src/node/__tests__/scan.spec.ts b/packages/vite/src/node/__tests__/scan.spec.ts index 0f9475562365d5..0a417f37a49b0a 100644 --- a/packages/vite/src/node/__tests__/scan.spec.ts +++ b/packages/vite/src/node/__tests__/scan.spec.ts @@ -14,14 +14,14 @@ describe('optimizer-scan:script-test', () => { test('component return value test', () => { scriptRE.lastIndex = 0 const [, tsOpenTag, tsContent] = scriptRE.exec( - `` + ``, ) expect(tsOpenTag).toEqual('` + ``, ) expect(openTag).toEqual(' const filePath = id.replace(normalizePath(config.root), '') addToHTMLProxyCache(config, filePath, inlineModuleIndex, { - code: contents + code: contents, }) js += `\nimport "${id}?html-proxy&index=${inlineModuleIndex}.js"` shouldRemove = true @@ -389,7 +389,7 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin { } else if (url && !isPublicFile) { if (!isExcludedUrl(url)) { config.logger.warn( - ` diff --git a/packages/vite/src/node/server/middlewares/htmlFallback.ts b/packages/vite/src/node/server/middlewares/htmlFallback.ts index 7976d24c0b09f0..b646488dddfff4 100644 --- a/packages/vite/src/node/server/middlewares/htmlFallback.ts +++ b/packages/vite/src/node/server/middlewares/htmlFallback.ts @@ -6,7 +6,7 @@ import { createDebugger } from '../../utils' export function htmlFallbackMiddleware( root: string, - spaFallback: boolean + spaFallback: boolean, ): Connect.NextHandleFunction { const historyHtmlFallbackMiddleware = history({ logger: createDebugger('vite:html-fallback'), @@ -23,9 +23,9 @@ export function htmlFallbackMiddleware( } return spaFallback ? `/index.html` : request.url - } - } - ] + }, + }, + ], }) // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...` diff --git a/packages/vite/src/node/server/middlewares/indexHtml.ts b/packages/vite/src/node/server/middlewares/indexHtml.ts index 13e4468c3fb291..9701637c0b544a 100644 --- a/packages/vite/src/node/server/middlewares/indexHtml.ts +++ b/packages/vite/src/node/server/middlewares/indexHtml.ts @@ -16,7 +16,7 @@ import { postImportMapHook, preImportMapHook, resolveHtmlTransforms, - traverseHtml + traverseHtml, } from '../../plugins/html' import type { ResolvedConfig, ViteDevServer } from '../..' import { send } from '../send' @@ -29,7 +29,7 @@ import { joinUrlSegments, normalizePath, processSrcSetSync, - wrapId + wrapId, } from '../../utils' import type { ModuleGraph } from '../moduleGraph' @@ -40,10 +40,10 @@ interface AssetNode { } export function createDevHtmlTransformFn( - server: ViteDevServer + server: ViteDevServer, ): (url: string, html: string, originalUrl: string) => Promise { const [preHooks, normalHooks, postHooks] = resolveHtmlTransforms( - server.config.plugins + server.config.plugins, ) return (url: string, html: string, originalUrl: string): Promise => { return applyHtmlTransforms( @@ -54,14 +54,14 @@ export function createDevHtmlTransformFn( devHtmlHook, ...normalHooks, ...postHooks, - postImportMapHook() + postImportMapHook(), ], { path: url, filename: getHtmlFilename(url, server), server, - originalUrl - } + originalUrl, + }, ) } } @@ -71,7 +71,7 @@ function getHtmlFilename(url: string, server: ViteDevServer) { return decodeURIComponent(fsPathFromId(url)) } else { return decodeURIComponent( - normalizePath(path.join(server.config.root, url.slice(1))) + normalizePath(path.join(server.config.root, url.slice(1))), ) } } @@ -84,7 +84,7 @@ const processNodeUrl = ( config: ResolvedConfig, htmlPath: string, originalUrl?: string, - moduleGraph?: ModuleGraph + moduleGraph?: ModuleGraph, ) => { let url = attr.value || '' @@ -122,7 +122,7 @@ const processNodeUrl = ( } const devHtmlHook: IndexHtmlTransformHook = async ( html, - { path: htmlPath, filename, server, originalUrl } + { path: htmlPath, filename, server, originalUrl }, ) => { const { config, moduleGraph, watcher } = server! const base = config.base || '/' @@ -149,13 +149,13 @@ const devHtmlHook: IndexHtmlTransformHook = async ( let inlineModuleIndex = -1 const proxyCacheUrl = cleanUrl(proxyModulePath).replace( normalizePath(config.root), - '' + '', ) const styleUrl: AssetNode[] = [] const addInlineModule = ( node: DefaultTreeAdapterMap['element'], - ext: 'js' + ext: 'js', ) => { inlineModuleIndex++ @@ -168,7 +168,7 @@ const devHtmlHook: IndexHtmlTransformHook = async ( map = new MagicString(html) .snip( contentNode.sourceCodeLocation!.startOffset, - contentNode.sourceCodeLocation!.endOffset + contentNode.sourceCodeLocation!.endOffset, ) .generateMap({ hires: true }) map.sources = [filename] @@ -189,7 +189,7 @@ const devHtmlHook: IndexHtmlTransformHook = async ( s.update( node.sourceCodeLocation!.startOffset, node.sourceCodeLocation!.endOffset, - `` + ``, ) } @@ -210,7 +210,7 @@ const devHtmlHook: IndexHtmlTransformHook = async ( config, htmlPath, originalUrl, - moduleGraph + moduleGraph, ) } else if (isModule && node.childNodes.length) { addInlineModule(node, 'js') @@ -222,7 +222,7 @@ const devHtmlHook: IndexHtmlTransformHook = async ( styleUrl.push({ start: children.sourceCodeLocation!.startOffset, end: children.sourceCodeLocation!.endOffset, - code: children.value + code: children.value, }) } @@ -238,7 +238,7 @@ const devHtmlHook: IndexHtmlTransformHook = async ( s, config, htmlPath, - originalUrl + originalUrl, ) } } @@ -255,7 +255,7 @@ const devHtmlHook: IndexHtmlTransformHook = async ( const result = await server!.pluginContainer.transform(code, mod.id!) s.overwrite(start, end, result?.code || '') - }) + }), ) html = s.toString() @@ -267,16 +267,16 @@ const devHtmlHook: IndexHtmlTransformHook = async ( tag: 'script', attrs: { type: 'module', - src: path.posix.join(base, CLIENT_PUBLIC_PATH) + src: path.posix.join(base, CLIENT_PUBLIC_PATH), }, - injectTo: 'head-prepend' - } - ] + injectTo: 'head-prepend', + }, + ], } } export function indexHtmlMiddleware( - server: ViteDevServer + server: ViteDevServer, ): Connect.NextHandleFunction { // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...` return async function viteIndexHtmlMiddleware(req, res, next) { @@ -293,7 +293,7 @@ export function indexHtmlMiddleware( let html = fs.readFileSync(filename, 'utf-8') html = await server.transformIndexHtml(url, html, req.originalUrl) return send(req, res, html, 'html', { - headers: server.config.server.headers + headers: server.config.server.headers, }) } catch (e) { return next(e) diff --git a/packages/vite/src/node/server/middlewares/proxy.ts b/packages/vite/src/node/server/middlewares/proxy.ts index 3e08e3c6aca901..43fce52e3befdf 100644 --- a/packages/vite/src/node/server/middlewares/proxy.ts +++ b/packages/vite/src/node/server/middlewares/proxy.ts @@ -25,14 +25,14 @@ export interface ProxyOptions extends HttpProxy.ServerOptions { bypass?: ( req: http.IncomingMessage, res: http.ServerResponse, - options: ProxyOptions + options: ProxyOptions, ) => void | null | undefined | false | string } export function proxyMiddleware( httpServer: http.Server | null, options: NonNullable, - config: ResolvedConfig + config: ResolvedConfig, ): Connect.NextHandleFunction { // lazy require only when proxy is used const proxies: Record = {} @@ -57,20 +57,20 @@ export function proxyMiddleware( }`, { timestamp: true, - error: err - } + error: err, + }, ) if (!res.headersSent && !res.writableEnded) { res .writeHead(500, { - 'Content-Type': 'text/plain' + 'Content-Type': 'text/plain', }) .end() } } else { config.logger.error(`${colors.red(`ws proxy error:`)}\n${err.stack}`, { timestamp: true, - error: err + error: err, }) res.end() } diff --git a/packages/vite/src/node/server/middlewares/static.ts b/packages/vite/src/node/server/middlewares/static.ts index 8f6b47f3a7e4bb..4e54af75d84538 100644 --- a/packages/vite/src/node/server/middlewares/static.ts +++ b/packages/vite/src/node/server/middlewares/static.ts @@ -15,7 +15,7 @@ import { isParentDirectory, isWindows, shouldServe, - slash + slash, } from '../../utils' const sirvOptions = (headers?: OutgoingHttpHeaders): Options => { @@ -37,13 +37,13 @@ const sirvOptions = (headers?: OutgoingHttpHeaders): Options => { res.setHeader(name, headers[name]!) } } - } + }, } } export function servePublicMiddleware( dir: string, - headers?: OutgoingHttpHeaders + headers?: OutgoingHttpHeaders, ): Connect.NextHandleFunction { const serve = sirv(dir, sirvOptions(headers)) @@ -62,7 +62,7 @@ export function servePublicMiddleware( export function serveStaticMiddleware( dir: string, - server: ViteDevServer + server: ViteDevServer, ): Connect.NextHandleFunction { const serve = sirv(dir, sirvOptions(server.config.server.headers)) @@ -122,7 +122,7 @@ export function serveStaticMiddleware( } export function serveRawFsMiddleware( - server: ViteDevServer + server: ViteDevServer, ): Connect.NextHandleFunction { const serveFromRoot = sirv('/', sirvOptions(server.config.server.headers)) @@ -141,7 +141,7 @@ export function serveRawFsMiddleware( slash(path.resolve(fsPathFromId(pathname))), server, res, - next + next, ) ) { return @@ -161,7 +161,7 @@ export function serveRawFsMiddleware( export function isFileServingAllowed( url: string, - server: ViteDevServer + server: ViteDevServer, ): boolean { if (!server.config.server.fs.strict) return true @@ -181,7 +181,7 @@ function ensureServingAccess( url: string, server: ViteDevServer, res: ServerResponse, - next: Connect.NextFunction + next: Connect.NextFunction, ): boolean { if (isFileServingAllowed(url, server)) { return true diff --git a/packages/vite/src/node/server/middlewares/transform.ts b/packages/vite/src/node/server/middlewares/transform.ts index 831ea2c2139a2b..f9ee475451a93b 100644 --- a/packages/vite/src/node/server/middlewares/transform.ts +++ b/packages/vite/src/node/server/middlewares/transform.ts @@ -15,7 +15,7 @@ import { prettifyUrl, removeImportQuery, removeTimestampQuery, - unwrapId + unwrapId, } from '../../utils' import { send } from '../send' import { ERR_LOAD_URL, transformRequest } from '../transformRequest' @@ -23,16 +23,16 @@ import { isHTMLProxy } from '../../plugins/html' import { DEP_VERSION_RE, FS_PREFIX, - NULL_BYTE_PLACEHOLDER + NULL_BYTE_PLACEHOLDER, } from '../../constants' import { isCSSRequest, isDirectCSSRequest, - isDirectRequest + isDirectRequest, } from '../../plugins/css' import { ERR_OPTIMIZE_DEPS_PROCESSING_ERROR, - ERR_OUTDATED_OPTIMIZED_DEP + ERR_OUTDATED_OPTIMIZED_DEP, } from '../../plugins/optimizedDeps' import { getDepsOptimizer } from '../../optimizer' @@ -42,11 +42,11 @@ const isDebug = !!process.env.DEBUG const knownIgnoreList = new Set(['/', '/favicon.ico']) export function transformMiddleware( - server: ViteDevServer + server: ViteDevServer, ): Connect.NextHandleFunction { const { config: { root, logger }, - moduleGraph + moduleGraph, } = server // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...` @@ -59,7 +59,7 @@ export function transformMiddleware( try { url = decodeURI(removeTimestampQuery(req.url!)).replace( NULL_BYTE_PLACEHOLDER, - '\0' + '\0', ) } catch (e) { return next(e) @@ -78,12 +78,12 @@ export function transformMiddleware( const mapFile = url.startsWith(FS_PREFIX) ? fsPathFromId(url) : normalizePath( - ensureVolumeInPath(path.resolve(root, url.slice(1))) + ensureVolumeInPath(path.resolve(root, url.slice(1))), ) try { const map = await fs.readFile(mapFile, 'utf-8') return send(req, res, map, 'json', { - headers: server.config.server.headers + headers: server.config.server.headers, }) } catch (e) { // Outdated source map request for optimized deps, this isn't an error @@ -95,11 +95,11 @@ export function transformMiddleware( sources: [], sourcesContent: [], names: [], - mappings: ';;;;;;;;;' + mappings: ';;;;;;;;;', } return send(req, res, JSON.stringify(dummySourceMap), 'json', { cacheControl: 'no-cache', - headers: server.config.server.headers + headers: server.config.server.headers, }) } } else { @@ -108,7 +108,7 @@ export function transformMiddleware( ?.transformResult?.map if (map) { return send(req, res, JSON.stringify(map), 'json', { - headers: server.config.server.headers + headers: server.config.server.headers, }) } else { return next() @@ -131,15 +131,15 @@ export function transformMiddleware( warning = 'Assets in public cannot be imported from JavaScript.\n' + `Instead of ${colors.cyan( - rawUrl + rawUrl, )}, put the file in the src directory, and use ${colors.cyan( - rawUrl.replace(publicPath, '/src/') + rawUrl.replace(publicPath, '/src/'), )} instead.` } else { warning = `files in the public directory are served at the root path.\n` + `Instead of ${colors.cyan(url)}, use ${colors.cyan( - url.replace(publicPath, '/') + url.replace(publicPath, '/'), )}.` } @@ -183,7 +183,7 @@ export function transformMiddleware( // resolve, load and transform using the plugin container const result = await transformRequest(url, server, { - html: req.headers.accept?.includes('text/html') + html: req.headers.accept?.includes('text/html'), }) if (result) { const depsOptimizer = getDepsOptimizer(server.config, false) // non-ssr @@ -195,7 +195,7 @@ export function transformMiddleware( // allow browser to cache npm deps! cacheControl: isDep ? 'max-age=31536000,immutable' : 'no-cache', headers: server.config.server.headers, - map: result.map + map: result.map, }) } } diff --git a/packages/vite/src/node/server/moduleGraph.ts b/packages/vite/src/node/server/moduleGraph.ts index b9d928b589e00b..895ebe02f4960d 100644 --- a/packages/vite/src/node/server/moduleGraph.ts +++ b/packages/vite/src/node/server/moduleGraph.ts @@ -5,7 +5,7 @@ import { cleanUrl, normalizePath, removeImportQuery, - removeTimestampQuery + removeTimestampQuery, } from '../utils' import { FS_PREFIX } from '../constants' import type { TransformResult } from './transformRequest' @@ -61,7 +61,7 @@ function invalidateSSRModule(mod: ModuleNode, seen: Set) { export type ResolvedUrl = [ url: string, resolvedId: string, - meta: object | null | undefined + meta: object | null | undefined, ] export class ModuleGraph { @@ -74,13 +74,13 @@ export class ModuleGraph { constructor( private resolveId: ( url: string, - ssr: boolean - ) => Promise + ssr: boolean, + ) => Promise, ) {} async getModuleByUrl( rawUrl: string, - ssr?: boolean + ssr?: boolean, ): Promise { const [url] = await this.resolveUrl(rawUrl, ssr) return this.urlToModuleMap.get(url) @@ -107,7 +107,7 @@ export class ModuleGraph { invalidateModule( mod: ModuleNode, seen: Set = new Set(), - timestamp: number = Date.now() + timestamp: number = Date.now(), ): void { // Save the timestamp for this invalidation, so we can avoid caching the result of possible already started // processing being done for this module @@ -139,7 +139,7 @@ export class ModuleGraph { acceptedModules: Set, acceptedExports: Set | null, isSelfAccepting: boolean, - ssr?: boolean + ssr?: boolean, ): Promise | undefined> { mod.isSelfAccepting = isSelfAccepting const prevImports = mod.importedModules @@ -182,7 +182,7 @@ export class ModuleGraph { async ensureEntryFromUrl( rawUrl: string, ssr?: boolean, - setIsSelfAccepting = true + setIsSelfAccepting = true, ): Promise { const [url, resolvedId, meta] = await this.resolveUrl(rawUrl, ssr) let mod = this.idToModuleMap.get(resolvedId) diff --git a/packages/vite/src/node/server/openBrowser.ts b/packages/vite/src/node/server/openBrowser.ts index 72fe339937a624..bf2a383d6b7aba 100644 --- a/packages/vite/src/node/server/openBrowser.ts +++ b/packages/vite/src/node/server/openBrowser.ts @@ -23,7 +23,7 @@ import { VITE_PACKAGE_DIR } from '../constants' export function openBrowser( url: string, opt: string | true, - logger: Logger + logger: Logger, ): boolean { // The browser executable to open. // See https://github.com/sindresorhus/open#app for documentation. @@ -39,17 +39,17 @@ export function openBrowser( function executeNodeScript(scriptPath: string, url: string, logger: Logger) { const extraArgs = process.argv.slice(2) const child = spawn(process.execPath, [scriptPath, ...extraArgs, url], { - stdio: 'inherit' + stdio: 'inherit', }) child.on('close', (code) => { if (code !== 0) { logger.error( colors.red( `\nThe script specified as BROWSER environment variable failed.\n\n${colors.cyan( - scriptPath - )} exited with code ${code}.` + scriptPath, + )} exited with code ${code}.`, ), - { error: null } + { error: null }, ) } }) @@ -64,7 +64,7 @@ const supportedChromiumBrowsers = [ 'Microsoft Edge', 'Brave Browser', 'Vivaldi', - 'Chromium' + 'Chromium', ] function startBrowserProcess(browser: string | undefined, url: string) { @@ -89,12 +89,12 @@ function startBrowserProcess(browser: string | undefined, url: string) { // Try our best to reuse existing tab with AppleScript execSync( `osascript openChrome.applescript "${encodeURI( - url + url, )}" "${openedBrowser}"`, { cwd: join(VITE_PACKAGE_DIR, 'bin'), - stdio: 'ignore' - } + stdio: 'ignore', + }, ) return true } catch (err) { diff --git a/packages/vite/src/node/server/pluginContainer.ts b/packages/vite/src/node/server/pluginContainer.ts index 4c4d7ffb1f1a13..f16498c3bbf50c 100644 --- a/packages/vite/src/node/server/pluginContainer.ts +++ b/packages/vite/src/node/server/pluginContainer.ts @@ -51,7 +51,7 @@ import type { PluginContext as RollupPluginContext, SourceDescription, SourceMap, - TransformResult + TransformResult, } from 'rollup' import * as acorn from 'acorn' import type { RawSourceMap } from '@ampproject/remapping' @@ -73,7 +73,7 @@ import { normalizePath, numberToPos, prettifyUrl, - timeFrom + timeFrom, } from '../utils' import { FS_PREFIX } from '../constants' import type { ResolvedConfig } from '../config' @@ -105,7 +105,7 @@ export interface PluginContainer { */ scan?: boolean isEntry?: boolean - } + }, ): Promise transform( code: string, @@ -113,13 +113,13 @@ export interface PluginContainer { options?: { inMap?: SourceDescription['map'] ssr?: boolean - } + }, ): Promise load( id: string, options?: { ssr?: boolean - } + }, ): Promise close(): Promise } @@ -139,14 +139,14 @@ export let parser = acorn.Parser export async function createPluginContainer( config: ResolvedConfig, moduleGraph?: ModuleGraph, - watcher?: FSWatcher + watcher?: FSWatcher, ): Promise { const isDebug = process.env.DEBUG const { plugins, logger, root, - build: { rollupOptions } + build: { rollupOptions }, } = config const { getSortedPluginHooks, getSortedPlugins } = createPluginHookUtils(plugins) @@ -154,19 +154,19 @@ export async function createPluginContainer( const seenResolves: Record = {} const debugResolve = createDebugger('vite:resolve') const debugPluginResolve = createDebugger('vite:plugin-resolve', { - onlyWhenFocused: 'vite:plugin' + onlyWhenFocused: 'vite:plugin', }) const debugPluginTransform = createDebugger('vite:plugin-transform', { - onlyWhenFocused: 'vite:plugin' + onlyWhenFocused: 'vite:plugin', }) const debugSourcemapCombineFlag = 'vite:sourcemap-combine' const isDebugSourcemapCombineFocused = process.env.DEBUG?.includes( - debugSourcemapCombineFlag + debugSourcemapCombineFlag, ) const debugSourcemapCombineFilter = process.env.DEBUG_VITE_SOURCEMAP_COMBINE_FILTER const debugSourcemapCombine = createDebugger('vite:sourcemap-combine', { - onlyWhenFocused: true + onlyWhenFocused: true, }) // --------------------------------------------------------------------------- @@ -176,8 +176,8 @@ export async function createPluginContainer( const minimalContext: MinimalPluginContext = { meta: { rollupVersion, - watchMode: true - } + watchMode: true, + }, } function warnIncompatibleMethod(method: string, plugin: string) { @@ -185,9 +185,9 @@ export async function createPluginContainer( colors.cyan(`[plugin:${plugin}] `) + colors.yellow( `context method ${colors.bold( - `${method}()` - )} is not supported in serve mode. This plugin is likely not vite-compatible.` - ) + `${method}()`, + )} is not supported in serve mode. This plugin is likely not vite-compatible.`, + ), ) } @@ -195,7 +195,7 @@ export async function createPluginContainer( async function hookParallel( hookName: H, context: (plugin: Plugin) => ThisType, - args: (plugin: Plugin) => Parameters + args: (plugin: Plugin) => Parameters, ): Promise { const parallelPromises: Promise[] = [] for (const plugin of getSortedPlugins(hookName)) { @@ -221,9 +221,9 @@ export async function createPluginContainer( return info[key] } throw Error( - `[vite] The "${key}" property of ModuleInfo is not supported.` + `[vite] The "${key}" property of ModuleInfo is not supported.`, ) - } + }, } // same default value of "moduleInfo.meta" as in Rollup @@ -237,7 +237,7 @@ export async function createPluginContainer( if (!module.info) { module.info = new Proxy( { id, meta: module.meta || EMPTY_OBJECT } as ModuleInfo, - ModuleInfoProxy + ModuleInfoProxy, ) } return module.info @@ -274,7 +274,7 @@ export async function createPluginContainer( sourceType: 'module', ecmaVersion: 'latest', locations: true, - ...opts + ...opts, }) } @@ -286,7 +286,7 @@ export async function createPluginContainer( custom?: CustomPluginOptions isEntry?: boolean skipSelf?: boolean - } + }, ) { let skip: Set | undefined if (options?.skipSelf && this._activePlugin) { @@ -299,7 +299,7 @@ export async function createPluginContainer( isEntry: !!options?.isEntry, skip, ssr: this.ssr, - scan: this._scan + scan: this._scan, }) if (typeof out === 'string') out = { id: out } return out as ResolvedId | null @@ -341,23 +341,23 @@ export async function createPluginContainer( warn( e: string | RollupError, - position?: number | { column: number; line: number } + position?: number | { column: number; line: number }, ) { const err = formatError(e, position, this) const msg = buildErrorMessage( err, [colors.yellow(`warning: ${err.message}`)], - false + false, ) logger.warn(msg, { clear: true, - timestamp: true + timestamp: true, }) } error( e: string | RollupError, - position?: number | { column: number; line: number } + position?: number | { column: number; line: number }, ): never { // error thrown here is caught by the transform middleware and passed on // the the error middleware. @@ -368,7 +368,7 @@ export async function createPluginContainer( function formatError( e: string | RollupError, position: number | { column: number; line: number } | undefined, - ctx: Context + ctx: Context, ) { const err = ( typeof e === 'string' ? new Error(e) : e @@ -399,16 +399,16 @@ export async function createPluginContainer( } catch (err2) { logger.error( colors.red( - `Error in error handler:\n${err2.stack || err2.message}\n` + `Error in error handler:\n${err2.stack || err2.message}\n`, ), // print extra newline to separate the two errors - { error: err2 } + { error: err2 }, ) throw err } err.loc = err.loc || { file: err.id, - ...errLocation + ...errLocation, } err.frame = err.frame || generateCodeFrame(ctx._activeCode, pos) } else if (err.loc) { @@ -427,7 +427,7 @@ export async function createPluginContainer( err.loc = { file: err.id, line: (err as any).line, - column: (err as any).column + column: (err as any).column, } err.frame = err.frame || generateCodeFrame(err.id!, err.loc) } @@ -438,7 +438,7 @@ export async function createPluginContainer( const traced = new TraceMap(rawSourceMap as any) const { source, line, column } = originalPositionFor(traced, { line: Number(err.loc.line), - column: Number(err.loc.column) + column: Number(err.loc.column), }) if (source && line != null && column != null) { err.loc = { file: source, line, column } @@ -495,9 +495,9 @@ export async function createPluginContainer( combinedMap = combineSourcemaps(cleanUrl(this.filename), [ { ...(m as RawSourceMap), - sourcesContent: combinedMap.sourcesContent + sourcesContent: combinedMap.sourcesContent, }, - combinedMap as RawSourceMap + combinedMap as RawSourceMap, ]) as SourceMap } } @@ -506,7 +506,7 @@ export async function createPluginContainer( ? new MagicString(this.originalCode).generateMap({ includeContent: true, hires: true, - source: cleanUrl(this.filename) + source: cleanUrl(this.filename), }) : null } @@ -532,13 +532,13 @@ export async function createPluginContainer( } if (options.acornInjectPlugins) { parser = acorn.Parser.extend( - ...(arraify(options.acornInjectPlugins) as any) + ...(arraify(options.acornInjectPlugins) as any), ) } return { acorn, acornInjectPlugins: [], - ...options + ...options, } })(), @@ -548,7 +548,7 @@ export async function createPluginContainer( await hookParallel( 'buildStart', (plugin) => new Context(plugin), - () => [container.options as NormalizedInputOptions] + () => [container.options as NormalizedInputOptions], ) }, @@ -580,7 +580,7 @@ export async function createPluginContainer( custom: options?.custom, isEntry: !!options?.isEntry, ssr, - scan + scan, }) if (!result) continue @@ -595,7 +595,7 @@ export async function createPluginContainer( debugPluginResolve( timeFrom(pluginResolveStart), plugin.name, - prettifyUrl(id, root) + prettifyUrl(id, root), ) // resolveId() is hookFirst - first non-null result is returned. @@ -609,8 +609,8 @@ export async function createPluginContainer( seenResolves[key] = true debugResolve( `${timeFrom(resolveStart)} ${colors.cyan(rawId)} -> ${colors.dim( - id - )}` + id, + )}`, ) } } @@ -669,7 +669,7 @@ export async function createPluginContainer( debugPluginTransform( timeFrom(start), plugin.name, - prettifyUrl(id, root) + prettifyUrl(id, root), ) if (isObject(result)) { if (result.code !== undefined) { @@ -689,7 +689,7 @@ export async function createPluginContainer( } return { code, - map: ctx._getCombinedSourcemap() + map: ctx._getCombinedSourcemap(), } }, @@ -699,15 +699,15 @@ export async function createPluginContainer( await hookParallel( 'buildEnd', () => ctx, - () => [] + () => [], ) await hookParallel( 'closeBundle', () => ctx, - () => [] + () => [], ) closed = true - } + }, } return container diff --git a/packages/vite/src/node/server/searchRoot.ts b/packages/vite/src/node/server/searchRoot.ts index b40226f4a53e38..2a2ebd2660a6cb 100644 --- a/packages/vite/src/node/server/searchRoot.ts +++ b/packages/vite/src/node/server/searchRoot.ts @@ -17,7 +17,7 @@ const ROOT_FILES = [ // 'nx.json', // https://github.com/lerna/lerna#lernajson - 'lerna.json' + 'lerna.json', ] // npm: https://docs.npmjs.com/cli/v7/using-npm/workspaces#installing-workspaces @@ -58,7 +58,7 @@ export function searchForPackageRoot(current: string, root = current): string { */ export function searchForWorkspaceRoot( current: string, - root = searchForPackageRoot(current) + root = searchForPackageRoot(current), ): string { if (hasRootFile(current)) return current if (hasWorkspacePackageJSON(current)) return current diff --git a/packages/vite/src/node/server/send.ts b/packages/vite/src/node/server/send.ts index 51f1fa65afed25..aadebd1628885c 100644 --- a/packages/vite/src/node/server/send.ts +++ b/packages/vite/src/node/server/send.ts @@ -1,7 +1,7 @@ import type { IncomingMessage, OutgoingHttpHeaders, - ServerResponse + ServerResponse, } from 'node:http' import getEtag from 'etag' import type { SourceMap } from 'rollup' @@ -11,7 +11,7 @@ const alias: Record = { js: 'application/javascript', css: 'text/css', html: 'text/html', - json: 'application/json' + json: 'application/json', } export interface SendOptions { @@ -26,13 +26,13 @@ export function send( res: ServerResponse, content: string | Buffer, type: string, - options: SendOptions + options: SendOptions, ): void { const { etag = getEtag(content, { weak: true }), cacheControl = 'no-cache', headers, - map + map, } = options if (res.writableEnded) { diff --git a/packages/vite/src/node/server/sourcemap.ts b/packages/vite/src/node/server/sourcemap.ts index 774d74dc8bb398..96c62d590c6fdc 100644 --- a/packages/vite/src/node/server/sourcemap.ts +++ b/packages/vite/src/node/server/sourcemap.ts @@ -6,7 +6,7 @@ import { createDebugger } from '../utils' const isDebug = !!process.env.DEBUG const debug = createDebugger('vite:sourcemap', { - onlyWhenFocused: true + onlyWhenFocused: true, }) // Virtual modules should be prefixed with a null byte to avoid a @@ -23,13 +23,13 @@ interface SourceMapLike { export async function injectSourcesContent( map: SourceMapLike, file: string, - logger: Logger + logger: Logger, ): Promise { let sourceRoot: string | undefined try { // The source root is undefined for virtual modules and permission errors. sourceRoot = await fs.realpath( - path.resolve(path.dirname(file), map.sourceRoot || '') + path.resolve(path.dirname(file), map.sourceRoot || ''), ) } catch {} @@ -47,7 +47,7 @@ export async function injectSourcesContent( }) } return null - }) + }), ) // Use this command… @@ -69,7 +69,7 @@ export function genSourceMapUrl(map: SourceMap | string | undefined): string { export function getCodeWithSourcemap( type: 'js' | 'css', code: string, - map: SourceMap | null + map: SourceMap | null, ): string { if (isDebug) { code += `\n/*${JSON.stringify(map, null, 2).replace(/\*\//g, '*\\/')}*/\n` diff --git a/packages/vite/src/node/server/transformRequest.ts b/packages/vite/src/node/server/transformRequest.ts index b7bed216348504..79e94cd04c15c0 100644 --- a/packages/vite/src/node/server/transformRequest.ts +++ b/packages/vite/src/node/server/transformRequest.ts @@ -14,7 +14,7 @@ import { isObject, prettifyUrl, removeTimestampQuery, - timeFrom + timeFrom, } from '../utils' import { checkPublicFile } from '../plugins/asset' import { getDepsOptimizer } from '../optimizer' @@ -45,7 +45,7 @@ export interface TransformOptions { export function transformRequest( url: string, server: ViteDevServer, - options: TransformOptions = {} + options: TransformOptions = {}, ): Promise { const cacheKey = (options.ssr ? 'ssr:' : options.html ? 'html:' : '') + url @@ -107,7 +107,7 @@ export function transformRequest( server._pendingRequests.set(cacheKey, { request, timestamp, - abort: clearCache + abort: clearCache, }) request.then(clearCache, clearCache) @@ -118,7 +118,7 @@ async function doTransform( url: string, server: ViteDevServer, options: TransformOptions, - timestamp: number + timestamp: number, ) { url = removeTimestampQuery(url) @@ -158,7 +158,7 @@ async function loadAndTransform( url: string, server: ViteDevServer, options: TransformOptions, - timestamp: number + timestamp: number, ) { const { config, pluginContainer, moduleGraph, watcher } = server const { root, logger } = config @@ -204,7 +204,7 @@ async function loadAndTransform( code = code.replace(convertSourceMap.mapFileCommentRegex, blankReplacer) } catch (e) { logger.warn(`Failed to load source map for ${url}.`, { - timestamp: true + timestamp: true, }) } } @@ -225,7 +225,7 @@ async function loadAndTransform( `imported from source code. It can only be referenced via HTML tags.` : `Does the file exist?` const err: any = new Error( - `Failed to load url ${url} (resolved id: ${id}). ${msg}` + `Failed to load url ${url} (resolved id: ${id}). ${msg}`, ) err.code = isPublicFile ? ERR_LOAD_PUBLIC_URL : ERR_LOAD_URL throw err @@ -238,7 +238,7 @@ async function loadAndTransform( const transformStart = isDebug ? performance.now() : 0 const transformResult = await pluginContainer.transform(code, id, { inMap: map, - ssr + ssr, }) const originalCode = code if ( @@ -248,7 +248,7 @@ async function loadAndTransform( // no transform applied, keep code as-is isDebug && debugTransform( - timeFrom(transformStart) + colors.dim(` [skipped] ${prettyUrl}`) + timeFrom(transformStart) + colors.dim(` [skipped] ${prettyUrl}`), ) } else { isDebug && debugTransform(`${timeFrom(transformStart)} ${prettyUrl}`) @@ -268,7 +268,7 @@ async function loadAndTransform( : ({ code, map, - etag: getEtag(code, { weak: true }) + etag: getEtag(code, { weak: true }), } as TransformResult) // Only cache the result if the module wasn't invalidated while it was diff --git a/packages/vite/src/node/server/ws.ts b/packages/vite/src/node/server/ws.ts index cb8555122b6840..87170d11df8b39 100644 --- a/packages/vite/src/node/server/ws.ts +++ b/packages/vite/src/node/server/ws.ts @@ -16,7 +16,7 @@ export const HMR_HEADER = 'vite-hmr' export type WebSocketCustomListener = ( data: T, - client: WebSocketClient + client: WebSocketClient, ) => void export interface WebSocketServer { @@ -42,7 +42,7 @@ export interface WebSocketServer { on: WebSocketTypes.Server['on'] & { ( event: T, - listener: WebSocketCustomListener> + listener: WebSocketCustomListener>, ): void } /** @@ -74,13 +74,13 @@ const wsServerEvents = [ 'error', 'headers', 'listening', - 'message' + 'message', ] export function createWebSocketServer( server: Server | null, config: ResolvedConfig, - httpsOptions?: HttpsServerOptions + httpsOptions?: HttpsServerOptions, ): WebSocketServer { let wss: WebSocketServerRaw let httpsServer: Server | undefined = undefined @@ -115,12 +115,12 @@ export function createWebSocketServer( const body = STATUS_CODES[statusCode] if (!body) throw new Error( - `No body text found for the ${statusCode} status code` + `No body text found for the ${statusCode} status code`, ) res.writeHead(statusCode, { 'Content-Length': body.length, - 'Content-Type': 'text/plain' + 'Content-Type': 'text/plain', }) res.end(body) }) @@ -163,12 +163,12 @@ export function createWebSocketServer( if (e.code === 'EADDRINUSE') { config.logger.error( colors.red(`WebSocket server error: Port is already in use`), - { error: e } + { error: e }, ) } else { config.logger.error( colors.red(`WebSocket server error:\n${e.stack || e.message}`), - { error: e } + { error: e }, ) } }) @@ -184,14 +184,14 @@ export function createWebSocketServer( payload = { type: 'custom', event: args[0], - data: args[1] + data: args[1], } } else { payload = args[0] } socket.send(JSON.stringify(payload)) }, - socket + socket, }) } return clientsMap.get(socket)! @@ -231,7 +231,7 @@ export function createWebSocketServer( payload = { type: 'custom', event: args[0], - data: args[1] + data: args[1], } } else { payload = args[0] @@ -274,6 +274,6 @@ export function createWebSocketServer( } }) }) - } + }, } } diff --git a/packages/vite/src/node/ssr/__tests__/ssrLoadModule.spec.ts b/packages/vite/src/node/ssr/__tests__/ssrLoadModule.spec.ts index 1df5f2b128da5d..a21b0673e1f36d 100644 --- a/packages/vite/src/node/ssr/__tests__/ssrLoadModule.spec.ts +++ b/packages/vite/src/node/ssr/__tests__/ssrLoadModule.spec.ts @@ -17,7 +17,7 @@ test('ssrLoad', async () => { await server.ssrLoadModule('/fixtures/modules/has-invalid-import.js') } catch (e) { expect(e.message).toBe( - 'Failed to load url ./non-existent.js (resolved id: ./non-existent.js). Does the file exist?' + 'Failed to load url ./non-existent.js (resolved id: ./non-existent.js). Does the file exist?', ) } }) diff --git a/packages/vite/src/node/ssr/__tests__/ssrTransform.spec.ts b/packages/vite/src/node/ssr/__tests__/ssrTransform.spec.ts index 33d5071a054a99..74ff0e5277c135 100644 --- a/packages/vite/src/node/ssr/__tests__/ssrTransform.spec.ts +++ b/packages/vite/src/node/ssr/__tests__/ssrTransform.spec.ts @@ -9,7 +9,7 @@ const ssrTransformSimpleCode = async (code: string, url?: string) => test('default import', async () => { expect( - await ssrTransformSimpleCode(`import foo from 'vue';console.log(foo.bar)`) + await ssrTransformSimpleCode(`import foo from 'vue';console.log(foo.bar)`), ).toMatchInlineSnapshot(` "const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"vue\\"); console.log(__vite_ssr_import_0__.default.bar)" @@ -19,8 +19,8 @@ test('default import', async () => { test('named import', async () => { expect( await ssrTransformSimpleCode( - `import { ref } from 'vue';function foo() { return ref(0) }` - ) + `import { ref } from 'vue';function foo() { return ref(0) }`, + ), ).toMatchInlineSnapshot(` "const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"vue\\"); function foo() { return __vite_ssr_import_0__.ref(0) }" @@ -30,8 +30,8 @@ test('named import', async () => { test('namespace import', async () => { expect( await ssrTransformSimpleCode( - `import * as vue from 'vue';function foo() { return vue.ref(0) }` - ) + `import * as vue from 'vue';function foo() { return vue.ref(0) }`, + ), ).toMatchInlineSnapshot(` "const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"vue\\"); function foo() { return __vite_ssr_import_0__.ref(0) }" @@ -65,7 +65,7 @@ test('export var declaration', async () => { test('export named', async () => { expect( - await ssrTransformSimpleCode(`const a = 1, b = 2; export { a, b as c }`) + await ssrTransformSimpleCode(`const a = 1, b = 2; export { a, b as c }`), ).toMatchInlineSnapshot(` "const a = 1, b = 2; Object.defineProperty(__vite_ssr_exports__, \\"a\\", { enumerable: true, configurable: true, get(){ return a }}); @@ -75,7 +75,7 @@ test('export named', async () => { test('export named from', async () => { expect( - await ssrTransformSimpleCode(`export { ref, computed as c } from 'vue'`) + await ssrTransformSimpleCode(`export { ref, computed as c } from 'vue'`), ).toMatchInlineSnapshot(` "const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"vue\\"); @@ -87,8 +87,8 @@ test('export named from', async () => { test('named exports of imported binding', async () => { expect( await ssrTransformSimpleCode( - `import {createApp} from 'vue';export {createApp}` - ) + `import {createApp} from 'vue';export {createApp}`, + ), ).toMatchInlineSnapshot(` "const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"vue\\"); @@ -99,8 +99,8 @@ test('named exports of imported binding', async () => { test('export * from', async () => { expect( await ssrTransformSimpleCode( - `export * from 'vue'\n` + `export * from 'react'` - ) + `export * from 'vue'\n` + `export * from 'react'`, + ), ).toMatchInlineSnapshot(` "const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"vue\\"); __vite_ssr_exportAll__(__vite_ssr_import_0__); @@ -120,15 +120,15 @@ test('export * as from', async () => { test('export default', async () => { expect( - await ssrTransformSimpleCode(`export default {}`) + await ssrTransformSimpleCode(`export default {}`), ).toMatchInlineSnapshot(`"__vite_ssr_exports__.default = {}"`) }) test('export then import minified', async () => { expect( await ssrTransformSimpleCode( - `export * from 'vue';import {createApp} from 'vue';` - ) + `export * from 'vue';import {createApp} from 'vue';`, + ), ).toMatchInlineSnapshot(` "const __vite_ssr_import_1__ = await __vite_ssr_import__(\\"vue\\"); __vite_ssr_exportAll__(__vite_ssr_import_1__);const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"vue\\"); @@ -138,13 +138,13 @@ test('export then import minified', async () => { test('import.meta', async () => { expect( - await ssrTransformSimpleCode(`console.log(import.meta.url)`) + await ssrTransformSimpleCode(`console.log(import.meta.url)`), ).toMatchInlineSnapshot(`"console.log(__vite_ssr_import_meta__.url)"`) }) test('dynamic import', async () => { const result = await ssrTransformSimple( - `export const i = () => import('./foo')` + `export const i = () => import('./foo')`, ) expect(result?.code).toMatchInlineSnapshot(` "const i = () => __vite_ssr_dynamic_import__('./foo') @@ -156,7 +156,7 @@ test('dynamic import', async () => { test('do not rewrite method definition', async () => { const result = await ssrTransformSimple( - `import { fn } from 'vue';class A { fn() { fn() } }` + `import { fn } from 'vue';class A { fn() { fn() } }`, ) expect(result?.code).toMatchInlineSnapshot(` "const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"vue\\"); @@ -167,7 +167,7 @@ test('do not rewrite method definition', async () => { test('do not rewrite when variable is in scope', async () => { const result = await ssrTransformSimple( - `import { fn } from 'vue';function A(){ const fn = () => {}; return { fn }; }` + `import { fn } from 'vue';function A(){ const fn = () => {}; return { fn }; }`, ) expect(result?.code).toMatchInlineSnapshot(` "const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"vue\\"); @@ -179,7 +179,7 @@ test('do not rewrite when variable is in scope', async () => { // #5472 test('do not rewrite when variable is in scope with object destructuring', async () => { const result = await ssrTransformSimple( - `import { fn } from 'vue';function A(){ let {fn, test} = {fn: 'foo', test: 'bar'}; return { fn }; }` + `import { fn } from 'vue';function A(){ let {fn, test} = {fn: 'foo', test: 'bar'}; return { fn }; }`, ) expect(result?.code).toMatchInlineSnapshot(` "const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"vue\\"); @@ -191,7 +191,7 @@ test('do not rewrite when variable is in scope with object destructuring', async // #5472 test('do not rewrite when variable is in scope with array destructuring', async () => { const result = await ssrTransformSimple( - `import { fn } from 'vue';function A(){ let [fn, test] = ['foo', 'bar']; return { fn }; }` + `import { fn } from 'vue';function A(){ let [fn, test] = ['foo', 'bar']; return { fn }; }`, ) expect(result?.code).toMatchInlineSnapshot(` "const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"vue\\"); @@ -203,7 +203,7 @@ test('do not rewrite when variable is in scope with array destructuring', async // #5727 test('rewrite variable in string interpolation in function nested arguments', async () => { const result = await ssrTransformSimple( - `import { fn } from 'vue';function A({foo = \`test\${fn}\`} = {}){ return {}; }` + `import { fn } from 'vue';function A({foo = \`test\${fn}\`} = {}){ return {}; }`, ) expect(result?.code).toMatchInlineSnapshot(` "const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"vue\\"); @@ -215,7 +215,7 @@ test('rewrite variable in string interpolation in function nested arguments', as // #6520 test('rewrite variables in default value of destructuring params', async () => { const result = await ssrTransformSimple( - `import { fn } from 'vue';function A({foo = fn}){ return {}; }` + `import { fn } from 'vue';function A({foo = fn}){ return {}; }`, ) expect(result?.code).toMatchInlineSnapshot(` "const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"vue\\"); @@ -226,7 +226,7 @@ test('rewrite variables in default value of destructuring params', async () => { test('do not rewrite when function declaration is in scope', async () => { const result = await ssrTransformSimple( - `import { fn } from 'vue';function A(){ function fn() {}; return { fn }; }` + `import { fn } from 'vue';function A(){ function fn() {}; return { fn }; }`, ) expect(result?.code).toMatchInlineSnapshot(` "const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"vue\\"); @@ -237,7 +237,7 @@ test('do not rewrite when function declaration is in scope', async () => { test('do not rewrite catch clause', async () => { const result = await ssrTransformSimple( - `import {error} from './dependency';try {} catch(error) {}` + `import {error} from './dependency';try {} catch(error) {}`, ) expect(result?.code).toMatchInlineSnapshot(` "const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"./dependency\\"); @@ -250,8 +250,8 @@ test('do not rewrite catch clause', async () => { test('should declare variable for imported super class', async () => { expect( await ssrTransformSimpleCode( - `import { Foo } from './dependency';` + `class A extends Foo {}` - ) + `import { Foo } from './dependency';` + `class A extends Foo {}`, + ), ).toMatchInlineSnapshot(` "const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"./dependency\\"); const Foo = __vite_ssr_import_0__.Foo; @@ -264,8 +264,8 @@ test('should declare variable for imported super class', async () => { await ssrTransformSimpleCode( `import { Foo } from './dependency';` + `export default class A extends Foo {}\n` + - `export class B extends Foo {}` - ) + `export class B extends Foo {}`, + ), ).toMatchInlineSnapshot(` "const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"./dependency\\"); const Foo = __vite_ssr_import_0__.Foo; @@ -293,8 +293,9 @@ test('should handle default export variants', async () => { // default named functions expect( await ssrTransformSimpleCode( - `export default function foo() {}\n` + `foo.prototype = Object.prototype;` - ) + `export default function foo() {}\n` + + `foo.prototype = Object.prototype;`, + ), ).toMatchInlineSnapshot(` "function foo() {} foo.prototype = Object.prototype; @@ -303,8 +304,8 @@ test('should handle default export variants', async () => { // default named classes expect( await ssrTransformSimpleCode( - `export default class A {}\n` + `export class B extends A {}` - ) + `export default class A {}\n` + `export class B extends A {}`, + ), ).toMatchInlineSnapshot(` "class A {} class B extends A {} @@ -319,7 +320,7 @@ test('sourcemap source', async () => { `export const a = 1`, null, 'input.js', - 'export const a = 1 /* */' + 'export const a = 1 /* */', ) )?.map expect(map?.sources).toStrictEqual(['input.js']) @@ -336,8 +337,8 @@ test('overwrite bindings', async () => { `const d = inject\n` + `function f() { console.log(inject) }\n` + `function e() { const { inject } = { inject: true } }\n` + - `function g() { const f = () => { const inject = true }; console.log(inject) }\n` - ) + `function g() { const f = () => { const inject = true }; console.log(inject) }\n`, + ), ).toMatchInlineSnapshot(` "const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"vue\\"); const a = { inject: __vite_ssr_import_0__.inject } @@ -353,7 +354,7 @@ test('overwrite bindings', async () => { test('Empty array pattern', async () => { expect( - await ssrTransformSimpleCode(`const [, LHS, RHS] = inMatch;`) + await ssrTransformSimpleCode(`const [, LHS, RHS] = inMatch;`), ).toMatchInlineSnapshot(`"const [, LHS, RHS] = inMatch;"`) }) @@ -365,8 +366,8 @@ import { foo, bar } from 'foo' const a = ({ _ = foo() }) => {} function b({ _ = bar() }) {} function c({ _ = bar() + foo() }) {} -` - ) +`, + ), ).toMatchInlineSnapshot(` " const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"foo\\"); @@ -387,8 +388,8 @@ const a = () => { const { type: n = 'bar' } = {} console.log(n) } -` - ) +`, + ), ).toMatchInlineSnapshot(` " const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"foo\\"); @@ -410,8 +411,8 @@ const foo = {} { const { [n]: m } = foo } -` - ) +`, + ), ).toMatchInlineSnapshot(` " const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"foo\\"); @@ -453,8 +454,8 @@ get() set() rest() objRest() -` - ) +`, + ), ).toMatchInlineSnapshot(` " const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"vue\\"); @@ -503,8 +504,8 @@ const obj = { [bar]: () => {}, bar(foo) {} } -` - ) +`, + ), ).toMatchInlineSnapshot(` " const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"foo\\"); @@ -535,8 +536,8 @@ class A { remove = 1 add = null } -` - ) +`, + ), ).toMatchInlineSnapshot(` " const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"vue\\"); @@ -567,8 +568,8 @@ class A { #foo() {} bar(foo) {} } -` - ) +`, + ), ).toMatchInlineSnapshot(` " const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"foo\\"); @@ -613,8 +614,8 @@ function foobar() { aaa() bbb() -` - ) +`, + ), ).toMatchInlineSnapshot(` " const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"vue\\"); @@ -679,8 +680,8 @@ test('continuous exports', async () => { export function fn1() { }export function fn2() { } - ` - ) + `, + ), ).toMatchInlineSnapshot(` " function fn1() { @@ -711,7 +712,7 @@ export default (function getRandom() { `) expect( - await ssrTransformSimpleCode(`export default (class A {});`) + await ssrTransformSimpleCode(`export default (class A {});`), ).toMatchInlineSnapshot(`"__vite_ssr_exports__.default = (class A {});"`) }) @@ -720,8 +721,8 @@ test('with hashbang', async () => { expect( await ssrTransformSimpleCode( `#!/usr/bin/env node -console.log("it can parse the hashbang")` - ) +console.log("it can parse the hashbang")`, + ), ).toMatchInlineSnapshot(` "#!/usr/bin/env node console.log(\\"it can parse the hashbang\\")" @@ -798,7 +799,7 @@ function test() { var foo = () => { var why = 'would' }, bar = 'someone' } return [foo, bar] -}`) +}`), ).toMatchInlineSnapshot(` " const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"foobar\\"); diff --git a/packages/vite/src/node/ssr/index.ts b/packages/vite/src/node/ssr/index.ts index d23e78b18cae5f..cdd9e9e5dd24b0 100644 --- a/packages/vite/src/node/ssr/index.ts +++ b/packages/vite/src/node/ssr/index.ts @@ -42,7 +42,7 @@ export interface ResolvedSSROptions extends SSROptions { export function resolveSSROptions( ssr: SSROptions | undefined, preserveSymlinks: boolean, - buildSsrCjsExternalHeuristics?: boolean + buildSsrCjsExternalHeuristics?: boolean, ): ResolvedSSROptions { ssr ??= {} const optimizeDeps = ssr.optimizeDeps ?? {} @@ -65,8 +65,8 @@ export function resolveSSROptions( ...optimizeDeps, esbuildOptions: { preserveSymlinks, - ...optimizeDeps.esbuildOptions - } - } + ...optimizeDeps.esbuildOptions, + }, + }, } } diff --git a/packages/vite/src/node/ssr/ssrExternal.ts b/packages/vite/src/node/ssr/ssrExternal.ts index 9281c8ebebc9b8..ce08b020d17fbf 100644 --- a/packages/vite/src/node/ssr/ssrExternal.ts +++ b/packages/vite/src/node/ssr/ssrExternal.ts @@ -11,7 +11,7 @@ import { isDefined, lookupFile, normalizePath, - resolveFrom + resolveFrom, } from '../utils' import type { Logger, ResolvedConfig } from '..' @@ -33,7 +33,7 @@ export function stripNesting(packages: string[]): string[] { */ export function cjsSsrResolveExternals( config: ResolvedConfig, - knownImports: string[] + knownImports: string[], ): string[] { // strip nesting since knownImports may be passed in from optimizeDeps which // supports a "parent > child" syntax @@ -56,7 +56,7 @@ export function cjsSsrResolveExternals( config.resolve, ssrExternals, seen, - config.logger + config.logger, ) const importedDeps = knownImports.map(getNpmPackageName).filter(isDefined) @@ -76,7 +76,7 @@ export function cjsSsrResolveExternals( let externals = [...ssrExternals] if (ssrConfig?.noExternal) { externals = externals.filter( - createFilter(undefined, ssrConfig.noExternal, { resolve: false }) + createFilter(undefined, ssrConfig.noExternal, { resolve: false }), ) } return externals @@ -95,7 +95,7 @@ const isSsrExternalCache = new WeakMap< export function shouldExternalizeForSSR( id: string, - config: ResolvedConfig + config: ResolvedConfig, ): boolean | undefined { let isSsrExternal = isSsrExternalCache.get(config) if (!isSsrExternal) { @@ -106,7 +106,7 @@ export function shouldExternalizeForSSR( } export function createIsConfiguredAsSsrExternal( - config: ResolvedConfig + config: ResolvedConfig, ): (id: string) => boolean { const { ssr, root } = config const noExternal = ssr?.noExternal @@ -119,12 +119,12 @@ export function createIsConfiguredAsSsrExternal( ...config.resolve, root, isProduction: false, - isBuild: true + isBuild: true, } const isExternalizable = ( id: string, - configuredAsExternal?: boolean + configuredAsExternal?: boolean, ): boolean => { if (!bareImportRE.test(id) || id.includes('\0')) { return false @@ -142,11 +142,11 @@ export function createIsConfiguredAsSsrExternal( true, // Allow linked packages to be externalized if they are explicitly // configured as external - !!configuredAsExternal + !!configuredAsExternal, )?.external } catch (e) { debug( - `Failed to node resolve "${id}". Skipping externalizing it by default.` + `Failed to node resolve "${id}". Skipping externalizing it by default.`, ) // may be an invalid import that's resolved by a plugin return false @@ -188,7 +188,7 @@ export function createIsConfiguredAsSsrExternal( } function createIsSsrExternal( - config: ResolvedConfig + config: ResolvedConfig, ): (id: string) => boolean | undefined { const processedIds = new Map() @@ -214,7 +214,7 @@ function cjsSsrCollectExternals( resolveOptions: Required, ssrExternals: Set, seen: Set, - logger: Logger + logger: Logger, ) { const rootPkgContent = lookupFile(root, ['package.json']) if (!rootPkgContent) { @@ -224,14 +224,14 @@ function cjsSsrCollectExternals( const rootPkg = JSON.parse(rootPkgContent) const deps = { ...rootPkg.devDependencies, - ...rootPkg.dependencies + ...rootPkg.dependencies, } const internalResolveOptions: InternalResolveOptions = { ...resolveOptions, root, isProduction: false, - isBuild: true + isBuild: true, } const depsToTrace = new Set() @@ -250,7 +250,7 @@ function cjsSsrCollectExternals( internalResolveOptions, true, // we set `targetWeb` to `true` to get the ESM entry undefined, - true + true, )?.id // normalizePath required for windows. tryNodeResolve uses normalizePath // which returns with '/', require.resolve returns with '\\' @@ -308,7 +308,7 @@ function cjsSsrCollectExternals( } logger.warn( - `${id} doesn't appear to be written in CJS, but also doesn't appear to be a valid ES module (i.e. it doesn't have "type": "module" or an .mjs extension for the entry point). Please contact the package author to fix.` + `${id} doesn't appear to be written in CJS, but also doesn't appear to be a valid ES module (i.e. it doesn't have "type": "module" or an .mjs extension for the entry point). Please contact the package author to fix.`, ) } } @@ -320,7 +320,7 @@ function cjsSsrCollectExternals( export function cjsShouldExternalizeForSSR( id: string, - externals: string[] | null + externals: string[] | null, ): boolean { if (!externals) { return false diff --git a/packages/vite/src/node/ssr/ssrManifestPlugin.ts b/packages/vite/src/node/ssr/ssrManifestPlugin.ts index 9a68b5ea22afe5..182a5eb67b8067 100644 --- a/packages/vite/src/node/ssr/ssrManifestPlugin.ts +++ b/packages/vite/src/node/ssr/ssrManifestPlugin.ts @@ -65,7 +65,7 @@ export function ssrManifestPlugin(config: ResolvedConfig): Plugin { } } const normalizedFile = normalizePath( - join(dirname(chunk.fileName), url.slice(1, -1)) + join(dirname(chunk.fileName), url.slice(1, -1)), ) addDeps(normalizedFile) ssrManifest[basename(name!)] = deps @@ -81,8 +81,8 @@ export function ssrManifestPlugin(config: ResolvedConfig): Plugin { ? config.build.ssrManifest : 'ssr-manifest.json', type: 'asset', - source: JSON.stringify(ssrManifest, null, 2) + source: JSON.stringify(ssrManifest, null, 2), }) - } + }, } } diff --git a/packages/vite/src/node/ssr/ssrModuleLoader.ts b/packages/vite/src/node/ssr/ssrModuleLoader.ts index 84b05ac7841973..9c9916ca616564 100644 --- a/packages/vite/src/node/ssr/ssrModuleLoader.ts +++ b/packages/vite/src/node/ssr/ssrModuleLoader.ts @@ -5,7 +5,7 @@ import { dynamicImport, isBuiltin, unwrapId, - usingDynamicImport + usingDynamicImport, } from '../utils' import { transformRequest } from '../server/transformRequest' import type { InternalResolveOptions } from '../plugins/resolve' @@ -15,7 +15,7 @@ import { ssrExportAllKey, ssrImportKey, ssrImportMetaKey, - ssrModuleExportsKey + ssrModuleExportsKey, } from './ssrTransform' import { rebindErrorStacktrace, ssrRewriteStacktrace } from './ssrStacktrace' @@ -33,7 +33,7 @@ export async function ssrLoadModule( server: ViteDevServer, context: SSRContext = { global }, urlStack: string[] = [], - fixStacktrace?: boolean + fixStacktrace?: boolean, ): Promise { url = unwrapId(url) @@ -51,7 +51,7 @@ export async function ssrLoadModule( server, context, urlStack, - fixStacktrace + fixStacktrace, ) pendingModules.set(url, modulePromise) modulePromise @@ -69,7 +69,7 @@ async function instantiateModule( server: ViteDevServer, context: SSRContext = { global }, urlStack: string[] = [], - fixStacktrace?: boolean + fixStacktrace?: boolean, ): Promise { const { moduleGraph } = server const mod = await moduleGraph.ensureEntryFromUrl(url, true) @@ -90,7 +90,7 @@ async function instantiateModule( } const ssrModule = { - [Symbol.toStringTag]: 'Module' + [Symbol.toStringTag]: 'Module', } Object.defineProperty(ssrModule, '__esModule', { value: true }) @@ -100,7 +100,7 @@ async function instantiateModule( const ssrImportMeta = { // The filesystem URL, matching native Node.js modules - url: pathToFileURL(mod.file!).toString() + url: pathToFileURL(mod.file!).toString(), } urlStack = urlStack.concat(url) @@ -109,7 +109,7 @@ async function instantiateModule( const { isProduction, resolve: { dedupe, preserveSymlinks }, - root + root, } = server.config const resolveOptions: InternalResolveOptions = { @@ -121,7 +121,7 @@ async function instantiateModule( preserveSymlinks, isBuild: false, isProduction, - root + root, } // Since dynamic imports can happen in parallel, we need to @@ -144,7 +144,7 @@ async function instantiateModule( server, context, urlStack, - fixStacktrace + fixStacktrace, ) if (pendingDeps.length === 1) { pendingImports.delete(url) @@ -174,7 +174,7 @@ async function instantiateModule( configurable: true, get() { return sourceModule[key] - } + }, }) } } @@ -190,7 +190,7 @@ async function instantiateModule( ssrImportKey, ssrDynamicImportKey, ssrExportAllKey, - '"use strict";' + result.code + `\n//# sourceURL=${mod.url}` + '"use strict";' + result.code + `\n//# sourceURL=${mod.url}`, ) await initModule( context.global, @@ -198,7 +198,7 @@ async function instantiateModule( ssrImportMeta, ssrImport, ssrDynamicImport, - ssrExportAll + ssrExportAll, ) } catch (e) { mod.ssrError = e @@ -210,8 +210,8 @@ async function instantiateModule( { timestamp: true, clear: server.config.clearScreen, - error: e - } + error: e, + }, ) } throw e @@ -224,7 +224,7 @@ async function instantiateModule( async function nodeImport( id: string, importer: string, - resolveOptions: InternalResolveOptions + resolveOptions: InternalResolveOptions, ) { let url: string if (id.startsWith('node:') || isBuiltin(id)) { @@ -239,11 +239,11 @@ async function nodeImport( typeof jest === 'undefined' ? { ...resolveOptions, tryEsmOnly: true } : resolveOptions, - false + false, ) if (!resolved) { const err: any = new Error( - `Cannot find module '${id}' imported from '${importer}'` + `Cannot find module '${id}' imported from '${importer}'`, ) err.code = 'ERR_MODULE_NOT_FOUND' throw err @@ -278,7 +278,7 @@ function proxyESM(mod: any) { get(mod, prop) { if (prop === 'default') return defaultExport return mod[prop] ?? defaultExport?.[prop] - } + }, }) } diff --git a/packages/vite/src/node/ssr/ssrStacktrace.ts b/packages/vite/src/node/ssr/ssrStacktrace.ts index 2d71fada82065f..cad1bd17e0422e 100644 --- a/packages/vite/src/node/ssr/ssrStacktrace.ts +++ b/packages/vite/src/node/ssr/ssrStacktrace.ts @@ -14,7 +14,7 @@ try { export function ssrRewriteStacktrace( stack: string, - moduleGraph: ModuleGraph + moduleGraph: ModuleGraph, ): string { return stack .split('\n') @@ -35,7 +35,7 @@ export function ssrRewriteStacktrace( const pos = originalPositionFor(traced, { line: Number(line) - offset, - column: Number(column) + column: Number(column), }) if (!pos.source || pos.line == null || pos.column == null) { @@ -49,7 +49,7 @@ export function ssrRewriteStacktrace( } else { return ` at ${trimedVarName} (${source})` } - } + }, ) }) .join('\n') @@ -58,14 +58,14 @@ export function ssrRewriteStacktrace( export function rebindErrorStacktrace(e: Error, stacktrace: string): void { const { configurable, writable } = Object.getOwnPropertyDescriptor( e, - 'stack' + 'stack', )! if (configurable) { Object.defineProperty(e, 'stack', { value: stacktrace, enumerable: true, configurable: true, - writable: true + writable: true, }) } else if (writable) { e.stack = stacktrace diff --git a/packages/vite/src/node/ssr/ssrTransform.ts b/packages/vite/src/node/ssr/ssrTransform.ts index eefdf29f70d7a1..b963494b7ab0b0 100644 --- a/packages/vite/src/node/ssr/ssrTransform.ts +++ b/packages/vite/src/node/ssr/ssrTransform.ts @@ -6,7 +6,7 @@ import type { Pattern, Property, VariableDeclaration, - Node as _Node + Node as _Node, } from 'estree' import { extract_names as extractNames } from 'periscopic' // `eslint-plugin-node` doesn't support package without main @@ -40,7 +40,7 @@ export async function ssrTransform( inMap: SourceMap | null, url: string, originalCode: string, - options?: TransformOptions + options?: TransformOptions, ): Promise { if (options?.json?.stringify && isJSONRequest(url)) { return ssrTransformJSON(code, inMap) @@ -50,13 +50,13 @@ export async function ssrTransform( async function ssrTransformJSON( code: string, - inMap: SourceMap | null + inMap: SourceMap | null, ): Promise { return { code: code.replace('export default', `${ssrModuleExportsKey}.default =`), map: inMap, deps: [], - dynamicDeps: [] + dynamicDeps: [], } } @@ -64,7 +64,7 @@ async function ssrTransformScript( code: string, inMap: SourceMap | null, url: string, - originalCode: string + originalCode: string, ): Promise { const s = new MagicString(code) @@ -74,7 +74,7 @@ async function ssrTransformScript( sourceType: 'module', ecmaVersion: 'latest', locations: true, - allowHashBang: true + allowHashBang: true, }) } catch (err) { if (!err.loc || !err.loc.line) throw err @@ -82,7 +82,7 @@ async function ssrTransformScript( throw new Error( `Parse failure: ${err.message}\nContents of line ${line}: ${ code.split('\n')[line - 1] - }` + }`, ) } @@ -97,7 +97,7 @@ async function ssrTransformScript( const importId = `__vite_ssr_import_${uid++}__` s.appendRight( node.start, - `const ${importId} = await ${ssrImportKey}(${JSON.stringify(source)});\n` + `const ${importId} = await ${ssrImportKey}(${JSON.stringify(source)});\n`, ) return importId } @@ -106,7 +106,7 @@ async function ssrTransformScript( s.appendLeft( position, `\nObject.defineProperty(${ssrModuleExportsKey}, "${name}", ` + - `{ enumerable: true, configurable: true, get(){ return ${local} }});` + `{ enumerable: true, configurable: true, get(){ return ${local} }});`, ) } @@ -122,7 +122,7 @@ async function ssrTransformScript( if (spec.type === 'ImportSpecifier') { idToImportMap.set( spec.local.name, - `${importId}.${spec.imported.name}` + `${importId}.${spec.imported.name}`, ) } else if (spec.type === 'ImportDefaultSpecifier') { idToImportMap.set(spec.local.name, `${importId}.default`) @@ -164,7 +164,7 @@ async function ssrTransformScript( defineExport( node.end, spec.exported.name, - `${importId}.${spec.local.name}` + `${importId}.${spec.local.name}`, ) } } else { @@ -193,14 +193,14 @@ async function ssrTransformScript( s.remove(node.start, node.start + 15 /* 'export default '.length */) s.append( `\nObject.defineProperty(${ssrModuleExportsKey}, "default", ` + - `{ enumerable: true, configurable: true, value: ${name} });` + `{ enumerable: true, configurable: true, value: ${name} });`, ) } else { // anonymous default exports s.update( node.start, node.start + 14 /* 'export default'.length */, - `${ssrModuleExportsKey}.default =` + `${ssrModuleExportsKey}.default =`, ) } } @@ -258,7 +258,7 @@ async function ssrTransformScript( if (node.type === 'ImportExpression' && node.source.type === 'Literal') { dynamicDeps.add(node.source.value as string) } - } + }, }) let map = s.generateMap({ hires: true }) @@ -269,11 +269,11 @@ async function ssrTransformScript( { ...map, sources: inMap.sources, - sourcesContent: inMap.sourcesContent + sourcesContent: inMap.sourcesContent, } as RawSourceMap, - inMap as RawSourceMap + inMap as RawSourceMap, ], - false + false, ) as SourceMap } else { map.sources = [url] @@ -286,7 +286,7 @@ async function ssrTransformScript( code: s.toString(), map, deps: [...deps], - dynamicDeps: [...dynamicDeps] + dynamicDeps: [...dynamicDeps], } } @@ -297,7 +297,7 @@ interface Visitors { end: number }, parent: Node, - parentStack: Node[] + parentStack: Node[], ) => void onImportMeta: (node: Node) => void onDynamicImport: (node: Node) => void @@ -314,7 +314,7 @@ const isNodeInPattern = (node: _Node): node is Property => */ function walk( root: Node, - { onIdentifier, onImportMeta, onDynamicImport }: Visitors + { onIdentifier, onImportMeta, onDynamicImport }: Visitors, ) { const parentStack: Node[] = [] const varKindStack: VariableDeclaration['kind'][] = [] @@ -434,7 +434,7 @@ function walk( return } setScope(node, child.name) - } + }, }) }) } else if (node.type === 'Property' && parent!.type === 'ObjectPattern') { @@ -443,7 +443,7 @@ function walk( } else if (node.type === 'VariableDeclarator') { const parentFunction = findParentScope( parentStack, - varKindStack[0] === 'var' + varKindStack[0] === 'var', ) if (parentFunction) { handlePattern(node.id, parentFunction) @@ -463,7 +463,7 @@ function walk( if (node.type === 'VariableDeclaration') { varKindStack.shift() } - } + }, }) // emit the identifier events in BFS so the hoisted declarations @@ -554,7 +554,7 @@ const scopeNodeTypeRE = /(?:Function|Class)(?:Expression|Declaration)$|Method$|^IfStatement$/ function findParentScope( parentStack: _Node[], - isVar = false + isVar = false, ): _Node | undefined { const regex = isVar ? functionNodeTypeRE : scopeNodeTypeRE return parentStack.find((i) => regex.test(i.type)) @@ -562,7 +562,7 @@ function findParentScope( function isInDestructuringAssignment( parent: _Node, - parentStack: _Node[] + parentStack: _Node[], ): boolean { if ( parent && diff --git a/packages/vite/src/node/utils.ts b/packages/vite/src/node/utils.ts index f288cffd8effac..c500462fd56671 100644 --- a/packages/vite/src/node/utils.ts +++ b/packages/vite/src/node/utils.ts @@ -29,7 +29,7 @@ import { OPTIMIZABLE_ENTRY_RE, VALID_ID_PREFIX, loopbackHosts, - wildcardHosts + wildcardHosts, } from './constants' import type { DepOptimizationConfig } from './optimizer' import type { ResolvedConfig } from './config' @@ -47,7 +47,7 @@ export type FilterPattern = export const createFilter = _createFilter as ( include?: FilterPattern, exclude?: FilterPattern, - options?: { resolve?: string | false | null } + options?: { resolve?: string | false | null }, ) => (id: string | unknown) => boolean export function slash(p: string): string { @@ -98,7 +98,7 @@ const builtins = new Set([ 'stream/web', 'timers/promises', 'util/types', - 'wasi' + 'wasi', ]) export function isBuiltin(id: string): boolean { @@ -107,14 +107,14 @@ export function isBuiltin(id: string): boolean { export function moduleListContains( moduleList: string[] | undefined, - id: string + id: string, ): boolean | undefined { return moduleList?.some((m) => m === id || id.startsWith(m + '/')) } export function isOptimizable( id: string, - optimizeDeps: DepOptimizationConfig + optimizeDeps: DepOptimizationConfig, ): boolean { const { extensions } = optimizeDeps return ( @@ -141,14 +141,14 @@ export function resolveFrom( id: string, basedir: string, preserveSymlinks = false, - ssr = false + ssr = false, ): string { return resolve.sync(id, { basedir, paths: [], extensions: ssr ? ssrExtensions : DEFAULT_EXTENSIONS, // necessary to work with pnpm - preserveSymlinks: preserveSymlinks || isRunningWithYarnPnp || false + preserveSymlinks: preserveSymlinks || isRunningWithYarnPnp || false, }) } @@ -159,7 +159,7 @@ export function resolveFrom( export function nestedResolveFrom( id: string, basedir: string, - preserveSymlinks = false + preserveSymlinks = false, ): string { const pkgs = id.split('>').map((pkg) => pkg.trim()) try { @@ -183,7 +183,7 @@ export type ViteDebugScope = `vite:${string}` export function createDebugger( namespace: ViteDebugScope, - options: DebuggerOptions = {} + options: DebuggerOptions = {}, ): debug.Debugger['log'] { const log = debug(namespace) const { onlyWhenFocused } = options @@ -203,13 +203,13 @@ export function createDebugger( function testCaseInsensitiveFS() { if (!CLIENT_ENTRY.endsWith('client.mjs')) { throw new Error( - `cannot test case insensitive FS, CLIENT_ENTRY const doesn't contain client.mjs` + `cannot test case insensitive FS, CLIENT_ENTRY const doesn't contain client.mjs`, ) } if (!fs.existsSync(CLIENT_ENTRY)) { throw new Error( 'cannot test case insensitive FS, CLIENT_ENTRY does not point to an existing file: ' + - CLIENT_ENTRY + CLIENT_ENTRY, ) } return fs.existsSync(CLIENT_ENTRY.replace('client.mjs', 'cLiEnT.mjs')) @@ -227,7 +227,7 @@ export function normalizePath(id: string): string { export function fsPathFromId(id: string): string { const fsPath = normalizePath( - id.startsWith(FS_PREFIX) ? id.slice(FS_PREFIX.length) : id + id.startsWith(FS_PREFIX) ? id.slice(FS_PREFIX.length) : id, ) return fsPath.startsWith('/') || fsPath.match(VOLUME_RE) ? fsPath @@ -308,7 +308,7 @@ const internalPrefixes = [ FS_PREFIX, VALID_ID_PREFIX, CLIENT_PUBLIC_PATH, - ENV_PUBLIC_PATH + ENV_PUBLIC_PATH, ] const InternalPrefixRE = new RegExp(`^(?:${internalPrefixes.join('|')})`) const trailingSeparatorRE = /[?&]$/ @@ -343,7 +343,7 @@ export function removeTimestampQuery(url: string): string { export async function asyncReplace( input: string, re: RegExp, - replacer: (match: RegExpExecArray) => string | Promise + replacer: (match: RegExpExecArray) => string | Promise, ): Promise { let match: RegExpExecArray | null let remaining = input @@ -410,7 +410,7 @@ interface LookupFileOptions { export function lookupFile( dir: string, formats: string[], - options?: LookupFileOptions + options?: LookupFileOptions, ): string | undefined { for (const format of formats) { const fullPath = path.join(dir, format) @@ -443,7 +443,7 @@ export function pad(source: string, n = 2): string { export function posToNumber( source: string, - pos: number | { line: number; column: number } + pos: number | { line: number; column: number }, ): number { if (typeof pos === 'number') return pos const lines = source.split(splitRE) @@ -457,12 +457,12 @@ export function posToNumber( export function numberToPos( source: string, - offset: number | { line: number; column: number } + offset: number | { line: number; column: number }, ): { line: number; column: number } { if (typeof offset !== 'number') return offset if (offset > source.length) { throw new Error( - `offset is longer than source length! offset ${offset} > length ${source.length}` + `offset is longer than source length! offset ${offset} > length ${source.length}`, ) } const lines = source.split(splitRE) @@ -483,7 +483,7 @@ export function numberToPos( export function generateCodeFrame( source: string, start: number | { line: number; column: number } = 0, - end?: number + end?: number, ): string { start = posToNumber(source, start) end = end || start @@ -499,7 +499,7 @@ export function generateCodeFrame( res.push( `${line}${' '.repeat(Math.max(3 - String(line).length, 0))}| ${ lines[j] - }` + }`, ) const lineLength = lines[j].length if (j === i) { @@ -507,7 +507,7 @@ export function generateCodeFrame( const pad = Math.max(start - (count - lineLength) + 1, 0) const length = Math.max( 1, - end > count ? lineLength - pad : end - start + end > count ? lineLength - pad : end - start, ) res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length)) } else if (j > i) { @@ -526,7 +526,7 @@ export function generateCodeFrame( export function writeFile( filename: string, - content: string | Uint8Array + content: string | Uint8Array, ): void { const dir = path.dirname(filename) if (!fs.existsSync(dir)) { @@ -613,7 +613,7 @@ export const renameDir = isWindows ? promisify(gracefulRename) : fs.renameSync export function ensureWatchedFile( watcher: FSWatcher, file: string | null, - root: string + root: string, ): void { if ( file && @@ -650,7 +650,7 @@ function splitSrcSetDescriptor(srcs: string): ImageCandidate[] { return { url, - descriptor: src?.slice(url.length).trim() + descriptor: src?.slice(url.length).trim(), } }) .filter(({ url }) => !!url) @@ -658,25 +658,25 @@ function splitSrcSetDescriptor(srcs: string): ImageCandidate[] { export function processSrcSet( srcs: string, - replacer: (arg: ImageCandidate) => Promise + replacer: (arg: ImageCandidate) => Promise, ): Promise { return Promise.all( splitSrcSetDescriptor(srcs).map(async ({ url, descriptor }) => ({ url: await replacer({ url, descriptor }), - descriptor - })) + descriptor, + })), ).then((ret) => reduceSrcset(ret)) } export function processSrcSetSync( srcs: string, - replacer: (arg: ImageCandidate) => string + replacer: (arg: ImageCandidate) => string, ): string { return reduceSrcset( splitSrcSetDescriptor(srcs).map(({ url, descriptor }) => ({ url: replacer({ url, descriptor }), - descriptor - })) + descriptor, + })), ) } @@ -685,14 +685,14 @@ function splitSrcSet(srcs: string) { // There could be a ',' inside of url(data:...), linear-gradient(...) or "data:..." const cleanedSrcs = srcs.replace( /(?:url|image|gradient|cross-fade)\([^)]*\)|"([^"]|(?<=\\)")*"|'([^']|(?<=\\)')*'/g, - blankReplacer + blankReplacer, ) let startIndex = 0 let splitIndex: number do { splitIndex = cleanedSrcs.indexOf(',', startIndex) parts.push( - srcs.slice(startIndex, splitIndex !== -1 ? splitIndex : undefined) + srcs.slice(startIndex, splitIndex !== -1 ? splitIndex : undefined), ) startIndex = splitIndex + 1 } while (splitIndex !== -1) @@ -724,12 +724,12 @@ const nullSourceMap: RawSourceMap = { names: [], sources: [], mappings: '', - version: 3 + version: 3, } export function combineSourcemaps( filename: string, sourcemapList: Array, - excludeContent = true + excludeContent = true, ): RawSourceMap { if ( sourcemapList.length === 0 || @@ -744,7 +744,7 @@ export function combineSourcemaps( sourcemapList = sourcemapList.map((sourcemap) => { const newSourcemaps = { ...sourcemap } newSourcemaps.sources = sourcemap.sources.map((source) => - source ? escapeToLinuxLikePath(source) : null + source ? escapeToLinuxLikePath(source) : null, ) if (sourcemap.sourceRoot) { newSourcemaps.sourceRoot = escapeToLinuxLikePath(sourcemap.sourceRoot) @@ -770,7 +770,7 @@ export function combineSourcemaps( return null } }, - excludeContent + excludeContent, ) } if (!map.file) { @@ -779,7 +779,7 @@ export function combineSourcemaps( // unescape the previous hack map.sources = map.sources.map((source) => - source ? unescapeToLinuxLikePath(source) : source + source ? unescapeToLinuxLikePath(source) : source, ) map.file = filename @@ -802,7 +802,7 @@ export async function getLocalhostAddressIfDiffersFromDNS(): Promise< > { const [nodeResult, dnsResult] = await Promise.all([ dns.lookup('localhost'), - dns.lookup('localhost', { verbatim: true }) + dns.lookup('localhost', { verbatim: true }), ]) const isSame = nodeResult.family === dnsResult.family && @@ -818,7 +818,7 @@ export interface Hostname { } export async function resolveHostname( - optionsHost: string | boolean | undefined + optionsHost: string | boolean | undefined, ): Promise { let host: string | undefined if (optionsHost === undefined || optionsHost === false) { @@ -848,7 +848,7 @@ export async function resolveHostname( export async function resolveServerUrls( server: Server, options: CommonServerOptions, - config: ResolvedConfig + config: ResolvedConfig, ): Promise { const address = server.address() @@ -884,7 +884,7 @@ export async function resolveServerUrls( // Node < v18 ((typeof detail.family === 'string' && detail.family === 'IPv4') || // Node >= v18 - (typeof detail.family === 'number' && detail.family === 4)) + (typeof detail.family === 'number' && detail.family === 4)), ) .forEach((detail) => { const host = detail.address.replace('127.0.0.1', hostname.name) @@ -944,7 +944,7 @@ export function getHash(text: Buffer | string): string { export const requireResolveFromRootWithFallback = ( root: string, - id: string + id: string, ): string => { const paths = _require.resolve.paths?.(id) || [] // Search in the root directory first, and fallback to the default require paths. @@ -974,7 +974,7 @@ const GRACEFUL_RENAME_TIMEOUT = 5000 function gracefulRename( from: string, to: string, - cb: (error: NodeJS.ErrnoException | null) => void + cb: (error: NodeJS.ErrnoException | null) => void, ) { const start = Date.now() let backoff = 0 @@ -1000,7 +1000,7 @@ function gracefulRename( const GRACEFUL_REMOVE_DIR_TIMEOUT = 5000 function gracefulRemoveDir( dir: string, - cb: (error: NodeJS.ErrnoException | null) => void + cb: (error: NodeJS.ErrnoException | null) => void, ) { const start = Date.now() let backoff = 0 @@ -1039,7 +1039,7 @@ export function removeComments(raw: string): string { function mergeConfigRecursively( defaults: Record, overrides: Record, - rootPath: string + rootPath: string, ) { const merged: Record = { ...defaults } for (const key in overrides) { @@ -1079,7 +1079,7 @@ function mergeConfigRecursively( merged[key] = mergeConfigRecursively( existing, value, - rootPath ? `${rootPath}.${key}` : key + rootPath ? `${rootPath}.${key}` : key, ) continue } @@ -1092,14 +1092,14 @@ function mergeConfigRecursively( export function mergeConfig( defaults: Record, overrides: Record, - isRoot = true + isRoot = true, ): Record { return mergeConfigRecursively(defaults, overrides, isRoot ? '' : '.') } export function mergeAlias( a?: AliasOptions, - b?: AliasOptions + b?: AliasOptions, ): AliasOptions | undefined { if (!a) return b if (!b) return a @@ -1117,8 +1117,8 @@ export function normalizeAlias(o: AliasOptions = []): Alias[] { : Object.keys(o).map((find) => normalizeSingleAlias({ find, - replacement: (o as any)[find] - }) + replacement: (o as any)[find], + }), ) } @@ -1127,7 +1127,7 @@ export function normalizeAlias(o: AliasOptions = []): Alias[] { function normalizeSingleAlias({ find, replacement, - customResolver + customResolver, }: Alias): Alias { if ( typeof find === 'string' && @@ -1140,7 +1140,7 @@ function normalizeSingleAlias({ const alias: Alias = { find, - replacement + replacement, } if (customResolver) { alias.customResolver = customResolver @@ -1155,14 +1155,14 @@ function normalizeSingleAlias({ export function transformStableResult( s: MagicString, id: string, - config: ResolvedConfig + config: ResolvedConfig, ): TransformResult { return { code: s.toString(), map: config.command === 'build' && config.build.sourcemap ? s.generateMap({ hires: true, source: id }) - : null + : null, } } @@ -1204,8 +1204,8 @@ export function shouldServe(url: string, assetsDir: string): boolean { const pathname = decodeURI( new URL( url.startsWith('//') ? url.substring(1) : url, - 'http://example.com' - ).pathname + 'http://example.com', + ).pathname, ) const file = path.join(assetsDir, pathname) if ( diff --git a/packages/vite/src/node/watch.ts b/packages/vite/src/node/watch.ts index 5b3332da2d3d1f..fa2a97fe1abff3 100644 --- a/packages/vite/src/node/watch.ts +++ b/packages/vite/src/node/watch.ts @@ -4,7 +4,7 @@ import type { ResolvedConfig } from '.' export function resolveChokidarOptions( config: ResolvedConfig, - options: WatchOptions | undefined + options: WatchOptions | undefined, ): WatchOptions { const { ignored = [], ...otherOptions } = options ?? {} @@ -14,11 +14,11 @@ export function resolveChokidarOptions( '**/node_modules/**', '**/test-results/**', // Playwright escapePath(config.cacheDir) + '/**', - ...(Array.isArray(ignored) ? ignored : [ignored]) + ...(Array.isArray(ignored) ? ignored : [ignored]), ], ignoreInitial: true, ignorePermissionErrors: true, - ...otherOptions + ...otherOptions, } return resolvedWatchOptions diff --git a/packages/vite/src/types/chokidar.d.ts b/packages/vite/src/types/chokidar.d.ts index 0dc4bec1013643..83f96ed952024f 100644 --- a/packages/vite/src/types/chokidar.d.ts +++ b/packages/vite/src/types/chokidar.d.ts @@ -69,7 +69,7 @@ export class FSWatcher extends EventEmitter implements fs.FSWatcher { on( event: 'add' | 'addDir' | 'change', - listener: (path: string, stats?: fs.Stats) => void + listener: (path: string, stats?: fs.Stats) => void, ): this on( @@ -77,8 +77,8 @@ export class FSWatcher extends EventEmitter implements fs.FSWatcher { listener: ( eventName: 'add' | 'addDir' | 'change' | 'unlink' | 'unlinkDir', path: string, - stats?: fs.Stats - ) => void + stats?: fs.Stats, + ) => void, ): this /** @@ -91,7 +91,7 @@ export class FSWatcher extends EventEmitter implements fs.FSWatcher { */ on( event: 'raw', - listener: (eventName: string, path: string, details: any) => void + listener: (eventName: string, path: string, details: any) => void, ): this /** @@ -225,5 +225,5 @@ export interface AwaitWriteFinishOptions { */ export function watch( paths: string | ReadonlyArray, - options?: WatchOptions + options?: WatchOptions, ): FSWatcher diff --git a/packages/vite/src/types/connect.d.ts b/packages/vite/src/types/connect.d.ts index 74c559b6a436f5..9589d6a683119d 100644 --- a/packages/vite/src/types/connect.d.ts +++ b/packages/vite/src/types/connect.d.ts @@ -21,18 +21,18 @@ export namespace Connect { export type SimpleHandleFunction = ( req: IncomingMessage, - res: http.ServerResponse + res: http.ServerResponse, ) => void export type NextHandleFunction = ( req: IncomingMessage, res: http.ServerResponse, - next: NextFunction + next: NextFunction, ) => void export type ErrorHandleFunction = ( err: any, req: IncomingMessage, res: http.ServerResponse, - next: NextFunction + next: NextFunction, ) => void export type HandleFunction = | SimpleHandleFunction @@ -73,7 +73,7 @@ export namespace Connect { handle( req: http.IncomingMessage, res: http.ServerResponse, - next: Function + next: Function, ): void /** @@ -102,7 +102,7 @@ export namespace Connect { port: number, hostname?: string, backlog?: number, - callback?: Function + callback?: Function, ): http.Server listen(port: number, hostname?: string, callback?: Function): http.Server listen(path: string, callback?: Function): http.Server diff --git a/packages/vite/src/types/http-proxy.d.ts b/packages/vite/src/types/http-proxy.d.ts index 1cae820dcdfa8f..ad3ae1eec4a3c8 100644 --- a/packages/vite/src/types/http-proxy.d.ts +++ b/packages/vite/src/types/http-proxy.d.ts @@ -43,7 +43,7 @@ export namespace HttpProxy { err: Error, req: http.IncomingMessage, res: http.ServerResponse, - target?: ProxyTargetUrl + target?: ProxyTargetUrl, ) => void export class Server extends events.EventEmitter { @@ -63,7 +63,7 @@ export namespace HttpProxy { req: http.IncomingMessage, res: http.ServerResponse, options?: ServerOptions, - callback?: ErrorCallback + callback?: ErrorCallback, ): void /** @@ -78,7 +78,7 @@ export namespace HttpProxy { socket: unknown, head: unknown, options?: ServerOptions, - callback?: ErrorCallback + callback?: ErrorCallback, ): void /** @@ -121,8 +121,8 @@ export namespace HttpProxy { listener: ( req: http.IncomingMessage, res: http.ServerResponse, - target: ProxyTargetUrl - ) => void + target: ProxyTargetUrl, + ) => void, ): this on( event: 'proxyReq', @@ -130,16 +130,16 @@ export namespace HttpProxy { proxyReq: http.ClientRequest, req: http.IncomingMessage, res: http.ServerResponse, - options: ServerOptions - ) => void + options: ServerOptions, + ) => void, ): this on( event: 'proxyRes', listener: ( proxyRes: http.IncomingMessage, req: http.IncomingMessage, - res: http.ServerResponse - ) => void + res: http.ServerResponse, + ) => void, ): this on( event: 'proxyReqWs', @@ -148,8 +148,8 @@ export namespace HttpProxy { req: http.IncomingMessage, socket: net.Socket, options: ServerOptions, - head: any - ) => void + head: any, + ) => void, ): this on( event: 'econnreset', @@ -157,24 +157,24 @@ export namespace HttpProxy { err: Error, req: http.IncomingMessage, res: http.ServerResponse, - target: ProxyTargetUrl - ) => void + target: ProxyTargetUrl, + ) => void, ): this on( event: 'end', listener: ( req: http.IncomingMessage, res: http.ServerResponse, - proxyRes: http.IncomingMessage - ) => void + proxyRes: http.IncomingMessage, + ) => void, ): this on( event: 'close', listener: ( proxyRes: http.IncomingMessage, proxySocket: net.Socket, - proxyHead: any - ) => void + proxyHead: any, + ) => void, ): this once(event: string, listener: () => void): this diff --git a/packages/vite/src/types/shims.d.ts b/packages/vite/src/types/shims.d.ts index db5ce9bc1dfb37..3540828cc2a14e 100644 --- a/packages/vite/src/types/shims.d.ts +++ b/packages/vite/src/types/shims.d.ts @@ -29,7 +29,7 @@ declare module 'postcss-import' { resolve: ( id: string, basedir: string, - importOptions: any + importOptions: any, ) => string | string[] | Promise nameLayer: (index: number, rootFilename: string) => string }) => Plugin diff --git a/packages/vite/src/types/terser.d.ts b/packages/vite/src/types/terser.d.ts index a704a20cdc71ae..6533da9d8c72de 100644 --- a/packages/vite/src/types/terser.d.ts +++ b/packages/vite/src/types/terser.d.ts @@ -106,7 +106,7 @@ export namespace Terser { Disabled = 0, SimpleFunctions = 1, WithArguments = 2, - WithArgumentsAndVariables = 3 + WithArgumentsAndVariables = 3, } export interface MangleOptions { @@ -182,7 +182,7 @@ export namespace Terser { pos: number line: number col: number - } + }, ) => boolean) ecma?: ECMA ie8?: boolean @@ -211,7 +211,7 @@ export namespace Terser { PreferDouble = 0, AlwaysSingle = 1, AlwaysDouble = 2, - AlwaysOriginal = 3 + AlwaysOriginal = 3, } export interface MinifyOptions { diff --git a/packages/vite/src/types/ws.d.ts b/packages/vite/src/types/ws.d.ts index a06341fca9eeb9..99932f49b19906 100644 --- a/packages/vite/src/types/ws.d.ts +++ b/packages/vite/src/types/ws.d.ts @@ -22,7 +22,7 @@ import type { ClientRequestArgs, Server as HTTPServer, IncomingMessage, - OutgoingHttpHeaders + OutgoingHttpHeaders, } from 'node:http' import type { Server as HTTPSServer } from 'node:https' import type { Duplex, DuplexOptions } from 'node:stream' @@ -72,12 +72,12 @@ declare class WebSocket extends EventEmitter { constructor(address: null) constructor( address: string | URL, - options?: WebSocket.ClientOptions | ClientRequestArgs + options?: WebSocket.ClientOptions | ClientRequestArgs, ) constructor( address: string | URL, protocols?: string | string[], - options?: WebSocket.ClientOptions | ClientRequestArgs + options?: WebSocket.ClientOptions | ClientRequestArgs, ) close(code?: number, data?: string | Buffer): void @@ -92,7 +92,7 @@ declare class WebSocket extends EventEmitter { compress?: boolean | undefined fin?: boolean | undefined }, - cb?: (err?: Error) => void + cb?: (err?: Error) => void, ): void terminate(): void @@ -112,190 +112,190 @@ declare class WebSocket extends EventEmitter { addEventListener( method: 'message', cb: (event: WebSocket.MessageEvent) => void, - options?: WebSocket.EventListenerOptions + options?: WebSocket.EventListenerOptions, ): void addEventListener( method: 'close', cb: (event: WebSocket.CloseEvent) => void, - options?: WebSocket.EventListenerOptions + options?: WebSocket.EventListenerOptions, ): void addEventListener( method: 'error', cb: (event: WebSocket.ErrorEvent) => void, - options?: WebSocket.EventListenerOptions + options?: WebSocket.EventListenerOptions, ): void addEventListener( method: 'open', cb: (event: WebSocket.Event) => void, - options?: WebSocket.EventListenerOptions + options?: WebSocket.EventListenerOptions, ): void removeEventListener( method: 'message', - cb: (event: WebSocket.MessageEvent) => void + cb: (event: WebSocket.MessageEvent) => void, ): void removeEventListener( method: 'close', - cb: (event: WebSocket.CloseEvent) => void + cb: (event: WebSocket.CloseEvent) => void, ): void removeEventListener( method: 'error', - cb: (event: WebSocket.ErrorEvent) => void + cb: (event: WebSocket.ErrorEvent) => void, ): void removeEventListener( method: 'open', - cb: (event: WebSocket.Event) => void + cb: (event: WebSocket.Event) => void, ): void // Events on( event: 'close', - listener: (this: WebSocket, code: number, reason: Buffer) => void + listener: (this: WebSocket, code: number, reason: Buffer) => void, ): this on(event: 'error', listener: (this: WebSocket, err: Error) => void): this on( event: 'upgrade', - listener: (this: WebSocket, request: IncomingMessage) => void + listener: (this: WebSocket, request: IncomingMessage) => void, ): this on( event: 'message', listener: ( this: WebSocket, data: WebSocket.RawData, - isBinary: boolean - ) => void + isBinary: boolean, + ) => void, ): this on(event: 'open', listener: (this: WebSocket) => void): this on( event: 'ping' | 'pong', - listener: (this: WebSocket, data: Buffer) => void + listener: (this: WebSocket, data: Buffer) => void, ): this on( event: 'unexpected-response', listener: ( this: WebSocket, request: ClientRequest, - response: IncomingMessage - ) => void + response: IncomingMessage, + ) => void, ): this on( event: string | symbol, - listener: (this: WebSocket, ...args: any[]) => void + listener: (this: WebSocket, ...args: any[]) => void, ): this once( event: 'close', - listener: (this: WebSocket, code: number, reason: Buffer) => void + listener: (this: WebSocket, code: number, reason: Buffer) => void, ): this once(event: 'error', listener: (this: WebSocket, err: Error) => void): this once( event: 'upgrade', - listener: (this: WebSocket, request: IncomingMessage) => void + listener: (this: WebSocket, request: IncomingMessage) => void, ): this once( event: 'message', listener: ( this: WebSocket, data: WebSocket.RawData, - isBinary: boolean - ) => void + isBinary: boolean, + ) => void, ): this once(event: 'open', listener: (this: WebSocket) => void): this once( event: 'ping' | 'pong', - listener: (this: WebSocket, data: Buffer) => void + listener: (this: WebSocket, data: Buffer) => void, ): this once( event: 'unexpected-response', listener: ( this: WebSocket, request: ClientRequest, - response: IncomingMessage - ) => void + response: IncomingMessage, + ) => void, ): this once( event: string | symbol, - listener: (this: WebSocket, ...args: any[]) => void + listener: (this: WebSocket, ...args: any[]) => void, ): this off( event: 'close', - listener: (this: WebSocket, code: number, reason: Buffer) => void + listener: (this: WebSocket, code: number, reason: Buffer) => void, ): this off(event: 'error', listener: (this: WebSocket, err: Error) => void): this off( event: 'upgrade', - listener: (this: WebSocket, request: IncomingMessage) => void + listener: (this: WebSocket, request: IncomingMessage) => void, ): this off( event: 'message', listener: ( this: WebSocket, data: WebSocket.RawData, - isBinary: boolean - ) => void + isBinary: boolean, + ) => void, ): this off(event: 'open', listener: (this: WebSocket) => void): this off( event: 'ping' | 'pong', - listener: (this: WebSocket, data: Buffer) => void + listener: (this: WebSocket, data: Buffer) => void, ): this off( event: 'unexpected-response', listener: ( this: WebSocket, request: ClientRequest, - response: IncomingMessage - ) => void + response: IncomingMessage, + ) => void, ): this off( event: string | symbol, - listener: (this: WebSocket, ...args: any[]) => void + listener: (this: WebSocket, ...args: any[]) => void, ): this addListener( event: 'close', - listener: (code: number, reason: Buffer) => void + listener: (code: number, reason: Buffer) => void, ): this addListener(event: 'error', listener: (err: Error) => void): this addListener( event: 'upgrade', - listener: (request: IncomingMessage) => void + listener: (request: IncomingMessage) => void, ): this addListener( event: 'message', - listener: (data: WebSocket.RawData, isBinary: boolean) => void + listener: (data: WebSocket.RawData, isBinary: boolean) => void, ): this addListener(event: 'open', listener: () => void): this addListener(event: 'ping' | 'pong', listener: (data: Buffer) => void): this addListener( event: 'unexpected-response', - listener: (request: ClientRequest, response: IncomingMessage) => void + listener: (request: ClientRequest, response: IncomingMessage) => void, ): this addListener(event: string | symbol, listener: (...args: any[]) => void): this removeListener( event: 'close', - listener: (code: number, reason: Buffer) => void + listener: (code: number, reason: Buffer) => void, ): this removeListener(event: 'error', listener: (err: Error) => void): this removeListener( event: 'upgrade', - listener: (request: IncomingMessage) => void + listener: (request: IncomingMessage) => void, ): this removeListener( event: 'message', - listener: (data: WebSocket.RawData, isBinary: boolean) => void + listener: (data: WebSocket.RawData, isBinary: boolean) => void, ): this removeListener(event: 'open', listener: () => void): this removeListener(event: 'ping' | 'pong', listener: (data: Buffer) => void): this removeListener( event: 'unexpected-response', - listener: (request: ClientRequest, response: IncomingMessage) => void + listener: (request: ClientRequest, response: IncomingMessage) => void, ): this removeListener( event: string | symbol, - listener: (...args: any[]) => void + listener: (...args: any[]) => void, ): this } @@ -340,8 +340,8 @@ declare namespace WebSocket { res: boolean, code?: number, message?: string, - headers?: OutgoingHttpHeaders - ) => void + headers?: OutgoingHttpHeaders, + ) => void, ) => void interface ClientOptions extends SecureContextOptions { @@ -428,7 +428,7 @@ declare namespace WebSocket { | undefined handleProtocols?: ( protocols: Set, - request: IncomingMessage + request: IncomingMessage, ) => string | false path?: string | undefined noServer?: boolean | undefined @@ -459,81 +459,93 @@ declare namespace WebSocket { request: IncomingMessage, socket: Duplex, upgradeHead: Buffer, - callback: (client: T, request: IncomingMessage) => void + callback: (client: T, request: IncomingMessage) => void, ): void shouldHandle(request: IncomingMessage): boolean | Promise // Events on( event: 'connection', - cb: (this: Server, socket: T, request: IncomingMessage) => void + cb: (this: Server, socket: T, request: IncomingMessage) => void, ): this on(event: 'error', cb: (this: Server, error: Error) => void): this on( event: 'headers', - cb: (this: Server, headers: string[], request: IncomingMessage) => void + cb: ( + this: Server, + headers: string[], + request: IncomingMessage, + ) => void, ): this on(event: 'close' | 'listening', cb: (this: Server) => void): this on( event: string | symbol, - listener: (this: Server, ...args: any[]) => void + listener: (this: Server, ...args: any[]) => void, ): this once( event: 'connection', - cb: (this: Server, socket: T, request: IncomingMessage) => void + cb: (this: Server, socket: T, request: IncomingMessage) => void, ): this once(event: 'error', cb: (this: Server, error: Error) => void): this once( event: 'headers', - cb: (this: Server, headers: string[], request: IncomingMessage) => void + cb: ( + this: Server, + headers: string[], + request: IncomingMessage, + ) => void, ): this once(event: 'close' | 'listening', cb: (this: Server) => void): this once( event: string | symbol, - listener: (this: Server, ...args: any[]) => void + listener: (this: Server, ...args: any[]) => void, ): this off( event: 'connection', - cb: (this: Server, socket: T, request: IncomingMessage) => void + cb: (this: Server, socket: T, request: IncomingMessage) => void, ): this off(event: 'error', cb: (this: Server, error: Error) => void): this off( event: 'headers', - cb: (this: Server, headers: string[], request: IncomingMessage) => void + cb: ( + this: Server, + headers: string[], + request: IncomingMessage, + ) => void, ): this off(event: 'close' | 'listening', cb: (this: Server) => void): this off( event: string | symbol, - listener: (this: Server, ...args: any[]) => void + listener: (this: Server, ...args: any[]) => void, ): this addListener( event: 'connection', - cb: (client: T, request: IncomingMessage) => void + cb: (client: T, request: IncomingMessage) => void, ): this addListener(event: 'error', cb: (err: Error) => void): this addListener( event: 'headers', - cb: (headers: string[], request: IncomingMessage) => void + cb: (headers: string[], request: IncomingMessage) => void, ): this addListener(event: 'close' | 'listening', cb: () => void): this addListener( event: string | symbol, - listener: (...args: any[]) => void + listener: (...args: any[]) => void, ): this removeListener(event: 'connection', cb: (client: T) => void): this removeListener(event: 'error', cb: (err: Error) => void): this removeListener( event: 'headers', - cb: (headers: string[], request: IncomingMessage) => void + cb: (headers: string[], request: IncomingMessage) => void, ): this removeListener(event: 'close' | 'listening', cb: () => void): this removeListener( event: string | symbol, - listener: (...args: any[]) => void + listener: (...args: any[]) => void, ): this } @@ -545,7 +557,7 @@ declare namespace WebSocket { // WebSocket stream function createWebSocketStream( websocket: WebSocket, - options?: DuplexOptions + options?: DuplexOptions, ): Duplex } diff --git a/packages/vite/types/customEvent.d.ts b/packages/vite/types/customEvent.d.ts index 86d0807e0b9256..c27bde437e97bf 100644 --- a/packages/vite/types/customEvent.d.ts +++ b/packages/vite/types/customEvent.d.ts @@ -2,7 +2,7 @@ import type { ErrorPayload, FullReloadPayload, PrunePayload, - UpdatePayload + UpdatePayload, } from './hmrPayload' export interface CustomEventMap { diff --git a/packages/vite/types/hot.d.ts b/packages/vite/types/hot.d.ts index 03f96d196e2099..5e8a450151606b 100644 --- a/packages/vite/types/hot.d.ts +++ b/packages/vite/types/hot.d.ts @@ -12,12 +12,12 @@ export interface ViteHotContext { accept(dep: string, cb: (mod: ModuleNamespace | undefined) => void): void accept( deps: readonly string[], - cb: (mods: Array) => void + cb: (mods: Array) => void, ): void acceptExports( exportNames: string | readonly string[], - cb?: (mod: ModuleNamespace | undefined) => void + cb?: (mod: ModuleNamespace | undefined) => void, ): void dispose(cb: (data: any) => void): void @@ -26,7 +26,7 @@ export interface ViteHotContext { on( event: T, - cb: (payload: InferCustomEventPayload) => void + cb: (payload: InferCustomEventPayload) => void, ): void send(event: T, data?: InferCustomEventPayload): void } diff --git a/packages/vite/types/importGlob.d.ts b/packages/vite/types/importGlob.d.ts index 321e3804a7e09a..98786bbdd9efa5 100644 --- a/packages/vite/types/importGlob.d.ts +++ b/packages/vite/types/importGlob.d.ts @@ -1,6 +1,6 @@ export interface ImportGlobOptions< Eager extends boolean, - AsType extends string + AsType extends string, > { /** * Import type for the import url. @@ -45,10 +45,10 @@ export interface ImportGlobFunction { < Eager extends boolean, As extends string, - T = As extends keyof KnownAsTypeMap ? KnownAsTypeMap[As] : unknown + T = As extends keyof KnownAsTypeMap ? KnownAsTypeMap[As] : unknown, >( glob: string | string[], - options?: ImportGlobOptions + options?: ImportGlobOptions, ): (Eager extends true ? true : false) extends true ? Record : Record Promise> @@ -59,7 +59,7 @@ export interface ImportGlobFunction { */ ( glob: string | string[], - options?: ImportGlobOptions + options?: ImportGlobOptions, ): Record Promise> /** * Import a list of files with a glob pattern. @@ -68,7 +68,7 @@ export interface ImportGlobFunction { */ ( glob: string | string[], - options: ImportGlobOptions + options: ImportGlobOptions, ): Record } @@ -80,10 +80,10 @@ export interface ImportGlobEagerFunction { */ < As extends string, - T = As extends keyof KnownAsTypeMap ? KnownAsTypeMap[As] : unknown + T = As extends keyof KnownAsTypeMap ? KnownAsTypeMap[As] : unknown, >( glob: string | string[], - options?: Omit, 'eager'> + options?: Omit, 'eager'>, ): Record /** * Eagerly import a list of files with a glob pattern. @@ -92,6 +92,6 @@ export interface ImportGlobEagerFunction { */ ( glob: string | string[], - options?: Omit, 'eager'> + options?: Omit, 'eager'>, ): Record } diff --git a/playground/alias/__tests__/alias.spec.ts b/playground/alias/__tests__/alias.spec.ts index cef34c07c51004..3cc6f8b8ce3315 100644 --- a/playground/alias/__tests__/alias.spec.ts +++ b/playground/alias/__tests__/alias.spec.ts @@ -7,13 +7,13 @@ test('fs', async () => { test('fs directory', async () => { expect(await page.textContent('.fs-dir')).toMatch( - '[success] alias to directory' + '[success] alias to directory', ) }) test('regex', async () => { expect(await page.textContent('.regex')).toMatch( - '[success] alias to directory via regex' + '[success] alias to directory via regex', ) }) @@ -23,7 +23,7 @@ test('dependency', async () => { test('js via script src', async () => { expect(await page.textContent('.from-script-src')).toMatch( - '[success] from script src' + '[success] from script src', ) }) @@ -35,18 +35,18 @@ test('css via link', async () => { test('optimized dep', async () => { expect(await page.textContent('.optimized')).toMatch( - '[success] alias optimized' + '[success] alias optimized', ) }) test('aliased module', async () => { expect(await page.textContent('.aliased-module')).toMatch( - '[success] aliased module' + '[success] aliased module', ) }) test('custom resolver', async () => { expect(await page.textContent('.custom-resolver')).toMatch( - '[success] alias to custom-resolver path' + '[success] alias to custom-resolver path', ) }) diff --git a/playground/alias/index.html b/playground/alias/index.html index 32a2fd171fc2b8..f292ea5c8ad07a 100644 --- a/playground/alias/index.html +++ b/playground/alias/index.html @@ -38,9 +38,9 @@

Alias

template: '[{{ msg }}] alias optimized dep', setup() { return { - msg: ref('success') + msg: ref('success'), } - } + }, }).mount('.optimized') // aliased to an absolute URL in CJS, should be optimized diff --git a/playground/alias/vite.config.js b/playground/alias/vite.config.js index 16c33dd859aa66..97ffcde1adc676 100644 --- a/playground/alias/vite.config.js +++ b/playground/alias/vite.config.js @@ -11,7 +11,7 @@ module.exports = { { find: 'dep', replacement: 'resolve-linked' }, { find: /^regex\/(.*)/, - replacement: `${path.resolve(__dirname, 'dir')}/$1` + replacement: `${path.resolve(__dirname, 'dir')}/$1`, }, { find: '/@', replacement: path.resolve(__dirname, 'dir') }, // aliasing an optimized dep @@ -19,7 +19,7 @@ module.exports = { // aliasing an optimized dep to absolute URL { find: '@vue/shared', - replacement: require.resolve('@vue/shared/dist/shared.cjs.prod.js') + replacement: require.resolve('@vue/shared/dist/shared.cjs.prod.js'), }, // aliasing one unoptimized dep to an optimized dep { find: 'foo', replacement: 'vue' }, @@ -28,15 +28,15 @@ module.exports = { replacement: path.resolve(__dirname, 'test.js'), customResolver(id) { return id.replace('test.js', 'customResolver.js') - } - } - ] + }, + }, + ], }, build: { - minify: false + minify: false, }, define: { __VUE_OPTIONS_API__: true, - __VUE_PROD_DEVTOOLS__: true - } + __VUE_PROD_DEVTOOLS__: true, + }, } diff --git a/playground/assets-sanitize/__tests__/assets-sanitize.spec.ts b/playground/assets-sanitize/__tests__/assets-sanitize.spec.ts index fc9c1ad8c81a7c..9fd8b1e988b089 100644 --- a/playground/assets-sanitize/__tests__/assets-sanitize.spec.ts +++ b/playground/assets-sanitize/__tests__/assets-sanitize.spec.ts @@ -17,7 +17,7 @@ if (!isBuild) { expect(await page.textContent('.plus-circle')).toMatch(plusCircleAsset) expect(await getBg('.underscore-circle')).toMatch(underscoreCircleAsset) expect(await page.textContent('.underscore-circle')).toMatch( - underscoreCircleAsset + underscoreCircleAsset, ) expect(plusCircleAsset).toMatch('/_circle') expect(underscoreCircleAsset).toMatch('/_circle') diff --git a/playground/assets-sanitize/vite.config.js b/playground/assets-sanitize/vite.config.js index 0e365a95383833..c259a739d608b0 100644 --- a/playground/assets-sanitize/vite.config.js +++ b/playground/assets-sanitize/vite.config.js @@ -6,6 +6,6 @@ module.exports = defineConfig({ minify: false, target: 'esnext', assetsInlineLimit: 0, - manifest: true - } + manifest: true, + }, }) diff --git a/playground/assets/__tests__/assets.spec.ts b/playground/assets/__tests__/assets.spec.ts index 5ba9437c4e0eab..482cf5a3b8a599 100644 --- a/playground/assets/__tests__/assets.spec.ts +++ b/playground/assets/__tests__/assets.spec.ts @@ -15,7 +15,7 @@ import { readManifest, untilUpdated, viteTestUrl, - watcher + watcher, } from '~utils' const assetMatch = isBuild @@ -32,17 +32,17 @@ test('should have no 404s', () => { test('should get a 404 when using incorrect case', async () => { expect((await fetch(path.posix.join(viteTestUrl, 'icon.png'))).status).toBe( - 200 + 200, ) expect((await fetch(path.posix.join(viteTestUrl, 'ICON.png'))).status).toBe( - 404 + 404, ) }) describe('injected scripts', () => { test('@vite/client', async () => { const hasClient = await page.$( - 'script[type="module"][src="/foo/@vite/client"]' + 'script[type="module"][src="/foo/@vite/client"]', ) if (isBuild) { expect(hasClient).toBeFalsy() @@ -53,7 +53,7 @@ describe('injected scripts', () => { test('html-proxy', async () => { const hasHtmlProxy = await page.$( - 'script[type="module"][src^="/foo/index.html?html-proxy"]' + 'script[type="module"][src^="/foo/index.html?html-proxy"]', ) if (isBuild) { expect(hasHtmlProxy).toBeFalsy() @@ -75,7 +75,7 @@ describe('raw references from /public', () => { test('import-expression from simple script', async () => { expect(await page.textContent('.import-expression')).toMatch( - '[success][success]' + '[success][success]', ) }) @@ -98,7 +98,7 @@ describe('css url() references', () => { expect( await page.evaluate(() => { return (document as any).fonts.check('700 32px Inter') - }) + }), ).toBe(true) }) @@ -137,7 +137,7 @@ describe('css url() references', () => { test('image-set with base64', async () => { const imageSet = await getBg('.css-image-set-base64') expect(imageSet).toMatch( - `-webkit-image-set(url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADwAAAA0AgMAAACrwbOMAAADI2lUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4gPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iQWRvYmUgWE1QIENvcmUgNS42LWMxMzggNzkuMTU5ODI0LCAyMDE2LzA5LzE0LTAxOjA5OjAxICAgICAgICAiPiA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPiA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtbG5zOnhtcD0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLyIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDo1MDI2QjVGQTg3RUIxMUVBQUFDMkQ3NTM0MUZGNzU3RSIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDo1MDI2QjVGOTg3RUIxMUVBQUFDMkQ3NTM0MUZGNzU3RSIgeG1wOkNyZWF0b3JUb29sPSJBZG9iZSBQaG90b3Nob3AgQ0MgKE1hY2ludG9zaCkiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDpBNzc3MDZDRjg3QUIxMUUzQjcwREVFMDM3NzA2QzEyMyIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDpBNzc3MDZEMDg3QUIxMUUzQjcwREVFMDM3NzA2QzEyMyIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/PqfCcbEAAAAZdEVYdFNvZnR3YXJlAEFkb2JlIEltYWdlUmVhZHlxyWU8AAAADFBMVEVBuoQ0R10/qn8/qX7FyuqbAAAABHRSTlP9/QGEiU0+GwAAAPtJREFUGBkFwbFNXEEUBdDD/QSWmE7YYAogWNeAaMfaEuiD5HfAk9yIAwqYwIGRRvt8zkNdvckrzzcfjqDccdPIYnH1AJ4ywLs7m53Fhkcw0+DLDxZn0PCHQrrg2xWOCpS7m6bFAj/ZDLFY/AJbDDZ/WUzR4B84BRoURBeAo4Si0CBMFvBEGMBmExYbi0loACcBjQKhC3AUQVGaRjBhMxAsFlwQDLYFBA04EaAVEHSBoxAoPmkITBYDAovNhsAAEwINTggAINCFoyCg0CBgYoCAjQsIACCgcYKABhCgHAUClAYCTAMIsF2AAAACtBMIQAEB+jcggE9AAC+A/zyyZDSXstCbAAAAAElFTkSuQmCC") 1x, url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADwAAAA0CAYAAADWr1sfAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyNpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNi1jMTM4IDc5LjE1OTgyNCwgMjAxNi8wOS8xNC0wMTowOTowMSAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0UmVmPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VSZWYjIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6NTAyNkI1RkE4N0VCMTFFQUFBQzJENzUzNDFGRjc1N0UiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6NTAyNkI1Rjk4N0VCMTFFQUFBQzJENzUzNDFGRjc1N0UiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENDIChNYWNpbnRvc2gpIj4gPHhtcE1NOkRlcml2ZWRGcm9tIHN0UmVmOmluc3RhbmNlSUQ9InhtcC5paWQ6QTc3NzA2Q0Y4N0FCMTFFM0I3MERFRTAzNzcwNkMxMjMiIHN0UmVmOmRvY3VtZW50SUQ9InhtcC5kaWQ6QTc3NzA2RDA4N0FCMTFFM0I3MERFRTAzNzcwNkMxMjMiLz4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz6nwnGxAAAJtklEQVR42txZ6W9c1RU/970373nsJHgZ27FThahSV8BCqGQTlIQ2EiUBReqHVpT8Af0r+NA/ogpqqWiDKrZuKYQPLGEpAlEFiqOgICSUBOKQhDjxeGY885bb37n3TGKPZ+4bx0uWK53Ec+cu53fPfkbtfu13B4noF6AQVAEpah0ak3cUSBU8qh46RfWj50ltKJDXXyBKdMtibI+TXlLqm2C87y/+eO/vlVIVnWbUcShFyld8T19ypvLbZKpyALOjVPCqrUcT1mWXYtIzMUV7Rqn315tJJyk+J51OZwb7QA3QkQD/fAL6JWiIXKMOhkOPwp1DFE/OkJ6NAQxn+fhuPhaFOc8DE9loern+hD9SfJVCdaLdOy5gif9rpHfyHp3pCX5cs6X1PfnORkr+SA9FO4bsgkZm1ykngm8ZK06ll0EvgWY6SwDn1fGKcykVfriewh2D5oKskhhw5KmFzLO0MJdO1yfS87UD2Uxc0tXErM+qLYQ5XUspK8el9JvagXSmPmH2W4lfG3wHNMHciXnmIfj+OvCVga8sD+yMYHyZAZ8H/Qk06dySaiNljf/DB0vklWAB1RQqnS0WA18eQE0Dz0++rjyRluOJDHuzWkwZNAPgLPHfPIeHTK/EEzHWKt/zDdh2asBmUUnJg3TDB0rQIuYptby5x6RgPO/JxIes304p44V1DMAzKQUbe4xqa62h2vbFyWuxeUie1RKqvVmXG/sxOaYKPqliQKp3HmEOB43pWaxJaTPvUV6rdK3Z6FloGUt35yD54EGXEwvaU3nSPSIYF7D5T/mio1rzS7Jaa1we4YWDzb1GUpptqJ1OGUl7BJX+jS7HP/OKEPlgRH5/SP5AZMjrCTz+jtdQQckxauEZ/IZ4bKyhYEsv7h6GpmGuhnsznafORwQbtQKGY6F/gy64pMxPnF2JSQ33UM/ecWNX/PJG3RbYsn15qCiYTQdhr49j9m4jQd8zXlkFZv3d/B087SBM4OodC+5kJYIX5r09+8ZIDYYAn4gqOdFeEEwn2gFmMb0BesEpZeOxARAOJ4SXjLbDlljKcbaQ0ebwrRNLy409oH1Xz1H2xrRc3wfaYx1dm/sgQTyYMZ1wZ4nC+4es76gnC3lqP14QTFk7wDymQH8DnXKCZibKiQHY89gY+aUeGwcT66xaw40JMUnWn52t7NWVeKt5GNaUarw1naruxXn9Rrrz9jRjLsd5PtsfZY3aaBZo9tT5qnxKsExRizto59EOccRzJQomHAC0DzsOHxwy3lvXk8VxU1u1VJFPaSW5B177SRtfNaVnq08izNyjQl9UefFe4zNwdoTI4I8XTfznu3NUORYMiyKP10HvD4neZy7VzqBaHEOjnw5TsKnXfgaDRjKqxWuzzRKtTy/Wt2W1ZAukuyX9tr4Ns+vZpheAVfKoOCuDKrNzDB8Ysp9Znd2qnAnvh9r5I8+hDs86HRhfCIlyQqGgbuHDI0Sz9gHaZj0sQXhhpJhbktOVp5Kvak/x31Sg9rarRXVxXvjwKJxk0Z7N/sOjPEf1bCez7LS1Ji/0iduBAUAD6JDpRFsHqfDjDZRdTqyU26gn2ykkXUovzf2KCV66ZGxXL9YeVtsMMb9w1x0U/WTAADWqnGO4wvMhwdA14PmqfbLjClZdTkaqCFPrAor2byIvUsZrd5Syp4BaFYW8RUmDeG8+wwsVRY+Pk7c+MJpkChXfCfhkJ1XuBjCPV0Bvt0nhFwoPiQfbVjixgaKHho3qGSlbgIu9ti/VEdHifJkdVc2aRoizwnv7kT+nNuy5hxZeX3EtygM8DfoX6FPnCcxL1Yap6NGNCCFFk5x0ETra2i7v9TcWqbh3zIbASmzvcHP7qfA6vRzAJIH7JWeYktRPz2a2bHuoZKpEdjgWdBeoWboMTpwea4o3GiF1lXzZPWLh8Y3ca7oAPAd6E/RubjLCkgBz4fYhCu6cl2d73UmX13KSUcDecNugqX2Np9a5mvKu8Di3EoB5HAP9WboGnZMRFiiXb0MhhYjNOrbeVsc5DPPexEqXz+C9HufLHHPT3PyxIbwd6wZIt4DnxCG81lG1JT9miZiaGeVj8L0+m3I2UrdaezY/z65Auj9ab0vPNLOlp+fEGwtPb3cj3aUA5nEWdDA3GTGMpqT6AupFmLLpYWaL9Hag2XZZdVHqcR1cfGzchDhdyWwFpnKTjIPCG600YFad96S+rHeOzZ5tB7Et3jeItLNk8+Fa2j6jYnU2YSyhaNcwFe4dMHv5DD7L1WUTXt5zmtoyADe7Bwfn15cdHZix3cxIzB+ObC+q2Z1Q6pq0E6gynF0A715ErasbqQWbH9JOCC8zSwGwVMA8Phb3X3a2g5BnZ5cRT78Dj7trxMRR7liY+lhdu5ntVnFDFLm4N1a0nr2e5rVtysLDx0tl/noAc9X7TLNH5KxZuC1Tg6puH0SYKtoaumFrYWPbsS0xg+/2UbjVVkNXW67u8aHwkKwFYB6fgQ47nYXXBBSbEBPtGjUtnWy6YcEm/F1q5sLdkO5AQTonuap8Vu7+7HoYv17APF4Fve6KrabEkzhcuH+AAuTFGmmjkeScbdsU7hswxGtMkqJzM7PX5W5aa8BfSDdwyt30I9Nw44qn+MgYef1IKC42SLN9D4TU8+iYCWGmKSfdEceYkju/uBGAebwvDW53KcOeFxlYcBeqqd3DBiznyCHCUPCDdUTsweM0765M7np/OQwvF/A5aYOedDcKmo23zP5qsalovTfny9wL4xQyP18+KXedu5GAmx0G9pizrsrAJCOQsuovUPTIKIU/HzG/SPKczks97dnPODswXY5gBQDXxK72g3a0fURT5yoTY7nw5w6ksVcAzZq/C7mbcv+TO2rLZXYlJMzjtNjXBedN7IlBXuibtq3ph8W5vw1dkLNPrwSjKwWY89oXQf9xNgqaXruaWLulXK8cy5kvOvP3GwC4mWc/50wImj+xaLrmpFRugvPcUvPltQJMUr0cXcHzjpLrF82bAHBN1O+dFTjrHTmrdjMD5vER6B/LZLQmZ3y00sytBuC65LtvLeOMt+SM+q0AmMekNNbK17G3LHsnV4Ox1QLM4wNRy3gJe2LZ88FqMbWagL8CPe2sptpXQ0/L3lsOMGcW3Cv+O+hyF+svy9pjsveWA9z0tn8Afd7F2s9lbW01GVptwJxTHZfE3/Uj17SsOU7ddLRuYsDN8decDOyorFn1sVaAvyT7k8iZNt+dke++vJ0A8+CfMw+3mT8s39HtBviSgDs+b+64zF26HQHz+C/o+Xmfn5c5ul0BXyT7w/U5oTdlbs1GQGs/vgb9cd7fazr+L8AAD0zRYMSYHQAAAAAASUVORK5CYII=") 2x)` + `-webkit-image-set(url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADwAAAA0AgMAAACrwbOMAAADI2lUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4gPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iQWRvYmUgWE1QIENvcmUgNS42LWMxMzggNzkuMTU5ODI0LCAyMDE2LzA5LzE0LTAxOjA5OjAxICAgICAgICAiPiA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPiA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtbG5zOnhtcD0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLyIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDo1MDI2QjVGQTg3RUIxMUVBQUFDMkQ3NTM0MUZGNzU3RSIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDo1MDI2QjVGOTg3RUIxMUVBQUFDMkQ3NTM0MUZGNzU3RSIgeG1wOkNyZWF0b3JUb29sPSJBZG9iZSBQaG90b3Nob3AgQ0MgKE1hY2ludG9zaCkiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDpBNzc3MDZDRjg3QUIxMUUzQjcwREVFMDM3NzA2QzEyMyIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDpBNzc3MDZEMDg3QUIxMUUzQjcwREVFMDM3NzA2QzEyMyIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/PqfCcbEAAAAZdEVYdFNvZnR3YXJlAEFkb2JlIEltYWdlUmVhZHlxyWU8AAAADFBMVEVBuoQ0R10/qn8/qX7FyuqbAAAABHRSTlP9/QGEiU0+GwAAAPtJREFUGBkFwbFNXEEUBdDD/QSWmE7YYAogWNeAaMfaEuiD5HfAk9yIAwqYwIGRRvt8zkNdvckrzzcfjqDccdPIYnH1AJ4ywLs7m53Fhkcw0+DLDxZn0PCHQrrg2xWOCpS7m6bFAj/ZDLFY/AJbDDZ/WUzR4B84BRoURBeAo4Si0CBMFvBEGMBmExYbi0loACcBjQKhC3AUQVGaRjBhMxAsFlwQDLYFBA04EaAVEHSBoxAoPmkITBYDAovNhsAAEwINTggAINCFoyCg0CBgYoCAjQsIACCgcYKABhCgHAUClAYCTAMIsF2AAAACtBMIQAEB+jcggE9AAC+A/zyyZDSXstCbAAAAAElFTkSuQmCC") 1x, url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADwAAAA0CAYAAADWr1sfAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyNpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNi1jMTM4IDc5LjE1OTgyNCwgMjAxNi8wOS8xNC0wMTowOTowMSAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0UmVmPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VSZWYjIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6NTAyNkI1RkE4N0VCMTFFQUFBQzJENzUzNDFGRjc1N0UiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6NTAyNkI1Rjk4N0VCMTFFQUFBQzJENzUzNDFGRjc1N0UiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENDIChNYWNpbnRvc2gpIj4gPHhtcE1NOkRlcml2ZWRGcm9tIHN0UmVmOmluc3RhbmNlSUQ9InhtcC5paWQ6QTc3NzA2Q0Y4N0FCMTFFM0I3MERFRTAzNzcwNkMxMjMiIHN0UmVmOmRvY3VtZW50SUQ9InhtcC5kaWQ6QTc3NzA2RDA4N0FCMTFFM0I3MERFRTAzNzcwNkMxMjMiLz4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz6nwnGxAAAJtklEQVR42txZ6W9c1RU/970373nsJHgZ27FThahSV8BCqGQTlIQ2EiUBReqHVpT8Af0r+NA/ogpqqWiDKrZuKYQPLGEpAlEFiqOgICSUBOKQhDjxeGY885bb37n3TGKPZ+4bx0uWK53Ec+cu53fPfkbtfu13B4noF6AQVAEpah0ak3cUSBU8qh46RfWj50ltKJDXXyBKdMtibI+TXlLqm2C87y/+eO/vlVIVnWbUcShFyld8T19ypvLbZKpyALOjVPCqrUcT1mWXYtIzMUV7Rqn315tJJyk+J51OZwb7QA3QkQD/fAL6JWiIXKMOhkOPwp1DFE/OkJ6NAQxn+fhuPhaFOc8DE9loern+hD9SfJVCdaLdOy5gif9rpHfyHp3pCX5cs6X1PfnORkr+SA9FO4bsgkZm1ykngm8ZK06ll0EvgWY6SwDn1fGKcykVfriewh2D5oKskhhw5KmFzLO0MJdO1yfS87UD2Uxc0tXErM+qLYQ5XUspK8el9JvagXSmPmH2W4lfG3wHNMHciXnmIfj+OvCVga8sD+yMYHyZAZ8H/Qk06dySaiNljf/DB0vklWAB1RQqnS0WA18eQE0Dz0++rjyRluOJDHuzWkwZNAPgLPHfPIeHTK/EEzHWKt/zDdh2asBmUUnJg3TDB0rQIuYptby5x6RgPO/JxIes304p44V1DMAzKQUbe4xqa62h2vbFyWuxeUie1RKqvVmXG/sxOaYKPqliQKp3HmEOB43pWaxJaTPvUV6rdK3Z6FloGUt35yD54EGXEwvaU3nSPSIYF7D5T/mio1rzS7Jaa1we4YWDzb1GUpptqJ1OGUl7BJX+jS7HP/OKEPlgRH5/SP5AZMjrCTz+jtdQQckxauEZ/IZ4bKyhYEsv7h6GpmGuhnsznafORwQbtQKGY6F/gy64pMxPnF2JSQ33UM/ecWNX/PJG3RbYsn15qCiYTQdhr49j9m4jQd8zXlkFZv3d/B087SBM4OodC+5kJYIX5r09+8ZIDYYAn4gqOdFeEEwn2gFmMb0BesEpZeOxARAOJ4SXjLbDlljKcbaQ0ebwrRNLy409oH1Xz1H2xrRc3wfaYx1dm/sgQTyYMZ1wZ4nC+4es76gnC3lqP14QTFk7wDymQH8DnXKCZibKiQHY89gY+aUeGwcT66xaw40JMUnWn52t7NWVeKt5GNaUarw1naruxXn9Rrrz9jRjLsd5PtsfZY3aaBZo9tT5qnxKsExRizto59EOccRzJQomHAC0DzsOHxwy3lvXk8VxU1u1VJFPaSW5B177SRtfNaVnq08izNyjQl9UefFe4zNwdoTI4I8XTfznu3NUORYMiyKP10HvD4neZy7VzqBaHEOjnw5TsKnXfgaDRjKqxWuzzRKtTy/Wt2W1ZAukuyX9tr4Ns+vZpheAVfKoOCuDKrNzDB8Ysp9Znd2qnAnvh9r5I8+hDs86HRhfCIlyQqGgbuHDI0Sz9gHaZj0sQXhhpJhbktOVp5Kvak/x31Sg9rarRXVxXvjwKJxk0Z7N/sOjPEf1bCez7LS1Ji/0iduBAUAD6JDpRFsHqfDjDZRdTqyU26gn2ykkXUovzf2KCV66ZGxXL9YeVtsMMb9w1x0U/WTAADWqnGO4wvMhwdA14PmqfbLjClZdTkaqCFPrAor2byIvUsZrd5Syp4BaFYW8RUmDeG8+wwsVRY+Pk7c+MJpkChXfCfhkJ1XuBjCPV0Bvt0nhFwoPiQfbVjixgaKHho3qGSlbgIu9ti/VEdHifJkdVc2aRoizwnv7kT+nNuy5hxZeX3EtygM8DfoX6FPnCcxL1Yap6NGNCCFFk5x0ETra2i7v9TcWqbh3zIbASmzvcHP7qfA6vRzAJIH7JWeYktRPz2a2bHuoZKpEdjgWdBeoWboMTpwea4o3GiF1lXzZPWLh8Y3ca7oAPAd6E/RubjLCkgBz4fYhCu6cl2d73UmX13KSUcDecNugqX2Np9a5mvKu8Di3EoB5HAP9WboGnZMRFiiXb0MhhYjNOrbeVsc5DPPexEqXz+C9HufLHHPT3PyxIbwd6wZIt4DnxCG81lG1JT9miZiaGeVj8L0+m3I2UrdaezY/z65Auj9ab0vPNLOlp+fEGwtPb3cj3aUA5nEWdDA3GTGMpqT6AupFmLLpYWaL9Hag2XZZdVHqcR1cfGzchDhdyWwFpnKTjIPCG600YFad96S+rHeOzZ5tB7Et3jeItLNk8+Fa2j6jYnU2YSyhaNcwFe4dMHv5DD7L1WUTXt5zmtoyADe7Bwfn15cdHZix3cxIzB+ObC+q2Z1Q6pq0E6gynF0A715ErasbqQWbH9JOCC8zSwGwVMA8Phb3X3a2g5BnZ5cRT78Dj7trxMRR7liY+lhdu5ntVnFDFLm4N1a0nr2e5rVtysLDx0tl/noAc9X7TLNH5KxZuC1Tg6puH0SYKtoaumFrYWPbsS0xg+/2UbjVVkNXW67u8aHwkKwFYB6fgQ47nYXXBBSbEBPtGjUtnWy6YcEm/F1q5sLdkO5AQTonuap8Vu7+7HoYv17APF4Fve6KrabEkzhcuH+AAuTFGmmjkeScbdsU7hswxGtMkqJzM7PX5W5aa8BfSDdwyt30I9Nw44qn+MgYef1IKC42SLN9D4TU8+iYCWGmKSfdEceYkju/uBGAebwvDW53KcOeFxlYcBeqqd3DBiznyCHCUPCDdUTsweM0765M7np/OQwvF/A5aYOedDcKmo23zP5qsalovTfny9wL4xQyP18+KXedu5GAmx0G9pizrsrAJCOQsuovUPTIKIU/HzG/SPKczks97dnPODswXY5gBQDXxK72g3a0fURT5yoTY7nw5w6ksVcAzZq/C7mbcv+TO2rLZXYlJMzjtNjXBedN7IlBXuibtq3ph8W5vw1dkLNPrwSjKwWY89oXQf9xNgqaXruaWLulXK8cy5kvOvP3GwC4mWc/50wImj+xaLrmpFRugvPcUvPltQJMUr0cXcHzjpLrF82bAHBN1O+dFTjrHTmrdjMD5vER6B/LZLQmZ3y00sytBuC65LtvLeOMt+SM+q0AmMekNNbK17G3LHsnV4Ox1QLM4wNRy3gJe2LZ88FqMbWagL8CPe2sptpXQ0/L3lsOMGcW3Cv+O+hyF+svy9pjsveWA9z0tn8Afd7F2s9lbW01GVptwJxTHZfE3/Uj17SsOU7ddLRuYsDN8decDOyorFn1sVaAvyT7k8iZNt+dke++vJ0A8+CfMw+3mT8s39HtBviSgDs+b+64zF26HQHz+C/o+Xmfn5c5ul0BXyT7w/U5oTdlbs1GQGs/vgb9cd7fazr+L8AAD0zRYMSYHQAAAAAASUVORK5CYII=") 2x)`, ) }) @@ -210,7 +210,7 @@ describe('image', () => { expect(s).toMatch( isBuild ? /\/foo\/assets\/asset-\w{8}\.png \dx/ - : /\/foo\/nested\/asset.png \dx/ + : /\/foo\/nested\/asset.png \dx/, ) }) }) @@ -238,7 +238,7 @@ describe('svg fragments', () => { test('Unknown extension assets import', async () => { expect(await page.textContent('.unknown-ext')).toMatch( - isBuild ? 'data:application/octet-stream;' : '/nested/foo.unknown' + isBuild ? 'data:application/octet-stream;' : '/nested/foo.unknown', ) }) @@ -251,9 +251,9 @@ test('?url import', async () => { expect(await page.textContent('.url')).toMatch( isBuild ? `data:application/javascript;base64,${Buffer.from(src).toString( - 'base64' + 'base64', )}` - : `/foo/foo.js` + : `/foo/foo.js`, ) }) @@ -263,7 +263,7 @@ test('?url import on css', async () => { expect(txt).toEqual( isBuild ? `data:text/css;base64,${Buffer.from(src).toString('base64')}` - : '/foo/css/icons.css' + : '/foo/css/icons.css', ) }) @@ -273,9 +273,9 @@ describe('unicode url', () => { expect(await page.textContent('.unicode-url')).toMatch( isBuild ? `data:application/javascript;base64,${Buffer.from(src).toString( - 'base64' + 'base64', )}` - : `/foo/テスト-測試-white space.js` + : `/foo/テスト-測試-white space.js`, ) }) }) @@ -284,7 +284,7 @@ describe.runIf(isBuild)('encodeURI', () => { test('img src with encodeURI', async () => { const img = await page.$('.encodeURI') expect( - (await img.getAttribute('src')).startsWith('data:image/png;base64') + (await img.getAttribute('src')).startsWith('data:image/png;base64'), ).toBe(true) }) }) @@ -299,25 +299,25 @@ test('new URL("@/...", import.meta.url)', async () => { test('new URL("/...", import.meta.url)', async () => { expect(await page.textContent('.import-meta-url-base-path')).toMatch( - iconMatch + iconMatch, ) }) test('new URL(`${dynamic}`, import.meta.url)', async () => { expect(await page.textContent('.dynamic-import-meta-url-1')).toMatch( - isBuild ? 'data:image/png;base64' : '/foo/nested/icon.png' + isBuild ? 'data:image/png;base64' : '/foo/nested/icon.png', ) expect(await page.textContent('.dynamic-import-meta-url-2')).toMatch( - assetMatch + assetMatch, ) expect(await page.textContent('.dynamic-import-meta-url-js')).toMatch( - isBuild ? 'data:application/javascript;base64' : '/foo/nested/test.js' + isBuild ? 'data:application/javascript;base64' : '/foo/nested/test.js', ) }) test('new URL(`non-existent`, import.meta.url)', async () => { expect(await page.textContent('.non-existent-import-meta-url')).toMatch( - new URL('non-existent', page.url()).pathname + new URL('non-existent', page.url()).pathname, ) }) @@ -371,7 +371,7 @@ if (!isBuild) { editFile( './css/import.css', (code) => code.replace('#0088ff', '#00ff88'), - true + true, ) await page.waitForNavigation() await untilUpdated(() => getColor('.import-css'), 'rgb(0, 255, 136)') @@ -380,7 +380,7 @@ if (!isBuild) { test('html import word boundary', async () => { expect(await page.textContent('.obj-import-express')).toMatch( - 'ignore object import prop' + 'ignore object import prop', ) expect(await page.textContent('.string-import-express')).toMatch('no load') }) diff --git a/playground/assets/__tests__/relative-base/relative-base-assets.spec.ts b/playground/assets/__tests__/relative-base/relative-base-assets.spec.ts index 7163b425ecc585..70cb0fef940978 100644 --- a/playground/assets/__tests__/relative-base/relative-base-assets.spec.ts +++ b/playground/assets/__tests__/relative-base/relative-base-assets.spec.ts @@ -6,7 +6,7 @@ import { getColor, isBuild, page, - viteConfig + viteConfig, } from '~utils' const absoluteAssetMatch = isBuild @@ -43,26 +43,26 @@ describe('raw references from /public', () => { test('import-expression from simple script', async () => { expect(await page.textContent('.import-expression')).toMatch( - '[success][success]' + '[success][success]', ) }) describe('asset imports from js', () => { test('relative', async () => { expect(await page.textContent('.asset-import-relative')).toMatch( - cssBgAssetMatch + cssBgAssetMatch, ) }) test('absolute', async () => { expect(await page.textContent('.asset-import-absolute')).toMatch( - cssBgAssetMatch + cssBgAssetMatch, ) }) test('from /public', async () => { expect(await page.textContent('.public-import')).toMatch( - absolutePublicIconMatch + absolutePublicIconMatch, ) }) }) @@ -72,7 +72,7 @@ describe('css url() references', () => { expect( await page.evaluate(() => { return (document as any).fonts.check('700 32px Inter') - }) + }), ).toBe(true) }) @@ -111,7 +111,7 @@ describe('css url() references', () => { test('relative in @import', async () => { expect(await getBg('.css-url-relative-at-imported')).toMatch( - cssBgAssetMatch + cssBgAssetMatch, ) }) @@ -159,7 +159,7 @@ describe('image', () => { expect(s).toMatch( isBuild ? /other-assets\/asset-\w{8}\.png \dx/ - : /\.\/nested\/asset\.png \dx/ + : /\.\/nested\/asset\.png \dx/, ) }) }) @@ -191,14 +191,14 @@ test('?raw import', async () => { test('?url import', async () => { expect(await page.textContent('.url')).toMatch( - isBuild ? /http.*\/other-assets\/foo-\w{8}\.js/ : `/foo.js` + isBuild ? /http.*\/other-assets\/foo-\w{8}\.js/ : `/foo.js`, ) }) test('?url import on css', async () => { const txt = await page.textContent('.url-css') expect(txt).toMatch( - isBuild ? /http.*\/other-assets\/icons-\w{8}\.css/ : '/css/icons.css' + isBuild ? /http.*\/other-assets\/icons-\w{8}\.css/ : '/css/icons.css', ) }) @@ -215,7 +215,7 @@ test('new URL(`${dynamic}`, import.meta.url)', async () => { test('new URL(`non-existent`, import.meta.url)', async () => { expect(await page.textContent('.non-existent-import-meta-url')).toMatch( - '/non-existent' + '/non-existent', ) }) @@ -226,7 +226,7 @@ test('inline style test', async () => { test('html import word boundary', async () => { expect(await page.textContent('.obj-import-express')).toMatch( - 'ignore object import prop' + 'ignore object import prop', ) expect(await page.textContent('.string-import-express')).toMatch('no load') }) diff --git a/playground/assets/__tests__/runtime-base/runtime-base-assets.spec.ts b/playground/assets/__tests__/runtime-base/runtime-base-assets.spec.ts index 0606e8bf8dfa88..12412d00ef4204 100644 --- a/playground/assets/__tests__/runtime-base/runtime-base-assets.spec.ts +++ b/playground/assets/__tests__/runtime-base/runtime-base-assets.spec.ts @@ -5,7 +5,7 @@ import { getBg, getColor, isBuild, - page + page, } from '~utils' const absoluteAssetMatch = isBuild @@ -42,26 +42,26 @@ describe('raw references from /public', () => { test('import-expression from simple script', async () => { expect(await page.textContent('.import-expression')).toMatch( - '[success][success]' + '[success][success]', ) }) describe('asset imports from js', () => { test('relative', async () => { expect(await page.textContent('.asset-import-relative')).toMatch( - cssBgAssetMatch + cssBgAssetMatch, ) }) test('absolute', async () => { expect(await page.textContent('.asset-import-absolute')).toMatch( - cssBgAssetMatch + cssBgAssetMatch, ) }) test('from /public', async () => { expect(await page.textContent('.public-import')).toMatch( - absolutePublicIconMatch + absolutePublicIconMatch, ) }) }) @@ -71,7 +71,7 @@ describe('css url() references', () => { expect( await page.evaluate(() => { return (document as any).fonts.check('700 32px Inter') - }) + }), ).toBe(true) }) @@ -110,7 +110,7 @@ describe('css url() references', () => { test('relative in @import', async () => { expect(await getBg('.css-url-relative-at-imported')).toMatch( - cssBgAssetMatch + cssBgAssetMatch, ) }) @@ -157,7 +157,7 @@ describe('image', () => { expect(s).toMatch( isBuild ? /other-assets\/asset-\w{8}\.png \dx/ - : /\.\/nested\/asset\.png \dx/ + : /\.\/nested\/asset\.png \dx/, ) }) }) @@ -189,14 +189,14 @@ test('?raw import', async () => { test('?url import', async () => { expect(await page.textContent('.url')).toMatch( - isBuild ? /\/other-assets\/foo-\w{8}\.js/ : `/foo.js` + isBuild ? /\/other-assets\/foo-\w{8}\.js/ : `/foo.js`, ) }) test('?url import on css', async () => { const txt = await page.textContent('.url-css') expect(txt).toMatch( - isBuild ? /\/other-assets\/icons-\w{8}\.css/ : '/css/icons.css' + isBuild ? /\/other-assets\/icons-\w{8}\.css/ : '/css/icons.css', ) }) @@ -213,7 +213,7 @@ test('new URL(`${dynamic}`, import.meta.url)', async () => { test('new URL(`non-existent`, import.meta.url)', async () => { expect(await page.textContent('.non-existent-import-meta-url')).toMatch( - '/non-existent' + '/non-existent', ) }) @@ -224,7 +224,7 @@ test('inline style test', async () => { test('html import word boundary', async () => { expect(await page.textContent('.obj-import-express')).toMatch( - 'ignore object import prop' + 'ignore object import prop', ) expect(await page.textContent('.string-import-express')).toMatch('no load') }) diff --git a/playground/assets/index.html b/playground/assets/index.html index f897d61a355ed0..a8dc818b25daee 100644 --- a/playground/assets/index.html +++ b/playground/assets/index.html @@ -234,7 +234,7 @@

simple script tag import-expression

const obj = { import(t) { text('.obj-import-express', t) - } + }, } const stringImport = "const t = import('package')" function text(el, text) { diff --git a/playground/assets/vite.config-relative-base.js b/playground/assets/vite.config-relative-base.js index 7b54a149bcd987..7edbaf07c95c29 100644 --- a/playground/assets/vite.config-relative-base.js +++ b/playground/assets/vite.config-relative-base.js @@ -16,11 +16,11 @@ module.exports = { output: { entryFileNames: 'entries/[name].js', chunkFileNames: 'chunks/[name]-[hash].js', - assetFileNames: 'other-assets/[name]-[hash][extname]' - } - } + assetFileNames: 'other-assets/[name]-[hash][extname]', + }, + }, }, testConfig: { - baseRoute: '/relative-base/' - } + baseRoute: '/relative-base/', + }, } diff --git a/playground/assets/vite.config-runtime-base.js b/playground/assets/vite.config-runtime-base.js index 12d20e7956e131..7d2c042c9211e5 100644 --- a/playground/assets/vite.config-runtime-base.js +++ b/playground/assets/vite.config-runtime-base.js @@ -23,9 +23,9 @@ module.exports = { output: { entryFileNames: 'entries/[name].js', chunkFileNames: 'chunks/[name]-[hash].js', - assetFileNames: 'other-assets/[name]-[hash][extname]' - } - } + assetFileNames: 'other-assets/[name]-[hash][extname]', + }, + }, }, plugins: [ { @@ -37,28 +37,28 @@ module.exports = { { tag: 'script', attrs: { type: 'module' }, - children: dynamicBaseAssetsCode - } + children: dynamicBaseAssetsCode, + }, ] } - } - } + }, + }, ], experimental: { renderBuiltUrl(filename, { hostType, type }) { if (type === 'asset') { if (hostType === 'js') { return { - runtime: `globalThis.__toAssetUrl(${JSON.stringify(filename)})` + runtime: `globalThis.__toAssetUrl(${JSON.stringify(filename)})`, } } } else if (type === 'public') { if (hostType === 'js') { return { - runtime: `globalThis.__publicBase+${JSON.stringify(filename)}` + runtime: `globalThis.__publicBase+${JSON.stringify(filename)}`, } } } - } - } + }, + }, } diff --git a/playground/assets/vite.config.js b/playground/assets/vite.config.js index ff4789679659d8..e6d2ba3fb460d2 100644 --- a/playground/assets/vite.config.js +++ b/playground/assets/vite.config.js @@ -8,14 +8,14 @@ module.exports = { publicDir: 'static', resolve: { alias: { - '@': path.resolve(__dirname, 'nested') - } + '@': path.resolve(__dirname, 'nested'), + }, }, assetsInclude: ['**/*.unknown'], build: { outDir: 'dist/foo', assetsInlineLimit: 8192, // 8kb manifest: true, - watch: {} - } + watch: {}, + }, } diff --git a/playground/backend-integration/__tests__/backend-integration.spec.ts b/playground/backend-integration/__tests__/backend-integration.spec.ts index 29b4b903c1d0ed..8d067f0616775d 100644 --- a/playground/backend-integration/__tests__/backend-integration.spec.ts +++ b/playground/backend-integration/__tests__/backend-integration.spec.ts @@ -9,7 +9,7 @@ import { page, readManifest, untilBrowserLogAfter, - untilUpdated + untilUpdated, } from '~utils' const outerAssetMatch = isBuild @@ -25,7 +25,7 @@ test('should have no 404s', () => { describe('asset imports from js', () => { test('file outside root', async () => { expect( - await page.textContent('.asset-reference.outside-root .asset-url') + await page.textContent('.asset-reference.outside-root .asset-url'), ).toMatch(outerAssetMatch) }) }) @@ -61,7 +61,7 @@ describe.runIf(isServe)('serve', () => { test('preserve the base in CSS HMR', async () => { await untilUpdated(() => getColor('body'), 'black') // sanity check editFile('frontend/entrypoints/global.css', (code) => - code.replace('black', 'red') + code.replace('black', 'red'), ) await untilUpdated(() => getColor('body'), 'red') // successful HMR @@ -75,9 +75,9 @@ describe.runIf(isServe)('serve', () => { await untilBrowserLogAfter( () => editFile('frontend/entrypoints/main.ts', (code) => - code.replace('text-black', 'text-[rgb(204,0,0)]') + code.replace('text-black', 'text-[rgb(204,0,0)]'), ), - '[vite] css hot updated: /global.css' + '[vite] css hot updated: /global.css', ) await untilUpdated(() => getColor(el), 'rgb(204, 0, 0)') }) diff --git a/playground/backend-integration/postcss.config.js b/playground/backend-integration/postcss.config.js index 9c7a1787315279..f2f538422a839e 100644 --- a/playground/backend-integration/postcss.config.js +++ b/playground/backend-integration/postcss.config.js @@ -1,6 +1,6 @@ // postcss.config.js module.exports = { plugins: { - tailwindcss: { config: __dirname + '/tailwind.config.js' } - } + tailwindcss: { config: __dirname + '/tailwind.config.js' }, + }, } diff --git a/playground/backend-integration/tailwind.config.js b/playground/backend-integration/tailwind.config.js index 0c3ae11de7565e..a91db5247f6553 100644 --- a/playground/backend-integration/tailwind.config.js +++ b/playground/backend-integration/tailwind.config.js @@ -1,10 +1,10 @@ module.exports = { content: [__dirname + '/frontend/**/*.{css,html,ts,js}'], theme: { - extend: {} + extend: {}, }, variants: { - extend: {} + extend: {}, }, - plugins: [] + plugins: [], } diff --git a/playground/backend-integration/vite.config.js b/playground/backend-integration/vite.config.js index ff5d2c43c3ed04..245f1324ded5ed 100644 --- a/playground/backend-integration/vite.config.js +++ b/playground/backend-integration/vite.config.js @@ -26,17 +26,17 @@ function BackendIntegrationExample() { manifest: true, outDir, rollupOptions: { - input: Object.fromEntries(entrypoints) - } + input: Object.fromEntries(entrypoints), + }, }, root, resolve: { alias: { - '~': sourceCodeDir - } - } + '~': sourceCodeDir, + }, + }, } - } + }, } } @@ -45,5 +45,5 @@ function BackendIntegrationExample() { */ module.exports = { base: '/dev/', - plugins: [BackendIntegrationExample()] + plugins: [BackendIntegrationExample()], } diff --git a/playground/build-old/vite.config.js b/playground/build-old/vite.config.js index aa85af55972eb1..6c5d26db8c0ee7 100644 --- a/playground/build-old/vite.config.js +++ b/playground/build-old/vite.config.js @@ -3,6 +3,6 @@ import { defineConfig } from 'vite' export default defineConfig({ build: { // old browsers only - target: ['chrome60'] - } + target: ['chrome60'], + }, }) diff --git a/playground/cli-module/__tests__/cli-module.spec.ts b/playground/cli-module/__tests__/cli-module.spec.ts index ef109e75cc77cc..7eccaaa74b8578 100644 --- a/playground/cli-module/__tests__/cli-module.spec.ts +++ b/playground/cli-module/__tests__/cli-module.spec.ts @@ -13,12 +13,12 @@ test('cli should work in "type":"module" package', async () => { page.on('console', onConsole) await page.goto(`http://localhost:${port}/`) expect(await page.textContent('.app')).toBe( - 'vite cli in "type":"module" package works!' + 'vite cli in "type":"module" package works!', ) expect( logs.some((msg) => - msg.match('vite cli in "type":"module" package works!') - ) + msg.match('vite cli in "type":"module" package works!'), + ), ).toBe(true) } finally { page.off('console', onConsole) diff --git a/playground/cli-module/__tests__/serve.ts b/playground/cli-module/__tests__/serve.ts index 545d3732844b6b..4a76a6f810b3a9 100644 --- a/playground/cli-module/__tests__/serve.ts +++ b/playground/cli-module/__tests__/serve.ts @@ -9,7 +9,7 @@ import { killProcess, ports, rootDir, - viteBinPath + viteBinPath, } from '~utils' export const port = ports['cli-module'] @@ -18,7 +18,7 @@ export async function serve() { // collect stdout and stderr streams from child processes here to avoid interfering with regular vitest output const streams = { build: { out: [], err: [] }, - server: { out: [], err: [] } + server: { out: [], err: [] }, } // helpers to collect streams const collectStreams = (name, process) => { @@ -47,7 +47,7 @@ export async function serve() { try { const buildProcess = execaCommand(buildCommand, { cwd: rootDir, - stdio: 'pipe' + stdio: 'pipe', }) collectStreams('build', buildProcess) await buildProcess @@ -69,7 +69,7 @@ export async function serve() { const serverCommand = `${viteBinPath} ${viteServerArgs.join(' ')}` const serverProcess = execaCommand(serverCommand, { cwd: rootDir, - stdio: 'pipe' + stdio: 'pipe', }) collectStreams('server', serverProcess) @@ -85,7 +85,7 @@ export async function serve() { collectErrorStreams('server', e) console.error( `error while killing cli command "${serverCommand}":`, - e + e, ) await printStreamsToConsole('server') } @@ -105,7 +105,7 @@ export async function serve() { } catch (e1) { console.error( `error while killing cli command after failed execute "${serverCommand}":`, - e1 + e1, ) } } @@ -120,7 +120,7 @@ async function startedOnPort(serverProcess, port, timeout) { // hack, console output may contain color code gibberish // skip gibberish between localhost: and port number const match = str.match( - /(http:\/\/(?:localhost|127\.0\.0\.1|\[::1\]):).*(\d{4})/ + /(http:\/\/(?:localhost|127\.0\.0\.1|\[::1\]):).*(\d{4})/, ) if (match) { const startedPort = parseInt(match[2], 10) @@ -137,7 +137,7 @@ async function startedOnPort(serverProcess, port, timeout) { return resolvedOrTimeout( startedPromise, timeout, - `failed to start within ${timeout}ms` + `failed to start within ${timeout}ms`, ).finally(() => serverProcess.stdout.off('data', checkPort)) } @@ -148,7 +148,7 @@ async function resolvedOrTimeout(promise, ms, errorMessage) { promise, new Promise((_, reject) => { timer = setTimeout(() => reject(errorMessage), ms) - }) + }), ]).finally(() => { clearTimeout(timer) timer = null diff --git a/playground/cli-module/vite.config.js b/playground/cli-module/vite.config.js index 4020d4627917bb..ed7ac01c2d6612 100644 --- a/playground/cli-module/vite.config.js +++ b/playground/cli-module/vite.config.js @@ -8,11 +8,11 @@ globalThis.__test_url = URL export default defineConfig({ server: { - host: 'localhost' + host: 'localhost', }, build: { //speed up build minify: false, - target: 'esnext' - } + target: 'esnext', + }, }) diff --git a/playground/cli/__tests__/serve.ts b/playground/cli/__tests__/serve.ts index ec4f80a79d4593..3597e236bdd806 100644 --- a/playground/cli/__tests__/serve.ts +++ b/playground/cli/__tests__/serve.ts @@ -9,7 +9,7 @@ import { killProcess, ports, rootDir, - viteBinPath + viteBinPath, } from '~utils' export const port = ports.cli @@ -18,7 +18,7 @@ export async function serve() { // collect stdout and stderr streams from child processes here to avoid interfering with regular vitest output const streams = { build: { out: [], err: [] }, - server: { out: [], err: [] } + server: { out: [], err: [] }, } // helpers to collect streams const collectStreams = (name, process) => { @@ -47,7 +47,7 @@ export async function serve() { try { const buildProcess = execaCommand(buildCommand, { cwd: rootDir, - stdio: 'pipe' + stdio: 'pipe', }) collectStreams('build', buildProcess) await buildProcess @@ -69,7 +69,7 @@ export async function serve() { const serverCommand = `${viteBinPath} ${viteServerArgs.join(' ')}` const serverProcess = execaCommand(serverCommand, { cwd: rootDir, - stdio: 'pipe' + stdio: 'pipe', }) collectStreams('server', serverProcess) @@ -85,7 +85,7 @@ export async function serve() { collectErrorStreams('server', e) console.error( `error while killing cli command "${serverCommand}":`, - e + e, ) await printStreamsToConsole('server') } @@ -105,7 +105,7 @@ export async function serve() { } catch (e1) { console.error( `error while killing cli command after failed execute "${serverCommand}":`, - e1 + e1, ) } } @@ -120,7 +120,7 @@ async function startedOnPort(serverProcess, port, timeout) { // hack, console output may contain color code gibberish // skip gibberish between localhost: and port number const match = str.match( - /(http:\/\/(?:localhost|127\.0\.0\.1|\[::1\]):).*(\d{4})/ + /(http:\/\/(?:localhost|127\.0\.0\.1|\[::1\]):).*(\d{4})/, ) if (match) { const startedPort = parseInt(match[2], 10) @@ -137,7 +137,7 @@ async function startedOnPort(serverProcess, port, timeout) { return resolvedOrTimeout( startedPromise, timeout, - `failed to start within ${timeout}ms` + `failed to start within ${timeout}ms`, ).finally(() => serverProcess.stdout.off('data', checkPort)) } @@ -148,7 +148,7 @@ async function resolvedOrTimeout(promise, ms, errorMessage) { promise, new Promise((_, reject) => { timer = setTimeout(() => reject(errorMessage), ms) - }) + }), ]).finally(() => { clearTimeout(timer) timer = null diff --git a/playground/cli/vite.config.js b/playground/cli/vite.config.js index f7b25d32ecc312..5a5d90cdd8d570 100644 --- a/playground/cli/vite.config.js +++ b/playground/cli/vite.config.js @@ -4,12 +4,12 @@ module.exports = defineConfig({ server: { host: 'localhost', headers: { - 'Cache-Control': 'no-store' - } + 'Cache-Control': 'no-store', + }, }, build: { //speed up build minify: false, - target: 'esnext' - } + target: 'esnext', + }, }) diff --git a/playground/config/__tests__/load.spec.ts b/playground/config/__tests__/load.spec.ts index 3205912b8156c3..6236fff91b9272 100644 --- a/playground/config/__tests__/load.spec.ts +++ b/playground/config/__tests__/load.spec.ts @@ -6,7 +6,7 @@ it('loadConfigFromFile', async () => { const { config } = await loadConfigFromFile( {} as any, resolve(__dirname, '../packages/entry/vite.config.ts'), - resolve(__dirname, '../packages/entry') + resolve(__dirname, '../packages/entry'), ) expect(config).toMatchInlineSnapshot(` { diff --git a/playground/config/packages/entry/vite.config.ts b/playground/config/packages/entry/vite.config.ts index 9b865e5fa3d66a..7a4e9a682ae040 100644 --- a/playground/config/packages/entry/vite.config.ts +++ b/playground/config/packages/entry/vite.config.ts @@ -3,5 +3,5 @@ import { array } from '../siblings/foo' export default { array, - moduleCondition + moduleCondition, } diff --git a/playground/css-codesplit-cjs/main.js b/playground/css-codesplit-cjs/main.js index 8c80df2c181511..4234674de9dee5 100644 --- a/playground/css-codesplit-cjs/main.js +++ b/playground/css-codesplit-cjs/main.js @@ -2,5 +2,5 @@ import './style.css' import './main.css' document.getElementById( - 'app' + 'app', ).innerHTML = `

This should be red

This should be blue

` diff --git a/playground/css-codesplit-cjs/vite.config.js b/playground/css-codesplit-cjs/vite.config.js index 85a7a0f07eff14..7646d17279e514 100644 --- a/playground/css-codesplit-cjs/vite.config.js +++ b/playground/css-codesplit-cjs/vite.config.js @@ -7,14 +7,14 @@ module.exports = { rollupOptions: { input: { main: resolve(__dirname, './index.html'), - other: resolve(__dirname, './other.js') + other: resolve(__dirname, './other.js'), }, treeshake: false, output: { format: 'cjs', freeze: false, - externalLiveBindings: false - } - } - } + externalLiveBindings: false, + }, + }, + }, } diff --git a/playground/css-codesplit/main.js b/playground/css-codesplit/main.js index eb6e703f79e718..6b9e3344c15033 100644 --- a/playground/css-codesplit/main.js +++ b/playground/css-codesplit/main.js @@ -9,7 +9,7 @@ import('./inline.css?inline').then((css) => { import('./mod.module.css').then((css) => { document.querySelector('.dynamic-module').textContent = JSON.stringify( - css.default + css.default, ) document.querySelector('.mod').classList.add(css.default.mod) }) diff --git a/playground/css-codesplit/vite.config.js b/playground/css-codesplit/vite.config.js index 0bc9cab5d025df..7f493850ff10d5 100644 --- a/playground/css-codesplit/vite.config.js +++ b/playground/css-codesplit/vite.config.js @@ -6,8 +6,8 @@ module.exports = { rollupOptions: { input: { main: resolve(__dirname, './index.html'), - other: resolve(__dirname, './other.js') - } - } - } + other: resolve(__dirname, './other.js'), + }, + }, + }, } diff --git a/playground/css-dynamic-import/__tests__/css-dynamic-import.spec.ts b/playground/css-dynamic-import/__tests__/css-dynamic-import.spec.ts index 0dbd34742d53df..c4c79291469050 100644 --- a/playground/css-dynamic-import/__tests__/css-dynamic-import.spec.ts +++ b/playground/css-dynamic-import/__tests__/css-dynamic-import.spec.ts @@ -5,7 +5,7 @@ import { getColor, isBuild, isServe, page, ports, rootDir } from '~utils' const baseOptions = [ { base: '', label: 'relative' }, - { base: '/', label: 'absolute' } + { base: '/', label: 'absolute' }, ] const getConfig = (base: string): InlineConfig => ({ @@ -13,7 +13,7 @@ const getConfig = (base: string): InlineConfig => ({ root: rootDir, logLevel: 'silent', preview: { port: ports['css/dynamic-import'] }, - build: { assetsInlineLimit: 0 } + build: { assetsInlineLimit: 0 }, }) async function withBuild(base: string, fn: () => Promise) { @@ -50,9 +50,9 @@ async function getLinks() { return handle.evaluate((link) => ({ pathname: new URL(link.href).pathname, rel: link.rel, - as: link.as + as: link.as, })) - }) + }), ) } @@ -68,37 +68,37 @@ baseOptions.forEach(({ base, label }) => { { pathname: expect.stringMatching(/^\/assets\/index-.+\.css$/), rel: 'stylesheet', - as: '' + as: '', }, { pathname: expect.stringMatching(/^\/assets\/dynamic-.+\.css$/), rel: 'preload', - as: 'style' + as: 'style', }, { pathname: expect.stringMatching(/^\/assets\/dynamic-.+\.js$/), rel: 'modulepreload', - as: 'script' + as: 'script', }, { pathname: expect.stringMatching(/^\/assets\/dynamic-.+\.css$/), rel: 'stylesheet', - as: '' + as: '', }, { pathname: expect.stringMatching(/^\/assets\/static-.+\.js$/), rel: 'modulepreload', - as: 'script' + as: 'script', }, { pathname: expect.stringMatching(/^\/assets\/index-.+\.js$/), rel: 'modulepreload', - as: 'script' - } + as: 'script', + }, ]) }) }, - { retry: 3 } + { retry: 3 }, ) test.runIf(isServe)( @@ -113,11 +113,11 @@ baseOptions.forEach(({ base, label }) => { { pathname: '/dynamic.css', rel: 'preload', - as: 'style' - } + as: 'style', + }, ]) }) }, - { retry: 3 } + { retry: 3 }, ) }) diff --git a/playground/css-dynamic-import/__tests__/serve.ts b/playground/css-dynamic-import/__tests__/serve.ts index ae33c33a5db107..48f55eee4f48ec 100644 --- a/playground/css-dynamic-import/__tests__/serve.ts +++ b/playground/css-dynamic-import/__tests__/serve.ts @@ -5,6 +5,6 @@ // function or a default server will be created export async function serve() { return { - close: () => Promise.resolve() + close: () => Promise.resolve(), } } diff --git a/playground/css-sourcemap/__tests__/css-sourcemap.spec.ts b/playground/css-sourcemap/__tests__/css-sourcemap.spec.ts index 4b2331e8836d4c..a6f89f8457dc96 100644 --- a/playground/css-sourcemap/__tests__/css-sourcemap.spec.ts +++ b/playground/css-sourcemap/__tests__/css-sourcemap.spec.ts @@ -6,7 +6,7 @@ import { isBuild, isServe, page, - serverLogs + serverLogs, } from '~utils' test.runIf(isBuild)('should not output sourcemap warning (#4939)', () => { @@ -32,9 +32,9 @@ describe.runIf(isServe)('serve', () => { new URL('./linked.css', page.url()).href, { headers: { - accept: 'text/css' - } - } + accept: 'text/css', + }, + }, ) const css = await res.text() const map = extractSourcemap(css) @@ -60,9 +60,9 @@ describe.runIf(isServe)('serve', () => { new URL('./linked-with-import.css', page.url()).href, { headers: { - accept: 'text/css' - } - } + accept: 'text/css', + }, + }, ) const css = await res.text() const map = extractSourcemap(css) @@ -94,12 +94,12 @@ describe.runIf(isServe)('serve', () => { 'js .css request does not include sourcemap', async () => { const res = await page.request.get( - new URL('./linked-with-import.css', page.url()).href + new URL('./linked-with-import.css', page.url()).href, ) const content = await res.text() const lines = content.trim().split('\n') expect(lines[lines.length - 1]).not.toMatch(/^\/\/#/) - } + }, ) test('imported css', async () => { diff --git a/playground/css-sourcemap/vite.config.js b/playground/css-sourcemap/vite.config.js index 4fbeaa9a13aeb0..64067165873701 100644 --- a/playground/css-sourcemap/vite.config.js +++ b/playground/css-sourcemap/vite.config.js @@ -6,14 +6,14 @@ const MagicString = require('magic-string') module.exports = { resolve: { alias: { - '@': __dirname - } + '@': __dirname, + }, }, css: { devSourcemap: true, preprocessorOptions: { less: { - additionalData: '@color: red;' + additionalData: '@color: red;', }, styl: { additionalData: (content, filename) => { @@ -29,14 +29,14 @@ module.exports = { return { content: ms.toString(), - map + map, } - } - } - } + }, + }, + }, }, build: { - sourcemap: true + sourcemap: true, }, plugins: [ { @@ -46,7 +46,7 @@ module.exports = { if (req.url === '/virtual.html') { const t = await server.transformIndexHtml( '/virtual.html', - '

virtual html

' + '

virtual html

', ) res.setHeader('Content-Type', 'text/html') res.statusCode = 200 @@ -55,7 +55,7 @@ module.exports = { } next() }) - } - } - ] + }, + }, + ], } diff --git a/playground/css/__tests__/css.spec.ts b/playground/css/__tests__/css.spec.ts index 7f87c0b73aa606..77878820eab415 100644 --- a/playground/css/__tests__/css.spec.ts +++ b/playground/css/__tests__/css.spec.ts @@ -11,7 +11,7 @@ import { serverLogs, untilUpdated, viteTestUrl, - withRetry + withRetry, } from '~utils' // note: tests should retrieve the element at the beginning of test and reuse it @@ -42,7 +42,7 @@ test('linked css', async () => { await untilUpdated(() => getColor(linked), 'red') editFile('linked-at-import.css', (code) => - code.replace('color: red', 'color: blue') + code.replace('color: red', 'color: blue'), ) await untilUpdated(() => getColor(atImport), 'blue') }) @@ -58,7 +58,7 @@ test('css import from js', async () => { await untilUpdated(() => getColor(imported), 'red') editFile('imported-at-import.css', (code) => - code.replace('color: purple', 'color: blue') + code.replace('color: purple', 'color: blue'), ) await untilUpdated(() => getColor(atImport), 'blue') }) @@ -89,25 +89,25 @@ test('sass', async () => { expect(await getBg(atImport)).toMatch(isBuild ? /base64/ : '/nested/icon.png') expect(await getColor(atImportAlias)).toBe('olive') expect(await getBg(atImportAlias)).toMatch( - isBuild ? /base64/ : '/nested/icon.png' + isBuild ? /base64/ : '/nested/icon.png', ) expect(await getBg(urlStartsWithVariable)).toMatch( - isBuild ? /ok-\w+\.png/ : `${viteTestUrl}/ok.png` + isBuild ? /ok-\w+\.png/ : `${viteTestUrl}/ok.png`, ) expect(await getColor(partialImport)).toBe('orchid') editFile('sass.scss', (code) => - code.replace('color: $injectedColor', 'color: red') + code.replace('color: $injectedColor', 'color: red'), ) await untilUpdated(() => getColor(imported), 'red') editFile('nested/_index.scss', (code) => - code.replace('color: olive', 'color: blue') + code.replace('color: olive', 'color: blue'), ) await untilUpdated(() => getColor(atImport), 'blue') editFile('nested/_partial.scss', (code) => - code.replace('color: orchid', 'color: green') + code.replace('color: orchid', 'color: green'), ) await untilUpdated(() => getColor(partialImport), 'green') }) @@ -123,17 +123,17 @@ test('less', async () => { expect(await getBg(atImport)).toMatch(isBuild ? /base64/ : '/nested/icon.png') expect(await getColor(atImportAlias)).toBe('darkslateblue') expect(await getBg(atImportAlias)).toMatch( - isBuild ? /base64/ : '/nested/icon.png' + isBuild ? /base64/ : '/nested/icon.png', ) expect(await getBg(urlStartsWithVariable)).toMatch( - isBuild ? /ok-\w+\.png/ : `${viteTestUrl}/ok.png` + isBuild ? /ok-\w+\.png/ : `${viteTestUrl}/ok.png`, ) editFile('less.less', (code) => code.replace('@color: blue', '@color: red')) await untilUpdated(() => getColor(imported), 'red') editFile('nested/nested.less', (code) => - code.replace('color: darkslateblue', 'color: blue') + code.replace('color: darkslateblue', 'color: blue'), ) await untilUpdated(() => getColor(atImport), 'blue') }) @@ -151,18 +151,18 @@ test('stylus', async () => { expect(await getColor(relativeImport)).toBe('darkslateblue') expect(await getColor(relativeImportAlias)).toBe('darkslateblue') expect(await getBg(relativeImportAlias)).toMatch( - isBuild ? /base64/ : '/nested/icon.png' + isBuild ? /base64/ : '/nested/icon.png', ) expect(await getColor(optionsRelativeImport)).toBe('green') expect(await getColor(optionsAbsoluteImport)).toBe('red') editFile('stylus.styl', (code) => - code.replace('$color ?= blue', '$color ?= red') + code.replace('$color ?= blue', '$color ?= red'), ) await untilUpdated(() => getColor(imported), 'red') editFile('nested/nested.styl', (code) => - code.replace('color: darkslateblue', 'color: blue') + code.replace('color: darkslateblue', 'color: blue'), ) await untilUpdated(() => getColor(relativeImport), 'blue') }) @@ -174,11 +174,11 @@ test('css modules', async () => { // check if the generated CSS module class name is indeed using the // format specified in vite.config.js expect(await imported.getAttribute('class')).toMatch( - /.mod-module__apply-color___[\w-]{5}/ + /.mod-module__apply-color___[\w-]{5}/, ) editFile('mod.module.css', (code) => - code.replace('color: turquoise', 'color: red') + code.replace('color: turquoise', 'color: red'), ) await untilUpdated(() => getColor(imported), 'red') }) @@ -190,11 +190,11 @@ test('css modules composes/from path resolving', async () => { // check if the generated CSS module class name is indeed using the // format specified in vite.config.js expect(await imported.getAttribute('class')).toMatch( - /.composed-module__apply-color___[\w-]{5}/ + /.composed-module__apply-color___[\w-]{5}/, ) expect(await imported.getAttribute('class')).toMatch( - /.composes-path-resolving-module__path-resolving-css___[\w-]{5}/ + /.composes-path-resolving-module__path-resolving-css___[\w-]{5}/, ) // @todo HMR is not working on this situation. @@ -211,11 +211,11 @@ test('sass modules composes/from path resolving', async () => { // check if the generated CSS module class name is indeed using the // format specified in vite.config.js expect(await imported.getAttribute('class')).toMatch( - /.composed-module__apply-color___[\w-]{5}/ + /.composed-module__apply-color___[\w-]{5}/, ) expect(await imported.getAttribute('class')).toMatch( - /.composes-path-resolving-module__path-resolving-sass___[\w-]{5}/ + /.composes-path-resolving-module__path-resolving-sass___[\w-]{5}/, ) // @todo HMR is not working on this situation. @@ -232,11 +232,11 @@ test('less modules composes/from path resolving', async () => { // check if the generated CSS module class name is indeed using the // format specified in vite.config.js expect(await imported.getAttribute('class')).toMatch( - /.composed-module__apply-color___[\w-]{5}/ + /.composed-module__apply-color___[\w-]{5}/, ) expect(await imported.getAttribute('class')).toMatch( - /.composes-path-resolving-module__path-resolving-less___[\w-]{5}/ + /.composes-path-resolving-module__path-resolving-less___[\w-]{5}/, ) // @todo HMR is not working on this situation. @@ -250,11 +250,11 @@ test('css modules w/ sass', async () => { const imported = await page.$('.modules-sass') expect(await getColor(imported)).toBe('orangered') expect(await imported.getAttribute('class')).toMatch( - /.mod-module__apply-color___[\w-]{5}/ + /.mod-module__apply-color___[\w-]{5}/, ) editFile('mod.module.scss', (code) => - code.replace('color: orangered', 'color: blue') + code.replace('color: orangered', 'color: blue'), ) await untilUpdated(() => getColor(imported), 'blue') }) @@ -314,7 +314,7 @@ test('treeshaken async chunk', async () => { expect( await page.evaluate(() => { return document.querySelector('.async-treeshaken') - }) + }), ).toBeNull() // assert that the css is not present anywhere expect(findAssetFile(/\.css$/)).not.toMatch('plum') @@ -326,7 +326,7 @@ test('treeshaken async chunk', async () => { // should be present in dev const el = await page.$('.async-treeshaken') editFile('async-treeshaken.css', (code) => - code.replace('color: plum', 'color: blue') + code.replace('color: plum', 'color: blue'), ) await untilUpdated(() => getColor(el), 'blue') } @@ -343,19 +343,19 @@ test('PostCSS dir-dependency', async () => { if (!isBuild) { editFile('glob-dep/foo.css', (code) => - code.replace('color: grey', 'color: blue') + code.replace('color: grey', 'color: blue'), ) await untilUpdated(() => getColor(el1), 'blue') expect(await getColor(el2)).toBe('grey') editFile('glob-dep/bar.css', (code) => - code.replace('color: grey', 'color: red') + code.replace('color: grey', 'color: red'), ) await untilUpdated(() => getColor(el2), 'red') expect(await getColor(el1)).toBe('blue') editFile('glob-dep/nested (dir)/baz.css', (code) => - code.replace('color: grey', 'color: green') + code.replace('color: grey', 'color: green'), ) await untilUpdated(() => getColor(el3), 'green') expect(await getColor(el1)).toBe('blue') @@ -379,8 +379,9 @@ test('URL separation', async () => { .fill('') .flatMap((_, i) => [',', ' ,', ', ', ' , '].map( - (sep) => `background-image:${new Array(i + 1).fill(baseUrl).join(sep)};` - ) + (sep) => + `background-image:${new Array(i + 1).fill(baseUrl).join(sep)};`, + ), ) // Insert the base case @@ -391,7 +392,7 @@ test('URL separation', async () => { if (i > 0) editFile('imported.css', (code) => code.replace(cases[i - 1], c)) expect(await getBg(urlSeparated)).toMatch( - /^url\(.+\)(?:\s*,\s*url\(.+\))*$/ + /^url\(.+\)(?:\s*,\s*url\(.+\))*$/, ) } }) @@ -427,7 +428,7 @@ test('?raw', async () => { const rawImportCss = await page.$('.raw-imported-css') expect(await rawImportCss.textContent()).toBe( - readFileSync(require.resolve('../raw-imported.css'), 'utf-8') + readFileSync(require.resolve('../raw-imported.css'), 'utf-8'), ) }) @@ -440,7 +441,7 @@ test("relative path rewritten in Less's data-uri", async () => { // relative path passed to Less's data-uri is rewritten to absolute, // the Less inlines it expect(await getBg('.form-box-data-uri')).toMatch( - /^url\("data:image\/svg\+xml,%3Csvg/ + /^url\("data:image\/svg\+xml,%3Csvg/, ) }) @@ -450,7 +451,7 @@ test('PostCSS source.input.from includes query', async () => { expect(code).toContain( isBuild ? '/postcss-source-input.css?used&query=foo' - : '/postcss-source-input.css?query=foo' + : '/postcss-source-input.css?query=foo', ) }) @@ -478,14 +479,14 @@ test('sugarss', async () => { expect(await getBg(atImport)).toMatch(isBuild ? /base64/ : '/nested/icon.png') expect(await getColor(atImportAlias)).toBe('darkslateblue') expect(await getBg(atImportAlias)).toMatch( - isBuild ? /base64/ : '/nested/icon.png' + isBuild ? /base64/ : '/nested/icon.png', ) editFile('sugarss.sss', (code) => code.replace('color: blue', 'color: coral')) await untilUpdated(() => getColor(imported), 'coral') editFile('nested/nested.sss', (code) => - code.replace('color: darkslateblue', 'color: blue') + code.replace('color: darkslateblue', 'color: blue'), ) await untilUpdated(() => getColor(atImport), 'blue') }) diff --git a/playground/css/__tests__/postcss-plugins-different-dir/postcss-plugins-different-dir.spec.ts b/playground/css/__tests__/postcss-plugins-different-dir/postcss-plugins-different-dir.spec.ts index fabf24da3dae99..f897d0fad2e234 100644 --- a/playground/css/__tests__/postcss-plugins-different-dir/postcss-plugins-different-dir.spec.ts +++ b/playground/css/__tests__/postcss-plugins-different-dir/postcss-plugins-different-dir.spec.ts @@ -11,12 +11,12 @@ test('postcss plugins in different dir', async () => { logLevel: 'silent', server: { port, - strictPort: true + strictPort: true, }, build: { // skip transpilation during tests to make it faster - target: 'esnext' - } + target: 'esnext', + }, }) await server.listen() try { diff --git a/playground/css/__tests__/postcss-plugins-different-dir/serve.ts b/playground/css/__tests__/postcss-plugins-different-dir/serve.ts index 16e7d655f5ec15..195bb47d8520c7 100644 --- a/playground/css/__tests__/postcss-plugins-different-dir/serve.ts +++ b/playground/css/__tests__/postcss-plugins-different-dir/serve.ts @@ -5,6 +5,6 @@ // function or a default server will be created export async function serve(): Promise<{ close(): Promise }> { return { - close: () => Promise.resolve() + close: () => Promise.resolve(), } } diff --git a/playground/css/main.js b/playground/css/main.js index 8af0e8355db719..5a2b726c1b7e92 100644 --- a/playground/css/main.js +++ b/playground/css/main.js @@ -31,7 +31,7 @@ document .classList.add(...composesPathResolvingMod['path-resolving-less'].split(' ')) text( '.path-resolved-modules-code', - JSON.stringify(composesPathResolvingMod, null, 2) + JSON.stringify(composesPathResolvingMod, null, 2), ) import inlineMod from './inline.module.css?inline' @@ -85,7 +85,7 @@ text('.inlined-code', inlined) // glob const glob = import.meta.glob('./glob-import/*.css', { query: '?inline' }) Promise.all( - Object.keys(glob).map((key) => glob[key]().then((i) => i.default)) + Object.keys(glob).map((key) => glob[key]().then((i) => i.default)), ).then((res) => { text('.imported-css-glob', JSON.stringify(res, null, 2)) }) @@ -93,7 +93,7 @@ Promise.all( // globEager const globEager = import.meta.glob('./glob-import/*.css', { eager: true, - query: '?inline' + query: '?inline', }) text('.imported-css-globEager', JSON.stringify(globEager, null, 2)) diff --git a/playground/css/postcss-caching/blue-app/postcss.config.js b/playground/css/postcss-caching/blue-app/postcss.config.js index 2506cd535feef7..50764f3ff8f21a 100644 --- a/playground/css/postcss-caching/blue-app/postcss.config.js +++ b/playground/css/postcss-caching/blue-app/postcss.config.js @@ -1,5 +1,5 @@ module.exports = { - plugins: [replacePinkWithBlue] + plugins: [replacePinkWithBlue], } function replacePinkWithBlue() { @@ -9,7 +9,7 @@ function replacePinkWithBlue() { if (decl.value === 'pink') { decl.value = 'blue' } - } + }, } } replacePinkWithBlue.postcss = true diff --git a/playground/css/postcss-caching/css.spec.ts b/playground/css/postcss-caching/css.spec.ts index c32bf6b6251d2d..101b9691bef45f 100644 --- a/playground/css/postcss-caching/css.spec.ts +++ b/playground/css/postcss-caching/css.spec.ts @@ -11,12 +11,12 @@ test('postcss config', async () => { logLevel: 'silent', server: { port, - strictPort: true + strictPort: true, }, build: { // skip transpilation during tests to make it faster - target: 'esnext' - } + target: 'esnext', + }, }) await server.listen() return server diff --git a/playground/css/postcss-caching/green-app/postcss.config.js b/playground/css/postcss-caching/green-app/postcss.config.js index 1367dfc1d27c7b..7d9d8818540e09 100644 --- a/playground/css/postcss-caching/green-app/postcss.config.js +++ b/playground/css/postcss-caching/green-app/postcss.config.js @@ -1,5 +1,5 @@ module.exports = { - plugins: [replacePinkWithGreen] + plugins: [replacePinkWithGreen], } function replacePinkWithGreen() { @@ -9,7 +9,7 @@ function replacePinkWithGreen() { if (decl.value === 'pink') { decl.value = 'green' } - } + }, } } replacePinkWithGreen.postcss = true diff --git a/playground/css/postcss-caching/serve.ts b/playground/css/postcss-caching/serve.ts index 16e7d655f5ec15..195bb47d8520c7 100644 --- a/playground/css/postcss-caching/serve.ts +++ b/playground/css/postcss-caching/serve.ts @@ -5,6 +5,6 @@ // function or a default server will be created export async function serve(): Promise<{ close(): Promise }> { return { - close: () => Promise.resolve() + close: () => Promise.resolve(), } } diff --git a/playground/css/postcss.config.js b/playground/css/postcss.config.js index a9bbd0f2b4e09e..955878ac216f53 100644 --- a/playground/css/postcss.config.js +++ b/playground/css/postcss.config.js @@ -1,5 +1,5 @@ module.exports = { - plugins: [require('postcss-nested'), testDirDep, testSourceInput] + plugins: [require('postcss-nested'), testDirDep, testSourceInput], } const fs = require('node:fs') @@ -16,7 +16,7 @@ function testDirDep() { AtRule(atRule, { result, Comment }) { if (atRule.name === 'test') { const pattern = normalizePath( - path.resolve(path.dirname(result.opts.from), './glob-dep/**/*.css') + path.resolve(path.dirname(result.opts.from), './glob-dep/**/*.css'), ) const files = glob.sync(pattern) const text = files.map((f) => fs.readFileSync(f, 'utf-8')).join('\n') @@ -28,7 +28,7 @@ function testDirDep() { plugin: 'dir-dep', dir: './glob-dep', glob: '*.css', - parent: result.opts.from + parent: result.opts.from, }) result.messages.push({ @@ -36,10 +36,10 @@ function testDirDep() { plugin: 'dir-dep', dir: './glob-dep/nested (dir)', // includes special characters in glob glob: '*.css', - parent: result.opts.from + parent: result.opts.from, }) } - } + }, } } testDirDep.postcss = true @@ -51,12 +51,12 @@ function testSourceInput() { if (atRule.name === 'source-input') { atRule.after( `.source-input::before { content: ${JSON.stringify( - atRule.source.input.from - )}; }` + atRule.source.input.from, + )}; }`, ) atRule.remove() } - } + }, } } testSourceInput.postcss = true diff --git a/playground/css/vite.config-relative-base.js b/playground/css/vite.config-relative-base.js index 7b54a149bcd987..7edbaf07c95c29 100644 --- a/playground/css/vite.config-relative-base.js +++ b/playground/css/vite.config-relative-base.js @@ -16,11 +16,11 @@ module.exports = { output: { entryFileNames: 'entries/[name].js', chunkFileNames: 'chunks/[name]-[hash].js', - assetFileNames: 'other-assets/[name]-[hash][extname]' - } - } + assetFileNames: 'other-assets/[name]-[hash][extname]', + }, + }, }, testConfig: { - baseRoute: '/relative-base/' - } + baseRoute: '/relative-base/', + }, } diff --git a/playground/css/vite.config.js b/playground/css/vite.config.js index 2435f7c0772bcd..489752655c828f 100644 --- a/playground/css/vite.config.js +++ b/playground/css/vite.config.js @@ -10,24 +10,24 @@ globalThis.location = new URL('http://localhost/') */ module.exports = { build: { - cssTarget: 'chrome61' + cssTarget: 'chrome61', }, esbuild: { logOverride: { - 'unsupported-css-property': 'silent' - } + 'unsupported-css-property': 'silent', + }, }, resolve: { alias: { '=': __dirname, spacefolder: __dirname + '/folder with space', '#alias': __dirname + '/aliased/foo.css', - '#alias-module': __dirname + '/aliased/bar.module.css' - } + '#alias-module': __dirname + '/aliased/bar.module.css', + }, }, css: { modules: { - generateScopedName: '[name]__[local]___[hash:base64:5]' + generateScopedName: '[name]__[local]___[hash:base64:5]', // example of how getJSON can be used to generate // typescript typings for css modules class names @@ -56,16 +56,16 @@ module.exports = { }, function (url) { return url.endsWith('.wxss') ? { contents: '' } : null - } - ] + }, + ], }, styl: { additionalData: `$injectedColor ?= orange`, imports: [ './options/relative-import.styl', - path.join(__dirname, 'options/absolute-import.styl') - ] - } - } - } + path.join(__dirname, 'options/absolute-import.styl'), + ], + }, + }, + }, } diff --git a/playground/define/__tests__/define.spec.ts b/playground/define/__tests__/define.spec.ts index 8c27686bce1703..7b1e306d973341 100644 --- a/playground/define/__tests__/define.spec.ts +++ b/playground/define/__tests__/define.spec.ts @@ -6,35 +6,35 @@ test('string', async () => { const defines = viteConfig.define expect(await page.textContent('.exp')).toBe( - String(typeof eval(defines.__EXP__)) + String(typeof eval(defines.__EXP__)), ) expect(await page.textContent('.string')).toBe(JSON.parse(defines.__STRING__)) expect(await page.textContent('.number')).toBe(String(defines.__NUMBER__)) expect(await page.textContent('.boolean')).toBe(String(defines.__BOOLEAN__)) expect(await page.textContent('.object')).toBe( - JSON.stringify(defines.__OBJ__, null, 2) + JSON.stringify(defines.__OBJ__, null, 2), ) expect(await page.textContent('.process-node-env')).toBe( - JSON.parse(defines['process.env.NODE_ENV']) + JSON.parse(defines['process.env.NODE_ENV']), ) expect(await page.textContent('.env-var')).toBe( - JSON.parse(defines['process.env.SOMEVAR']) + JSON.parse(defines['process.env.SOMEVAR']), ) expect(await page.textContent('.process-as-property')).toBe( - defines.__OBJ__.process.env.SOMEVAR + defines.__OBJ__.process.env.SOMEVAR, ) expect(await page.textContent('.spread-object')).toBe( - JSON.stringify({ SOMEVAR: defines['process.env.SOMEVAR'] }) + JSON.stringify({ SOMEVAR: defines['process.env.SOMEVAR'] }), ) expect(await page.textContent('.spread-array')).toBe( - JSON.stringify([...defines.__STRING__]) + JSON.stringify([...defines.__STRING__]), ) expect(await page.textContent('.dollar-identifier')).toBe( - String(defines.$DOLLAR) + String(defines.$DOLLAR), ) expect(await page.textContent('.unicode-identifier')).toBe( - String(defines.ÖUNICODE_LETTERɵ) + String(defines.ÖUNICODE_LETTERɵ), ) expect(await page.textContent('.no-identifier-substring')).toBe(String(true)) expect(await page.textContent('.no-property')).toBe(String(true)) @@ -42,12 +42,12 @@ test('string', async () => { expect(await page.textContent('.exp-define')).toBe('__EXP__') expect(await page.textContent('.import-json')).toBe('__EXP__') expect(await page.textContent('.define-in-dep')).toBe( - defines.__STRINGIFIED_OBJ__ + defines.__STRINGIFIED_OBJ__, ) expect(await page.textContent('.import-meta-env-undefined')).toBe( - isBuild ? '({}).UNDEFINED' : 'import.meta.env.UNDEFINED' + isBuild ? '({}).UNDEFINED' : 'import.meta.env.UNDEFINED', ) expect(await page.textContent('.process-env-undefined')).toBe( - isBuild ? '({}).UNDEFINED' : 'process.env.UNDEFINED' + isBuild ? '({}).UNDEFINED' : 'process.env.UNDEFINED', ) }) diff --git a/playground/define/commonjs-dep/index.js b/playground/define/commonjs-dep/index.js index 9be5641e04b844..ba630bf28ff6d5 100644 --- a/playground/define/commonjs-dep/index.js +++ b/playground/define/commonjs-dep/index.js @@ -1,5 +1,5 @@ module.exports = { defined: __STRINGIFIED_OBJ__, importMetaEnvUndefined: 'import.meta.env.UNDEFINED', - processEnvUndefined: 'process.env.UNDEFINED' + processEnvUndefined: 'process.env.UNDEFINED', } diff --git a/playground/define/index.html b/playground/define/index.html index 06b2f4f9479d38..7d81d42d8966a1 100644 --- a/playground/define/index.html +++ b/playground/define/index.html @@ -35,8 +35,8 @@

Define

text( '.spread-object', JSON.stringify({ - ...(process.env.SOMEVAR ? { SOMEVAR: `"${process.env.SOMEVAR}"` } : {}) - }) + ...(process.env.SOMEVAR ? { SOMEVAR: `"${process.env.SOMEVAR}"` } : {}), + }), ) text('.spread-array', JSON.stringify([...`"${__STRING__}"`])) text('.dollar-identifier', $DOLLAR) diff --git a/playground/define/vite.config.js b/playground/define/vite.config.js index 7650603e046419..41cb419d03b38f 100644 --- a/playground/define/vite.config.js +++ b/playground/define/vite.config.js @@ -7,19 +7,19 @@ module.exports = { __OBJ__: { foo: 1, bar: { - baz: 2 + baz: 2, }, process: { env: { - SOMEVAR: '"PROCESS MAY BE PROPERTY"' - } - } + SOMEVAR: '"PROCESS MAY BE PROPERTY"', + }, + }, }, 'process.env.NODE_ENV': '"dev"', 'process.env.SOMEVAR': '"SOMEVAR"', $DOLLAR: 456, ÖUNICODE_LETTERɵ: 789, __VAR_NAME__: false, - __STRINGIFIED_OBJ__: JSON.stringify({ foo: true }) - } + __STRINGIFIED_OBJ__: JSON.stringify({ foo: true }), + }, } diff --git a/playground/dynamic-import/__tests__/dynamic-import.spec.ts b/playground/dynamic-import/__tests__/dynamic-import.spec.ts index 8b599462470d18..6748c9078ec627 100644 --- a/playground/dynamic-import/__tests__/dynamic-import.spec.ts +++ b/playground/dynamic-import/__tests__/dynamic-import.spec.ts @@ -11,7 +11,7 @@ test('should load full dynamic import from public', async () => { await untilUpdated(() => page.textContent('.view'), 'Qux view', true) // No warning should be logged as we are using @vite-ignore expect( - serverLogs.some((log) => log.includes('cannot be analyzed by vite')) + serverLogs.some((log) => log.includes('cannot be analyzed by vite')), ).toBe(false) }) @@ -57,7 +57,7 @@ test('should load dynamic import with css', async () => { await untilUpdated( () => page.$eval('.view', (node) => window.getComputedStyle(node).color), 'rgb(255, 0, 0)', - true + true, ) }) @@ -65,7 +65,7 @@ test('should load dynamic import with vars', async () => { await untilUpdated( () => page.textContent('.dynamic-import-with-vars'), 'hello', - true + true, ) }) @@ -73,7 +73,7 @@ test('should load dynamic import with vars multiline', async () => { await untilUpdated( () => page.textContent('.dynamic-import-with-vars'), 'hello', - true + true, ) }) @@ -81,7 +81,7 @@ test('should load dynamic import with vars alias', async () => { await untilUpdated( () => page.textContent('.dynamic-import-with-vars-alias'), 'hi', - true + true, ) }) @@ -89,7 +89,7 @@ test('should load dynamic import with vars raw', async () => { await untilUpdated( () => page.textContent('.dynamic-import-with-vars-raw'), 'export function hello()', - true + true, ) }) @@ -97,7 +97,7 @@ test('should load dynamic import with vars url', async () => { await untilUpdated( () => page.textContent('.dynamic-import-with-vars-url'), isBuild ? 'data:application/javascript' : '/alias/url.js', - true + true, ) }) @@ -105,7 +105,7 @@ test('should load dynamic import with vars worker', async () => { await untilUpdated( () => page.textContent('.dynamic-import-with-vars-worker'), 'load worker', - true + true, ) }) @@ -118,7 +118,7 @@ test('should work with load ../ and itself directory', async () => { await untilUpdated( () => page.textContent('.dynamic-import-self'), 'dynamic-import-self-content', - true + true, ) }) @@ -126,6 +126,6 @@ test('should work with load ../ and contain itself directory', async () => { await untilUpdated( () => page.textContent('.dynamic-import-nested-self'), 'dynamic-import-nested-self-content', - true + true, ) }) diff --git a/playground/dynamic-import/alias/worker.js b/playground/dynamic-import/alias/worker.js index 6206a6536b8064..2a8fc242aab315 100644 --- a/playground/dynamic-import/alias/worker.js +++ b/playground/dynamic-import/alias/worker.js @@ -1,5 +1,5 @@ self.onmessage = (event) => { self.postMessage({ - msg: 'load worker' + msg: 'load worker', }) } diff --git a/playground/dynamic-import/nested/index.js b/playground/dynamic-import/nested/index.js index dc4992abc85021..054801f451a85f 100644 --- a/playground/dynamic-import/nested/index.js +++ b/playground/dynamic-import/nested/index.js @@ -57,7 +57,7 @@ document.querySelector('.issue-2658-1').addEventListener('click', async () => { // data URLs (`data:`) const code2 = 'export const msg = "data";' const dataURL = `data:text/javascript;charset=utf-8,${encodeURIComponent( - code2 + code2, )}` document.querySelector('.issue-2658-2').addEventListener('click', async () => { const { msg } = await import(/*@vite-ignore*/ dataURL) diff --git a/playground/dynamic-import/vite.config.js b/playground/dynamic-import/vite.config.js index f3b7cb1dd049ce..f9f231a1a335cb 100644 --- a/playground/dynamic-import/vite.config.js +++ b/playground/dynamic-import/vite.config.js @@ -11,25 +11,25 @@ module.exports = vite.defineConfig({ fs.mkdirSync(path.resolve(__dirname, 'dist/files')) fs.copyFileSync( path.resolve(__dirname, 'views/qux.js'), - path.resolve(__dirname, 'dist/views/qux.js') + path.resolve(__dirname, 'dist/views/qux.js'), ) fs.copyFileSync( path.resolve(__dirname, 'files/mxd.js'), - path.resolve(__dirname, 'dist/files/mxd.js') + path.resolve(__dirname, 'dist/files/mxd.js'), ) fs.copyFileSync( path.resolve(__dirname, 'files/mxd.json'), - path.resolve(__dirname, 'dist/files/mxd.json') + path.resolve(__dirname, 'dist/files/mxd.json'), ) - } - } + }, + }, ], resolve: { alias: { - '@': path.resolve(__dirname, 'alias') - } + '@': path.resolve(__dirname, 'alias'), + }, }, build: { - sourcemap: true - } + sourcemap: true, + }, }) diff --git a/playground/env-nested/vite.config.js b/playground/env-nested/vite.config.js index 0e46100698650d..8f85449e41e4de 100644 --- a/playground/env-nested/vite.config.js +++ b/playground/env-nested/vite.config.js @@ -1,5 +1,5 @@ const { defineConfig } = require('vite') module.exports = defineConfig({ - envDir: './envs' + envDir: './envs', }) diff --git a/playground/env/__tests__/env.spec.ts b/playground/env/__tests__/env.spec.ts index ee05fff1d3736c..227f6b5c09ccfe 100644 --- a/playground/env/__tests__/env.spec.ts +++ b/playground/env/__tests__/env.spec.ts @@ -33,7 +33,7 @@ test('mode file override', async () => { test('inline variables', async () => { expect(await page.textContent('.inline')).toBe( - isBuild ? `inline-build` : `inline-serve` + isBuild ? `inline-build` : `inline-serve`, ) }) @@ -58,7 +58,7 @@ test('env object', async () => { BASE_URL: '/env/', MODE: mode, DEV: !isBuild, - PROD: isBuild + PROD: isBuild, }) }) diff --git a/playground/env/vite.config.js b/playground/env/vite.config.js index 51be87cbec43f5..3b2d5e3e7674ab 100644 --- a/playground/env/vite.config.js +++ b/playground/env/vite.config.js @@ -6,9 +6,9 @@ module.exports = defineConfig({ base: '/env/', envPrefix: ['VITE_', 'CUSTOM_PREFIX_'], build: { - outDir: 'dist/env' + outDir: 'dist/env', }, define: { - 'import.meta.env.VITE_BOOL': true - } + 'import.meta.env.VITE_BOOL': true, + }, }) diff --git a/playground/extensions/vite.config.js b/playground/extensions/vite.config.js index 53c744b71d3637..4ed3195b219bff 100644 --- a/playground/extensions/vite.config.js +++ b/playground/extensions/vite.config.js @@ -1,6 +1,6 @@ module.exports = { resolve: { alias: [{ find: 'vue', replacement: 'vue/dist/vue.esm-bundler.js' }], - extensions: ['.js'] - } + extensions: ['.js'], + }, } diff --git a/playground/external/__tests__/external.spec.ts b/playground/external/__tests__/external.spec.ts index 7504b6ae1c293c..30f87291fd31a1 100644 --- a/playground/external/__tests__/external.spec.ts +++ b/playground/external/__tests__/external.spec.ts @@ -3,7 +3,7 @@ import { browserLogs, isBuild, page } from '~utils' test('importmap', () => { expect(browserLogs).not.toContain( - 'An import map is added after module script load was triggered.' + 'An import map is added after module script load was triggered.', ) }) diff --git a/playground/external/vite.config.js b/playground/external/vite.config.js index 1e38f9f65a18b5..14259ecde860b0 100644 --- a/playground/external/vite.config.js +++ b/playground/external/vite.config.js @@ -3,15 +3,15 @@ import { defineConfig } from 'vite' export default defineConfig({ optimizeDeps: { include: ['dep-that-imports', 'dep-that-requires'], - exclude: ['vue', 'slash5'] + exclude: ['vue', 'slash5'], }, build: { minify: false, rollupOptions: { - external: ['vue', 'slash3', 'slash5'] + external: ['vue', 'slash3', 'slash5'], }, commonjsOptions: { - esmExternals: ['vue', 'slash5'] - } - } + esmExternals: ['vue', 'slash5'], + }, + }, }) diff --git a/playground/file-delete-restore/__tests__/file-delete-restore.spec.ts b/playground/file-delete-restore/__tests__/file-delete-restore.spec.ts index 943cabb35da2c2..90887f93461770 100644 --- a/playground/file-delete-restore/__tests__/file-delete-restore.spec.ts +++ b/playground/file-delete-restore/__tests__/file-delete-restore.spec.ts @@ -5,7 +5,7 @@ import { isBuild, page, removeFile, - untilUpdated + untilUpdated, } from '~utils' test.runIf(isBuild)( @@ -14,7 +14,7 @@ test.runIf(isBuild)( await untilUpdated(() => page.textContent('p'), 'Child state 1') editFile('Child.jsx', (code) => - code.replace('Child state 1', 'Child state 2') + code.replace('Child state 1', 'Child state 2'), ) await untilUpdated(() => page.textContent('p'), 'Child state 2') @@ -22,7 +22,7 @@ test.runIf(isBuild)( editFile('App.jsx', (code) => code .replace(`import Child from './Child'`, '') - .replace(``, '

Child deleted

') + .replace(``, '

Child deleted

'), ) removeFile('Child.jsx') await untilUpdated(() => page.textContent('p'), 'Child deleted') @@ -33,7 +33,7 @@ test.runIf(isBuild)( ` export default function Child() { return

Child state 1

} - ` + `, ) // restore App.jsx @@ -52,9 +52,9 @@ test.runIf(isBuild)( } export default App - ` + `, ) await untilUpdated(() => page.textContent('p'), 'Child state 1') - } + }, ) diff --git a/playground/file-delete-restore/index.html b/playground/file-delete-restore/index.html index f0015ceb9829a3..7417c442dfbf36 100644 --- a/playground/file-delete-restore/index.html +++ b/playground/file-delete-restore/index.html @@ -5,6 +5,6 @@ import App from './App.jsx' ReactDOM.createRoot(document.getElementById('app')).render( - React.createElement(App) + React.createElement(App), ) diff --git a/playground/file-delete-restore/vite.config.js b/playground/file-delete-restore/vite.config.js index 51cb5c54bd6821..d47f7cfc6704c5 100644 --- a/playground/file-delete-restore/vite.config.js +++ b/playground/file-delete-restore/vite.config.js @@ -7,6 +7,6 @@ module.exports = { plugins: [react()], build: { // to make tests faster - minify: false - } + minify: false, + }, } diff --git a/playground/fs-serve/__tests__/fs-serve.spec.ts b/playground/fs-serve/__tests__/fs-serve.spec.ts index 90d35d21b04773..eb3475f565b773 100644 --- a/playground/fs-serve/__tests__/fs-serve.spec.ts +++ b/playground/fs-serve/__tests__/fs-serve.spec.ts @@ -30,10 +30,10 @@ describe.runIf(isServe)('main', () => { test('safe fetch with special characters', async () => { expect( - await page.textContent('.safe-fetch-subdir-special-characters') + await page.textContent('.safe-fetch-subdir-special-characters'), ).toMatch('KEY=safe') expect( - await page.textContent('.safe-fetch-subdir-special-characters-status') + await page.textContent('.safe-fetch-subdir-special-characters-status'), ).toBe('200') }) @@ -44,7 +44,7 @@ describe.runIf(isServe)('main', () => { test('unsafe fetch with special characters (#8498)', async () => { expect(await page.textContent('.unsafe-fetch-8498')).toMatch( - '403 Restricted' + '403 Restricted', ) expect(await page.textContent('.unsafe-fetch-8498-status')).toBe('403') }) @@ -66,7 +66,7 @@ describe.runIf(isServe)('main', () => { test('safe fs fetch with special characters', async () => { expect(await page.textContent('.safe-fs-fetch-special-characters')).toBe( - stringified + stringified, ) expect(await page.textContent('.safe-fs-fetch-status')).toBe('200') }) diff --git a/playground/fs-serve/root/src/index.html b/playground/fs-serve/root/src/index.html index 95b31e73d72ea6..9e9cfe501d10fe 100644 --- a/playground/fs-serve/root/src/index.html +++ b/playground/fs-serve/root/src/index.html @@ -177,7 +177,7 @@

Denied

// outside root with special characters 2 #8498 fetch( - '/@fs/' + ROOT + '/root/src/%252e%252e%252f%252e%252e%252funsafe%252ejson' + '/@fs/' + ROOT + '/root/src/%252e%252e%252f%252e%252e%252funsafe%252ejson', ) .then((r) => { text('.unsafe-fs-fetch-8498-2-status', r.status) @@ -191,7 +191,7 @@

Denied

fetch( '/@fs/' + ROOT + - '/root/src/special%20characters%20%C3%A5%C3%A4%C3%B6/safe.json' + '/root/src/special%20characters%20%C3%A5%C3%A4%C3%B6/safe.json', ) .then((r) => { text('.safe-fs-fetch-special-characters-status', r.status) diff --git a/playground/fs-serve/root/vite.config.js b/playground/fs-serve/root/vite.config.js index 12d07754cbf10d..ca7fefd0108870 100644 --- a/playground/fs-serve/root/vite.config.js +++ b/playground/fs-serve/root/vite.config.js @@ -7,28 +7,28 @@ module.exports = { build: { rollupOptions: { input: { - main: path.resolve(__dirname, 'src/index.html') - } - } + main: path.resolve(__dirname, 'src/index.html'), + }, + }, }, server: { fs: { strict: true, - allow: [path.resolve(__dirname, 'src')] + allow: [path.resolve(__dirname, 'src')], }, hmr: { - overlay: false + overlay: false, }, headers: { - 'x-served-by': 'vite' - } + 'x-served-by': 'vite', + }, }, preview: { headers: { - 'x-served-by': 'vite' - } + 'x-served-by': 'vite', + }, }, define: { - ROOT: JSON.stringify(path.dirname(__dirname).replace(/\\/g, '/')) - } + ROOT: JSON.stringify(path.dirname(__dirname).replace(/\\/g, '/')), + }, } diff --git a/playground/glob-import/__tests__/glob-import.spec.ts b/playground/glob-import/__tests__/glob-import.spec.ts index 9a10b2b7bf6892..34b77127cdb1e0 100644 --- a/playground/glob-import/__tests__/glob-import.spec.ts +++ b/playground/glob-import/__tests__/glob-import.spec.ts @@ -12,84 +12,84 @@ import { removeFile, untilBrowserLogAfter, viteTestUrl, - withRetry + withRetry, } from '~utils' const filteredResult = { './alias.js': { - default: 'hi' + default: 'hi', }, './foo.js': { - msg: 'foo' + msg: 'foo', }, "./quote'.js": { - msg: 'single-quote' - } + msg: 'single-quote', + }, } const json = { msg: 'baz', default: { - msg: 'baz' - } + msg: 'baz', + }, } const globWithAlias = { '/dir/alias.js': { - default: 'hi' - } + default: 'hi', + }, } const allResult = { // JSON file should be properly transformed '/dir/alias.js': { - default: 'hi' + default: 'hi', }, '/dir/baz.json': json, '/dir/foo.css': isBuild ? { - default: '.foo{color:#00f}\n' + default: '.foo{color:#00f}\n', } : { - default: '.foo {\n color: blue;\n}\n' + default: '.foo {\n color: blue;\n}\n', }, '/dir/foo.js': { - msg: 'foo' + msg: 'foo', }, '/dir/index.js': isBuild ? { modules: filteredResult, - globWithAlias + globWithAlias, } : { globWithAlias, - modules: filteredResult + modules: filteredResult, }, '/dir/nested/bar.js': { modules: { - '../baz.json': json + '../baz.json': json, }, - msg: 'bar' + msg: 'bar', }, "/dir/quote'.js": { - msg: 'single-quote' - } + msg: 'single-quote', + }, } const nodeModulesResult = { - '/dir/node_modules/hoge.js': { msg: 'hoge' } + '/dir/node_modules/hoge.js': { msg: 'hoge' }, } const rawResult = { '/dir/baz.json': { - msg: 'baz' - } + msg: 'baz', + }, } const relativeRawResult = { './dir/baz.json': { - msg: 'baz' - } + msg: 'baz', + }, } test('should work', async () => { @@ -109,25 +109,25 @@ test('should work', async () => { test('import glob raw', async () => { expect(await page.textContent('.globraw')).toBe( - JSON.stringify(rawResult, null, 2) + JSON.stringify(rawResult, null, 2), ) }) test('import property access', async () => { expect(await page.textContent('.property-access')).toBe( - JSON.stringify(rawResult['/dir/baz.json'], null, 2) + JSON.stringify(rawResult['/dir/baz.json'], null, 2), ) }) test('import relative glob raw', async () => { expect(await page.textContent('.relative-glob-raw')).toBe( - JSON.stringify(relativeRawResult, null, 2) + JSON.stringify(relativeRawResult, null, 2), ) }) test('unassigned import processes', async () => { expect(await page.textContent('.side-effect-result')).toBe( - 'Hello from side effect' + 'Hello from side effect', ) }) @@ -145,9 +145,9 @@ if (!isBuild) { ...allResult['/dir/index.js'], modules: { './a.js': {}, - ...allResult['/dir/index.js'].modules - } - } + ...allResult['/dir/index.js'].modules, + }, + }, }) }) @@ -157,18 +157,18 @@ if (!isBuild) { const actualEdit = await resultElement.textContent() expect(JSON.parse(actualEdit)).toStrictEqual({ '/dir/a.js': { - msg: 'a' + msg: 'a', }, ...allResult, '/dir/index.js': { ...allResult['/dir/index.js'], modules: { './a.js': { - msg: 'a' + msg: 'a', }, - ...allResult['/dir/index.js'].modules - } - } + ...allResult['/dir/index.js'].modules, + }, + }, }) }) @@ -184,7 +184,7 @@ test('tree-shake eager css', async () => { expect(await getColor('.tree-shake-eager-css')).toBe('orange') expect(await getColor('.no-tree-shake-eager-css')).toBe('orange') expect(await page.textContent('.no-tree-shake-eager-css-result')).toMatch( - '.no-tree-shake-eager-css' + '.no-tree-shake-eager-css', ) if (isBuild) { @@ -196,7 +196,7 @@ test('tree-shake eager css', async () => { test('warn CSS default import', async () => { const logs = await untilBrowserLogAfter( () => page.goto(viteTestUrl), - 'Ran scripts' + 'Ran scripts', ) const noTreeshakeCSSMessage = 'For example: `import.meta.glob("/no-tree-shake.css", { "eager": true, "query": "?inline" })`' @@ -206,14 +206,14 @@ test('warn CSS default import', async () => { expect( logs.some((log) => log.includes(noTreeshakeCSSMessage)), `expected logs to include a message including ${JSON.stringify( - noTreeshakeCSSMessage - )}` + noTreeshakeCSSMessage, + )}`, ).toBe(isServe) expect( logs.every((log) => !log.includes(treeshakeCSSMessage)), `expected logs not to include a message including ${JSON.stringify( - treeshakeCSSMessage - )}` + treeshakeCSSMessage, + )}`, ).toBe(true) }) @@ -225,7 +225,7 @@ test('escapes special chars in globs without mangling user supplied glob suffix' // this test finally compares the printed output of index.js with the list of directories with special chars, // expecting that they all work const files = await readdir(path.join(__dirname, '..', 'escape'), { - withFileTypes: true + withFileTypes: true, }) const expectedNames = files .filter((f) => f.isDirectory()) diff --git a/playground/glob-import/escape/(parenthesis)/glob.js b/playground/glob-import/escape/(parenthesis)/glob.js index e97de892c30e2b..9e0d925c4d1026 100644 --- a/playground/glob-import/escape/(parenthesis)/glob.js +++ b/playground/glob-import/escape/(parenthesis)/glob.js @@ -1,5 +1,5 @@ const relative = import.meta.glob('./**/*.js', { eager: true }) const alias = import.meta.glob('@escape_(parenthesis)_mod/**/*.js', { - eager: true + eager: true, }) export { relative, alias } diff --git a/playground/glob-import/escape/[brackets]/glob.js b/playground/glob-import/escape/[brackets]/glob.js index 7cc656bfe97464..320cf021f9db77 100644 --- a/playground/glob-import/escape/[brackets]/glob.js +++ b/playground/glob-import/escape/[brackets]/glob.js @@ -1,5 +1,5 @@ const relative = import.meta.glob('./**/*.js', { eager: true }) const alias = import.meta.glob('@escape_[brackets]_mod/**/*.js', { - eager: true + eager: true, }) export { relative, alias } diff --git a/playground/glob-import/index.html b/playground/glob-import/index.html index 5c07bd11690281..a899d244326f68 100644 --- a/playground/glob-import/index.html +++ b/playground/glob-import/index.html @@ -40,13 +40,13 @@

Escape alias glob

document.querySelector(selector).textContent = JSON.stringify( res, null, - 2 + 2, ) }) } const modules = import.meta.glob( - '/dir/**' + '/dir/**', // for test: annotation contain ")" /* * for test: annotation contain ")" @@ -57,7 +57,7 @@

Escape alias glob

document.querySelector('.result-eager').textContent = JSON.stringify( eagerModules, null, - 2 + 2, ) const nodeModules = import.meta.glob('/dir/node_modules/**') @@ -67,7 +67,7 @@

Escape alias glob

@@ -125,7 +125,7 @@

Escape alias glob

diff --git a/playground/lib/vite.config.js b/playground/lib/vite.config.js index 3e5187b68c55ee..ec46c6c5a12249 100644 --- a/playground/lib/vite.config.js +++ b/playground/lib/vite.config.js @@ -8,21 +8,21 @@ module.exports = { esbuild: { supported: { // Force esbuild inject helpers to test regex - 'object-rest-spread': false - } + 'object-rest-spread': false, + }, }, build: { rollupOptions: { output: { - banner: `/*!\nMayLib\n*/` - } + banner: `/*!\nMayLib\n*/`, + }, }, lib: { entry: path.resolve(__dirname, 'src/main.js'), name: 'MyLib', formats: ['es', 'umd', 'iife'], - fileName: 'my-lib-custom-filename' - } + fileName: 'my-lib-custom-filename', + }, }, plugins: [ { @@ -33,10 +33,10 @@ module.exports = { fileName: 'index.html', source: fs.readFileSync( path.resolve(__dirname, 'index.dist.html'), - 'utf-8' - ) + 'utf-8', + ), }) - } - } - ] + }, + }, + ], } diff --git a/playground/lib/vite.dyimport.config.js b/playground/lib/vite.dyimport.config.js index c621c90fb2ed8a..a808475f386980 100644 --- a/playground/lib/vite.dyimport.config.js +++ b/playground/lib/vite.dyimport.config.js @@ -10,8 +10,8 @@ module.exports = { entry: path.resolve(__dirname, 'src/main2.js'), formats: ['es', 'iife'], name: 'message', - fileName: (format) => `dynamic-import-message.${format}.mjs` + fileName: (format) => `dynamic-import-message.${format}.mjs`, }, - outDir: 'dist/lib' - } + outDir: 'dist/lib', + }, } diff --git a/playground/minify/vite.config.js b/playground/minify/vite.config.js index 43eca91a5c0f30..0f9accb248290a 100644 --- a/playground/minify/vite.config.js +++ b/playground/minify/vite.config.js @@ -2,6 +2,6 @@ import { defineConfig } from 'vite' export default defineConfig({ esbuild: { - minifySyntax: false - } + minifySyntax: false, + }, }) diff --git a/playground/multiple-entrypoints/vite.config.js b/playground/multiple-entrypoints/vite.config.js index e1289dbf5a0078..f0e2ea0ea12779 100644 --- a/playground/multiple-entrypoints/vite.config.js +++ b/playground/multiple-entrypoints/vite.config.js @@ -33,8 +33,8 @@ module.exports = { a22: resolve(__dirname, 'entrypoints/a22.js'), a23: resolve(__dirname, 'entrypoints/a23.js'), a24: resolve(__dirname, 'entrypoints/a24.js'), - index: resolve(__dirname, './index.html') - } - } - } + index: resolve(__dirname, './index.html'), + }, + }, + }, } diff --git a/playground/nested-deps/vite.config.js b/playground/nested-deps/vite.config.js index 85980c5dcfe807..982d97397de55a 100644 --- a/playground/nested-deps/vite.config.js +++ b/playground/nested-deps/vite.config.js @@ -9,8 +9,8 @@ module.exports = { 'test-package-c', 'test-package-c/side', 'test-package-d > test-package-d-nested', - 'test-package-e > test-package-e-included' + 'test-package-e > test-package-e-included', ], - exclude: ['test-package-d', 'test-package-e-excluded'] - } + exclude: ['test-package-d', 'test-package-e-excluded'], + }, } diff --git a/playground/object-hooks/vite.config.ts b/playground/object-hooks/vite.config.ts index 554462dc730df3..1024ce7c0be140 100644 --- a/playground/object-hooks/vite.config.ts +++ b/playground/object-hooks/vite.config.ts @@ -11,14 +11,14 @@ export default defineConfig({ async handler() { await new Promise((r) => setTimeout(r, 100)) count += 1 - } + }, }, transform: { order: 'post', handler(code) { return code.replace('__TRANSFORM3__', 'ok') - } - } + }, + }, }, { name: 'plugin2', @@ -28,13 +28,13 @@ export default defineConfig({ assert(count === 1) await new Promise((r) => setTimeout(r, 100)) count += 1 - } + }, }, transform: { handler(code) { return code.replace('__TRANSFORM1__', '__TRANSFORM2__') - } - } + }, + }, }, { name: 'plugin3', @@ -43,27 +43,27 @@ export default defineConfig({ assert(count === 2) await new Promise((r) => setTimeout(r, 100)) count += 1 - } + }, }, transform: { order: 'pre', handler(code) { return code.replace('__TRANSFORM__', '__TRANSFORM1__') - } - } + }, + }, }, { name: 'plugin4', buildStart: { async handler() { assert(count === 2) - } + }, }, transform: { handler(code) { return code.replace('__TRANSFORM2__', '__TRANSFORM3__') - } - } - } - ] + }, + }, + }, + ], }) diff --git a/playground/optimize-deps/__tests__/optimize-deps.spec.ts b/playground/optimize-deps/__tests__/optimize-deps.spec.ts index 8d109205855555..ad55be500aa5c1 100644 --- a/playground/optimize-deps/__tests__/optimize-deps.spec.ts +++ b/playground/optimize-deps/__tests__/optimize-deps.spec.ts @@ -5,7 +5,7 @@ import { getColor, isBuild, isServe, - page + page, } from '~utils' test('default + named imports from cjs dep (react)', async () => { @@ -38,13 +38,13 @@ test('dynamic default import from webpacked cjs (clipboard)', async () => { test('dynamic default import from cjs (cjs-dynamic-dep-cjs-compiled-from-esm)', async () => { expect(await page.textContent('.cjs-dynamic-dep-cjs-compiled-from-esm')).toBe( - 'ok' + 'ok', ) }) test('dynamic default import from cjs (cjs-dynamic-dep-cjs-compiled-from-cjs)', async () => { expect(await page.textContent('.cjs-dynamic-dep-cjs-compiled-from-cjs')).toBe( - 'ok' + 'ok', ) }) @@ -88,19 +88,19 @@ test('Import from dependency which uses relative path which needs to be resolved test('dep with dynamic import', async () => { expect(await page.textContent('.dep-with-dynamic-import')).toMatch( - `[success]` + `[success]`, ) }) test('dep with optional peer dep', async () => { expect(await page.textContent('.dep-with-optional-peer-dep')).toMatch( - `[success]` + `[success]`, ) if (isServe) { expect(browserErrors.map((error) => error.message)).toEqual( expect.arrayContaining([ - 'Could not resolve "foobar" imported by "dep-with-optional-peer-dep". Is it installed?' - ]) + 'Could not resolve "foobar" imported by "dep-with-optional-peer-dep". Is it installed?', + ]), ) } }) @@ -125,7 +125,7 @@ test('vue + vuex', async () => { // the esbuild plugins won't apply to dependencies test('esbuild-plugin', async () => { expect(await page.textContent('.esbuild-plugin')).toMatch( - `Hello from an esbuild plugin` + `Hello from an esbuild plugin`, ) }) @@ -152,7 +152,7 @@ test('flatten id should generate correctly', async () => { test('non optimized module is not duplicated', async () => { expect( - await page.textContent('.non-optimized-module-is-not-duplicated') + await page.textContent('.non-optimized-module-is-not-duplicated'), ).toBe('from-absolute-path, from-relative-path') }) @@ -163,28 +163,28 @@ test.runIf(isServe)('error on builtin modules usage', () => { expect.stringMatching(/dep-with-builtin-module-esm.*is not a function/), // dep-with-builtin-module-esm warnings expect.stringContaining( - 'Module "fs" has been externalized for browser compatibility. Cannot access "fs.readFileSync" in client code.' + 'Module "fs" has been externalized for browser compatibility. Cannot access "fs.readFileSync" in client code.', ), expect.stringContaining( - 'Module "path" has been externalized for browser compatibility. Cannot access "path.join" in client code.' + 'Module "path" has been externalized for browser compatibility. Cannot access "path.join" in client code.', ), // from dep-with-builtin-module-cjs expect.stringMatching(/dep-with-builtin-module-cjs.*is not a function/), // dep-with-builtin-module-cjs warnings expect.stringContaining( - 'Module "fs" has been externalized for browser compatibility. Cannot access "fs.readFileSync" in client code.' + 'Module "fs" has been externalized for browser compatibility. Cannot access "fs.readFileSync" in client code.', ), expect.stringContaining( - 'Module "path" has been externalized for browser compatibility. Cannot access "path.join" in client code.' - ) - ]) + 'Module "path" has been externalized for browser compatibility. Cannot access "path.join" in client code.', + ), + ]), ) expect(browserErrors.map((error) => error.message)).toEqual( expect.arrayContaining([ // from user source code 'Module "buffer" has been externalized for browser compatibility. Cannot access "buffer.Buffer" in client code.', - 'Module "child_process" has been externalized for browser compatibility. Cannot access "child_process.execSync" in client code.' - ]) + 'Module "child_process" has been externalized for browser compatibility. Cannot access "child_process.execSync" in client code.', + ]), ) }) diff --git a/playground/optimize-deps/cjs-dynamic.js b/playground/optimize-deps/cjs-dynamic.js index 21aec63fe27098..6b74bff96b38f3 100644 --- a/playground/optimize-deps/cjs-dynamic.js +++ b/playground/optimize-deps/cjs-dynamic.js @@ -36,14 +36,14 @@ { onClick() { setCount(count + 1) - } + }, }, - `count is ${count}` + `count is ${count}`, ) } ReactDOM.createRoot(document.querySelector('.cjs-dynamic')).render( - React.createElement(App) + React.createElement(App), ) function text(el, text) { diff --git a/playground/optimize-deps/cjs.js b/playground/optimize-deps/cjs.js index 9a4651d6ad4008..ba3e0aa783e69c 100644 --- a/playground/optimize-deps/cjs.js +++ b/playground/optimize-deps/cjs.js @@ -27,14 +27,14 @@ function App() { { onClick() { setCount(count + 1) - } + }, }, - `count is ${count}` + `count is ${count}`, ) } ReactDOM.createRoot(document.querySelector('.cjs')).render( - React.createElement(App) + React.createElement(App), ) function text(el, text) { diff --git a/playground/optimize-deps/dedupe.js b/playground/optimize-deps/dedupe.js index 7299fb9d3bb6c8..8429b719884d43 100644 --- a/playground/optimize-deps/dedupe.js +++ b/playground/optimize-deps/dedupe.js @@ -14,12 +14,12 @@ function App() { { onClick() { setCount(count + 1) - } + }, }, - `count is ${count}` + `count is ${count}`, ) } ReactDOM.createRoot(document.querySelector('.dedupe')).render( - React.createElement(App) + React.createElement(App), ) diff --git a/playground/optimize-deps/dep-cjs-browser-field-bare/events-shim.js b/playground/optimize-deps/dep-cjs-browser-field-bare/events-shim.js index fb5ce844858a55..964e815b7a7bcf 100644 --- a/playground/optimize-deps/dep-cjs-browser-field-bare/events-shim.js +++ b/playground/optimize-deps/dep-cjs-browser-field-bare/events-shim.js @@ -1,3 +1,3 @@ module.exports = { - foo: 'foo' + foo: 'foo', } diff --git a/playground/optimize-deps/index.html b/playground/optimize-deps/index.html index 3ca86a5359781a..f6bafd8b1eb825 100644 --- a/playground/optimize-deps/index.html +++ b/playground/optimize-deps/index.html @@ -164,7 +164,7 @@

Non Optimized Module isn't duplicated

addFromDirectRelativePath('from-relative-path') text( '.non-optimized-module-is-not-duplicated', - getFromBareImport().join(', ') + getFromBareImport().join(', '), ) diff --git a/playground/optimize-deps/vite.config.js b/playground/optimize-deps/vite.config.js index d8e575271f2572..8bd56a721d6666 100644 --- a/playground/optimize-deps/vite.config.js +++ b/playground/optimize-deps/vite.config.js @@ -11,8 +11,8 @@ module.exports = { resolve: { dedupe: ['react'], alias: { - 'node:url': 'url' - } + 'node:url': 'url', + }, }, optimizeDeps: { disabled: false, @@ -20,7 +20,7 @@ module.exports = { 'dep-linked-include', 'nested-exclude > nested-include', // will throw if optimized (should log warning instead) - 'non-optimizable-include' + 'non-optimizable-include', ], exclude: ['nested-exclude', 'dep-non-optimized'], esbuildOptions: { @@ -32,14 +32,14 @@ module.exports = { { filter: /dep-esbuild-plugin-transform(\\|\/)index\.js$/ }, () => ({ contents: `export const hello = () => 'Hello from an esbuild plugin'`, - loader: 'js' - }) + loader: 'js', + }), ) - } - } - ] + }, + }, + ], }, - entries: ['entry.js'] + entries: ['entry.js'], }, build: { @@ -47,8 +47,8 @@ module.exports = { minify: false, // Avoid @rollup/plugin-commonjs commonjsOptions: { - include: [] - } + include: [], + }, }, plugins: [ @@ -68,7 +68,7 @@ module.exports = { res.statusCode = 200 res.end('pong') }) - } + }, }, { name: 'test-astro', @@ -77,7 +77,7 @@ module.exports = { code = `export default {}` return { code } } - } + }, }, // TODO: Remove this one support for prebundling in build lands. // It is expected that named importing in build doesn't work @@ -90,9 +90,9 @@ module.exports = { if (id === '__vite-browser-external') { return `export default {}; export function readFileSync() {}` } - } - } - ] + }, + }, + ], } // Handles .notjs file, basically remove wrapping and tags @@ -115,11 +115,11 @@ function notjs() { .replace('', '') return { contents, loader: 'js' } }) - } - } - ] - } - } + }, + }, + ], + }, + }, } }, transform(code, id) { @@ -127,6 +127,6 @@ function notjs() { code = code.replace('', '').replace('', '') return { code } } - } + }, } } diff --git a/playground/optimize-missing-deps/__test__/serve.ts b/playground/optimize-missing-deps/__test__/serve.ts index 750d57075c2452..ed9ad41a7c90a1 100644 --- a/playground/optimize-missing-deps/__test__/serve.ts +++ b/playground/optimize-missing-deps/__test__/serve.ts @@ -10,7 +10,7 @@ export async function serve(): Promise<{ close(): Promise }> { const { createServer } = require(path.resolve(rootDir, 'server.js')) const { app, vite } = await createServer( rootDir, - hmrPorts['optimize-missing-deps'] + hmrPorts['optimize-missing-deps'], ) return new Promise((resolve, reject) => { @@ -25,7 +25,7 @@ export async function serve(): Promise<{ close(): Promise }> { if (vite) { await vite.close() } - } + }, }) }) } catch (e) { diff --git a/playground/optimize-missing-deps/server.js b/playground/optimize-missing-deps/server.js index 0685d0148eff43..1940d76fa7e0cd 100644 --- a/playground/optimize-missing-deps/server.js +++ b/playground/optimize-missing-deps/server.js @@ -19,10 +19,10 @@ async function createServer(root = process.cwd(), hmrPort) { server: { middlewareMode: true, hmr: { - port: hmrPort - } + port: hmrPort, + }, }, - appType: 'custom' + appType: 'custom', }) app.use(vite.middlewares) @@ -59,7 +59,7 @@ if (!isTest) { createServer().then(({ app }) => app.listen(5173, () => { console.log('http://localhost:5173') - }) + }), ) } diff --git a/playground/preload/__tests__/preload.spec.ts b/playground/preload/__tests__/preload.spec.ts index dc93f51ba2b700..9407d26942456a 100644 --- a/playground/preload/__tests__/preload.spec.ts +++ b/playground/preload/__tests__/preload.spec.ts @@ -17,10 +17,10 @@ describe.runIf(isBuild)('build', () => { await page.goto(viteTestUrl + '/#/hello') const html = await page.content() expect(html).toMatch( - /link rel="modulepreload".*?href=".*?\/assets\/Hello-\w{8}\.js"/ + /link rel="modulepreload".*?href=".*?\/assets\/Hello-\w{8}\.js"/, ) expect(html).toMatch( - /link rel="stylesheet".*?href=".*?\/assets\/Hello-\w{8}\.css"/ + /link rel="stylesheet".*?href=".*?\/assets\/Hello-\w{8}\.css"/, ) }) }) diff --git a/playground/preload/__tests__/resolve-deps/preload-resolve-deps.spec.ts b/playground/preload/__tests__/resolve-deps/preload-resolve-deps.spec.ts index b587f78b08c207..78a19d7c09cb35 100644 --- a/playground/preload/__tests__/resolve-deps/preload-resolve-deps.spec.ts +++ b/playground/preload/__tests__/resolve-deps/preload-resolve-deps.spec.ts @@ -17,11 +17,11 @@ describe.runIf(isBuild)('build', () => { await page.goto(viteTestUrl + '/#/hello') const html = await page.content() expect(html).toMatch( - /link rel="modulepreload".*?href="http.*?\/Hello-\w{8}\.js"/ + /link rel="modulepreload".*?href="http.*?\/Hello-\w{8}\.js"/, ) expect(html).toMatch(/link rel="modulepreload".*?href="\/preloaded.js"/) expect(html).toMatch( - /link rel="stylesheet".*?href="http.*?\/Hello-\w{8}\.css"/ + /link rel="stylesheet".*?href="http.*?\/Hello-\w{8}\.css"/, ) }) }) diff --git a/playground/preload/router.js b/playground/preload/router.js index d3d5afdc99f6a3..2e4388967838ae 100644 --- a/playground/preload/router.js +++ b/playground/preload/router.js @@ -6,16 +6,16 @@ const routes = [ { path: '/hello', name: 'Hello', - component: () => import(/* a comment */ './src/components/Hello.vue') + component: () => import(/* a comment */ './src/components/Hello.vue'), }, { path: '/about', name: 'About', - component: () => import('./src/components/About.vue') - } // Lazy load route component + component: () => import('./src/components/About.vue'), + }, // Lazy load route component ] export default createRouter({ routes, - history: createWebHashHistory() + history: createWebHashHistory(), }) diff --git a/playground/preload/vite.config-preload-disabled.ts b/playground/preload/vite.config-preload-disabled.ts index 27735976335365..47f8a7ee5e1ac1 100644 --- a/playground/preload/vite.config-preload-disabled.ts +++ b/playground/preload/vite.config-preload-disabled.ts @@ -7,12 +7,12 @@ export default defineConfig({ minify: 'terser', terserOptions: { format: { - beautify: true + beautify: true, }, compress: { - passes: 3 - } + passes: 3, + }, }, - modulePreload: false - } + modulePreload: false, + }, }) diff --git a/playground/preload/vite.config-resolve-deps.ts b/playground/preload/vite.config-resolve-deps.ts index d556f2a843c6d4..951544634b19de 100644 --- a/playground/preload/vite.config-resolve-deps.ts +++ b/playground/preload/vite.config-resolve-deps.ts @@ -7,11 +7,11 @@ export default defineConfig({ minify: 'terser', terserOptions: { format: { - beautify: true + beautify: true, }, compress: { - passes: 3 - } + passes: 3, + }, }, modulePreload: { resolveDependencies(filename, deps, { hostId, hostType }) { @@ -19,8 +19,8 @@ export default defineConfig({ return [...deps, 'preloaded.js'] } return deps - } - } + }, + }, }, experimental: { renderBuiltUrl(filename, { hostId, hostType }) { @@ -28,6 +28,6 @@ export default defineConfig({ return { runtime: `""+${JSON.stringify('/' + filename)}` } } return { relative: true } - } - } + }, + }, }) diff --git a/playground/preload/vite.config.ts b/playground/preload/vite.config.ts index 7fa1eb189818b3..29e81c358c866c 100644 --- a/playground/preload/vite.config.ts +++ b/playground/preload/vite.config.ts @@ -7,11 +7,11 @@ export default defineConfig({ minify: 'terser', terserOptions: { format: { - beautify: true + beautify: true, }, compress: { - passes: 3 - } - } - } + passes: 3, + }, + }, + }, }) diff --git a/playground/preserve-symlinks/moduleA/src/data.js b/playground/preserve-symlinks/moduleA/src/data.js index e1bc98ec67da12..5e21c75a71d952 100644 --- a/playground/preserve-symlinks/moduleA/src/data.js +++ b/playground/preserve-symlinks/moduleA/src/data.js @@ -1,3 +1,3 @@ export const data = { - msg: 'hello vite' + msg: 'hello vite', } diff --git a/playground/resolve-config/__tests__/resolve-config.spec.ts b/playground/resolve-config/__tests__/resolve-config.spec.ts index 7c9d003791b4d9..eeb4f2c79edcbb 100644 --- a/playground/resolve-config/__tests__/resolve-config.spec.ts +++ b/playground/resolve-config/__tests__/resolve-config.spec.ts @@ -13,7 +13,7 @@ const build = (configName: string) => { const getDistFile = (configName: string, extension: string) => { return fs.readFileSync( fromTestDir(`${configName}/dist/index.${extension}`), - 'utf8' + 'utf8', ) } diff --git a/playground/resolve-config/__tests__/serve.ts b/playground/resolve-config/__tests__/serve.ts index b2cc1ccc1e1e77..39e84860cfadfb 100644 --- a/playground/resolve-config/__tests__/serve.ts +++ b/playground/resolve-config/__tests__/serve.ts @@ -24,7 +24,7 @@ export async function serve() { const conf = await fs.readFile(pathToConf, 'utf8') await fs.writeFile( pathToConf, - conf.replace('export default', 'module.exports = ') + conf.replace('export default', 'module.exports = '), ) } @@ -37,7 +37,7 @@ export async function serve() { // copy directory and add package.json with "type": "module" await fs.copy(fromTestDir(configName), fromTestDir(`${configName}-module`)) await fs.writeJSON(fromTestDir(`${configName}-module`, 'package.json'), { - type: 'module' + type: 'module', }) } } diff --git a/playground/resolve-config/root/vite.config.ts b/playground/resolve-config/root/vite.config.ts index a6ad03b2122361..016564355261d8 100644 --- a/playground/resolve-config/root/vite.config.ts +++ b/playground/resolve-config/root/vite.config.ts @@ -5,6 +5,6 @@ export default { build: { minify: false, sourcemap: false, - lib: { entry: 'index.js', fileName: 'index', formats: ['es'] } - } + lib: { entry: 'index.js', fileName: 'index', formats: ['es'] }, + }, } diff --git a/playground/resolve/__tests__/resolve.spec.ts b/playground/resolve/__tests__/resolve.spec.ts index 8f910f4989bfaa..2181f6d3c8433e 100644 --- a/playground/resolve/__tests__/resolve.spec.ts +++ b/playground/resolve/__tests__/resolve.spec.ts @@ -20,26 +20,26 @@ test('deep import with exports field', async () => { test('deep import with query with exports field', async () => { // since it is imported with `?url` it should return a URL expect(await page.textContent('.exports-deep-query')).toMatch( - isBuild ? /base64/ : '/exports-path/deep.json' + isBuild ? /base64/ : '/exports-path/deep.json', ) }) test('deep import with exports field + exposed dir', async () => { expect(await page.textContent('.exports-deep-exposed-dir')).toMatch( - '[success]' + '[success]', ) }) test('deep import with exports field + mapped dir', async () => { expect(await page.textContent('.exports-deep-mapped-dir')).toMatch( - '[success]' + '[success]', ) }) // this is how Svelte 3 is packaged test('deep import with exports and legacy fallback', async () => { expect(await page.textContent('.exports-legacy-fallback')).toMatch( - '[success]' + '[success]', ) }) @@ -49,7 +49,7 @@ test('Respect exports field env key priority', async () => { test('Respect production/development conditionals', async () => { expect(await page.textContent('.exports-env')).toMatch( - isBuild ? `browser.prod.mjs` : `browser.mjs` + isBuild ? `browser.prod.mjs` : `browser.mjs`, ) }) @@ -71,7 +71,7 @@ test('dont add extension to directory name (./dir-with-ext.js/index.js)', async test('do not resolve to the `module` field if the importer is a `require` call', async () => { expect(await page.textContent('.require-pkg-with-module-field')).toMatch( - '[success]' + '[success]', ) }) @@ -141,6 +141,6 @@ test('resolve.conditions', async () => { test('resolve package that contains # in path', async () => { expect(await page.textContent('.path-contains-sharp-symbol')).toMatch( - '[success]' + '[success]', ) }) diff --git a/playground/resolve/config-dep.js b/playground/resolve/config-dep.js index 8bc3563c743bcd..167d270797e4c2 100644 --- a/playground/resolve/config-dep.js +++ b/playground/resolve/config-dep.js @@ -1,3 +1,3 @@ module.exports = { - a: 1 + a: 1, } diff --git a/playground/resolve/vite.config.js b/playground/resolve/vite.config.js index b27613eb6bc2ad..54f2ccf839f70c 100644 --- a/playground/resolve/vite.config.js +++ b/playground/resolve/vite.config.js @@ -14,24 +14,24 @@ const generatedContentVirtualFile = '@generated-content-virtual-file' const generatedContentImports = [ { specifier: normalizePath( - path.resolve(__dirname, './drive-relative.js').replace(/^[a-zA-Z]:/, '') + path.resolve(__dirname, './drive-relative.js').replace(/^[a-zA-Z]:/, ''), ), - elementQuery: '.drive-relative' + elementQuery: '.drive-relative', }, { specifier: normalizePath(path.resolve(__dirname, './absolute.js')), - elementQuery: '.absolute' - } + elementQuery: '.absolute', + }, ] module.exports = { resolve: { extensions: ['.mjs', '.js', '.es', '.ts'], mainFields: ['custom', 'module'], - conditions: ['custom'] + conditions: ['custom'], }, define: { - VITE_CONFIG_DEP_TEST: a + VITE_CONFIG_DEP_TEST: a, }, plugins: [ { @@ -45,7 +45,7 @@ module.exports = { if (id === virtualId) { return `export const msg = "[success] from conventional virtual file"` } - } + }, }, { name: 'virtual-module-9036', @@ -58,7 +58,7 @@ module.exports = { if (id === virtualId9036) { return `export const msg = "[success] from virtual file #9036"` } - } + }, }, { name: 'custom-resolve', @@ -71,7 +71,7 @@ module.exports = { if (id === customVirtualFile) { return `export const msg = "[success] from custom virtual file"` } - } + }, }, { name: 'generated-content', @@ -86,7 +86,7 @@ module.exports = { .map( ({ specifier, elementQuery }, i) => `import content${i} from ${JSON.stringify(specifier)}\n` + - `text(${JSON.stringify(elementQuery)}, content${i})` + `text(${JSON.stringify(elementQuery)}, content${i})`, ) .join('\n') @@ -97,10 +97,10 @@ module.exports = { tests ) } - } - } + }, + }, ], optimizeDeps: { - include: ['require-pkg-with-module-field'] - } + include: ['require-pkg-with-module-field'], + }, } diff --git a/playground/ssr-deps/__tests__/serve.ts b/playground/ssr-deps/__tests__/serve.ts index c9475c76441773..d7502f5542a356 100644 --- a/playground/ssr-deps/__tests__/serve.ts +++ b/playground/ssr-deps/__tests__/serve.ts @@ -25,7 +25,7 @@ export async function serve(): Promise<{ close(): Promise }> { if (vite) { await vite.close() } - } + }, }) }) } catch (e) { diff --git a/playground/ssr-deps/__tests__/ssr-deps.spec.ts b/playground/ssr-deps/__tests__/ssr-deps.spec.ts index a98bf5bcd76299..5a45d047ee86a0 100644 --- a/playground/ssr-deps/__tests__/ssr-deps.spec.ts +++ b/playground/ssr-deps/__tests__/ssr-deps.spec.ts @@ -13,7 +13,7 @@ const url = `http://localhost:${port}` test('msg should be encrypted', async () => { await page.goto(url) expect(await page.textContent('.encrypted-msg')).not.toMatch( - 'Secret Message!' + 'Secret Message!', ) }) @@ -25,52 +25,52 @@ test('msg read by fs/promises', async () => { test('msg from primitive export', async () => { await page.goto(url) expect(await page.textContent('.primitive-export-message')).toMatch( - 'Hello World!' + 'Hello World!', ) }) test('msg from TS transpiled exports', async () => { await page.goto(url) expect(await page.textContent('.ts-default-export-message')).toMatch( - 'Hello World!' + 'Hello World!', ) expect(await page.textContent('.ts-named-export-message')).toMatch( - 'Hello World!' + 'Hello World!', ) }) test('msg from Object.assign exports', async () => { await page.goto(url) expect(await page.textContent('.object-assigned-exports-message')).toMatch( - 'Hello World!' + 'Hello World!', ) }) test('msg from forwarded exports', async () => { await page.goto(url) expect(await page.textContent('.forwarded-export-message')).toMatch( - 'Hello World!' + 'Hello World!', ) }) test('msg from define properties exports', async () => { await page.goto(url) expect(await page.textContent('.define-properties-exports-msg')).toMatch( - 'Hello World!' + 'Hello World!', ) }) test('msg from define property exports', async () => { await page.goto(url) expect(await page.textContent('.define-property-exports-msg')).toMatch( - 'Hello World!' + 'Hello World!', ) }) test('msg from only object assigned exports', async () => { await page.goto(url) expect(await page.textContent('.only-object-assigned-exports-msg')).toMatch( - 'Hello World!' + 'Hello World!', ) }) @@ -82,28 +82,28 @@ test('msg from no external cjs', async () => { test('msg from optimized with nested external', async () => { await page.goto(url) expect(await page.textContent('.optimized-with-nested-external')).toMatch( - 'Hello World!' + 'Hello World!', ) }) test('msg from optimized cjs with nested external', async () => { await page.goto(url) expect(await page.textContent('.optimized-cjs-with-nested-external')).toMatch( - 'Hello World!' + 'Hello World!', ) }) test('msg from external using external entry', async () => { await page.goto(url) expect(await page.textContent('.external-using-external-entry')).toMatch( - 'Hello World!' + 'Hello World!', ) }) test('msg from linked no external', async () => { await page.goto(url) expect(await page.textContent('.linked-no-external')).toMatch( - `Hello World from ${process.env.NODE_ENV}!` + `Hello World from ${process.env.NODE_ENV}!`, ) }) diff --git a/playground/ssr-deps/define-property-exports/index.js b/playground/ssr-deps/define-property-exports/index.js index 4506dd6200051e..d9708c8a5fed60 100644 --- a/playground/ssr-deps/define-property-exports/index.js +++ b/playground/ssr-deps/define-property-exports/index.js @@ -1,5 +1,5 @@ Object.defineProperty(exports, 'hello', { value() { return 'Hello World!' - } + }, }) diff --git a/playground/ssr-deps/external-using-external-entry/index.js b/playground/ssr-deps/external-using-external-entry/index.js index 8d0e6e15200dc6..e8160fcd36d176 100644 --- a/playground/ssr-deps/external-using-external-entry/index.js +++ b/playground/ssr-deps/external-using-external-entry/index.js @@ -3,5 +3,5 @@ import getMessage from 'external-entry/entry' export default { hello() { return getMessage() - } + }, } diff --git a/playground/ssr-deps/object-assigned-exports/index.js b/playground/ssr-deps/object-assigned-exports/index.js index d6510e38f3a36f..e0e61fcd260e4e 100644 --- a/playground/ssr-deps/object-assigned-exports/index.js +++ b/playground/ssr-deps/object-assigned-exports/index.js @@ -3,7 +3,7 @@ Object.defineProperty(exports, '__esModule', { value: true }) const obj = { hello() { return 'Hello World!' - } + }, } Object.assign(exports, obj) diff --git a/playground/ssr-deps/only-object-assigned-exports/index.js b/playground/ssr-deps/only-object-assigned-exports/index.js index b6a4ab368b133d..8d268027ec7f0c 100644 --- a/playground/ssr-deps/only-object-assigned-exports/index.js +++ b/playground/ssr-deps/only-object-assigned-exports/index.js @@ -1,5 +1,5 @@ Object.assign(exports, { hello() { return 'Hello World!' - } + }, }) diff --git a/playground/ssr-deps/optimized-cjs-with-nested-external/index.js b/playground/ssr-deps/optimized-cjs-with-nested-external/index.js index adbbb819ed31ea..6fc7c0c31a8324 100644 --- a/playground/ssr-deps/optimized-cjs-with-nested-external/index.js +++ b/playground/ssr-deps/optimized-cjs-with-nested-external/index.js @@ -1,5 +1,5 @@ const getMessage = require('nested-external') module.exports = { - hello: getMessage + hello: getMessage, } diff --git a/playground/ssr-deps/server.js b/playground/ssr-deps/server.js index 08a8b331495882..9cda0482aa1469 100644 --- a/playground/ssr-deps/server.js +++ b/playground/ssr-deps/server.js @@ -27,11 +27,11 @@ export async function createServer(root = process.cwd(), hmrPort) { // During tests we edit the files too fast and sometimes chokidar // misses change events, so enforce polling for consistency usePolling: true, - interval: 100 + interval: 100, }, hmr: { - port: hmrPort - } + port: hmrPort, + }, }, appType: 'custom', ssr: { @@ -39,12 +39,12 @@ export async function createServer(root = process.cwd(), hmrPort) { 'no-external-cjs', 'import-builtin-cjs', 'no-external-css', - 'external-entry' + 'external-entry', ], external: ['nested-external', 'external-entry/entry'], optimizeDeps: { - disabled: 'build' - } + disabled: 'build', + }, }, plugins: [ { @@ -59,9 +59,9 @@ export async function createServer(root = process.cwd(), hmrPort) { if (id === 'pkg-exports/virtual') { return 'export default "[success]"' } - } - } - ] + }, + }, + ], }) // use vite's connect instance as middleware app.use(vite.middlewares) @@ -94,6 +94,6 @@ if (!isTest) { createServer().then(({ app }) => app.listen(5173, () => { console.log('http://localhost:5173') - }) + }), ) } diff --git a/playground/ssr-html/__tests__/serve.ts b/playground/ssr-html/__tests__/serve.ts index 47076edcb40550..4886414606b6b6 100644 --- a/playground/ssr-html/__tests__/serve.ts +++ b/playground/ssr-html/__tests__/serve.ts @@ -25,7 +25,7 @@ export async function serve(): Promise<{ close(): Promise }> { if (vite) { await vite.close() } - } + }, }) }) } catch (e) { diff --git a/playground/ssr-html/__tests__/ssr-html.spec.ts b/playground/ssr-html/__tests__/ssr-html.spec.ts index 94e64bdb5d8b8b..fa871fce04efb8 100644 --- a/playground/ssr-html/__tests__/ssr-html.spec.ts +++ b/playground/ssr-html/__tests__/ssr-html.spec.ts @@ -9,7 +9,7 @@ describe('injected inline scripts', () => { test('no injected inline scripts are present', async () => { await page.goto(url) const inlineScripts = await page.$$eval('script', (nodes) => - nodes.filter((n) => !n.getAttribute('src') && n.innerHTML) + nodes.filter((n) => !n.getAttribute('src') && n.innerHTML), ) expect(inlineScripts).toHaveLength(0) }) @@ -23,14 +23,14 @@ describe('injected inline scripts', () => { if (!src) return false return src.includes('?html-proxy&index') }) - .map((n) => n.getAttribute('src')) + .map((n) => n.getAttribute('src')), ) // assert at least 1 proxied script exists expect(proxiedScripts).not.toHaveLength(0) const scriptContents = await Promise.all( - proxiedScripts.map((src) => fetch(url + src).then((res) => res.text())) + proxiedScripts.map((src) => fetch(url + src).then((res) => res.text())), ) // all proxied scripts return code @@ -46,7 +46,7 @@ describe.runIf(isServe)('hmr', () => { const el = await page.$('.virtual') expect(await el.textContent()).toBe('[success]') editFile('src/importedVirtual.js', (code) => - code.replace('[success]', '[wow]') + code.replace('[success]', '[wow]'), ) await page.waitForNavigation() await untilUpdated(async () => { diff --git a/playground/ssr-html/server.js b/playground/ssr-html/server.js index 02d613ed49004f..0c4deacfc64f2e 100644 --- a/playground/ssr-html/server.js +++ b/playground/ssr-html/server.js @@ -42,11 +42,11 @@ export async function createServer(root = process.cwd(), hmrPort) { // During tests we edit the files too fast and sometimes chokidar // misses change events, so enforce polling for consistency usePolling: true, - interval: 100 + interval: 100, }, hmr: { - port: hmrPort - } + port: hmrPort, + }, }, appType: 'custom', plugins: [ @@ -61,9 +61,9 @@ export async function createServer(root = process.cwd(), hmrPort) { if (id === '\0virtual:file') { return 'import { virtual } from "/src/importedVirtual.js"; export { virtual };' } - } - } - ] + }, + }, + ], }) // use vite's connect instance as middleware app.use(vite.middlewares) @@ -85,7 +85,7 @@ export async function createServer(root = process.cwd(), hmrPort) { template = template.replace( '', - `${DYNAMIC_SCRIPTS}${DYNAMIC_STYLES}` + `${DYNAMIC_SCRIPTS}${DYNAMIC_STYLES}`, ) // Force calling transformIndexHtml with url === '/', to simulate @@ -108,6 +108,6 @@ if (!isTest) { createServer().then(({ app }) => app.listen(5173, () => { console.log('http://localhost:5173') - }) + }), ) } diff --git a/playground/ssr-noexternal/__tests__/serve.ts b/playground/ssr-noexternal/__tests__/serve.ts index 5878da8f5ce439..47bb4c5236294f 100644 --- a/playground/ssr-noexternal/__tests__/serve.ts +++ b/playground/ssr-noexternal/__tests__/serve.ts @@ -16,8 +16,8 @@ export async function serve(): Promise<{ close(): Promise }> { root: rootDir, logLevel: 'silent', build: { - ssr: 'src/entry-server.js' - } + ssr: 'src/entry-server.js', + }, }) } @@ -27,7 +27,7 @@ export async function serve(): Promise<{ close(): Promise }> { const { app, vite } = await createServer( rootDir, isBuild, - hmrPorts['ssr-noexternal'] + hmrPorts['ssr-noexternal'], ) return new Promise((resolve, reject) => { @@ -42,7 +42,7 @@ export async function serve(): Promise<{ close(): Promise }> { if (vite) { await vite.close() } - } + }, }) }) } catch (e) { diff --git a/playground/ssr-noexternal/server.js b/playground/ssr-noexternal/server.js index 5ee318f4093952..b11f161f70d2e6 100644 --- a/playground/ssr-noexternal/server.js +++ b/playground/ssr-noexternal/server.js @@ -10,7 +10,7 @@ const isTest = process.env.VITEST export async function createServer( root = process.cwd(), isProd = process.env.NODE_ENV === 'production', - hmrPort + hmrPort, ) { const resolve = (p) => path.resolve(__dirname, p) @@ -36,13 +36,13 @@ export async function createServer( // During tests we edit the files too fast and sometimes chokidar // misses change events, so enforce polling for consistency usePolling: true, - interval: 100 + interval: 100, }, hmr: { - port: hmrPort - } + port: hmrPort, + }, }, - appType: 'custom' + appType: 'custom', }) app.use(vite.middlewares) } @@ -82,6 +82,6 @@ if (!isTest) { createServer().then(({ app }) => app.listen(5173, () => { console.log('http://localhost:5173') - }) + }), ) } diff --git a/playground/ssr-noexternal/vite.config.js b/playground/ssr-noexternal/vite.config.js index 848179b85a24e7..124939d4cde737 100644 --- a/playground/ssr-noexternal/vite.config.js +++ b/playground/ssr-noexternal/vite.config.js @@ -6,17 +6,17 @@ export default defineConfig({ noExternal: ['@vitejs/require-external-cjs'], external: ['@vitejs/external-cjs'], optimizeDeps: { - disabled: false - } + disabled: false, + }, }, build: { target: 'esnext', minify: false, rollupOptions: { - external: ['@vitejs/external-cjs'] + external: ['@vitejs/external-cjs'], }, commonjsOptions: { - include: [] - } - } + include: [], + }, + }, }) diff --git a/playground/ssr-pug/__tests__/serve.ts b/playground/ssr-pug/__tests__/serve.ts index 35ae326964b486..715c38e99801ad 100644 --- a/playground/ssr-pug/__tests__/serve.ts +++ b/playground/ssr-pug/__tests__/serve.ts @@ -25,7 +25,7 @@ export async function serve(): Promise<{ close(): Promise }> { if (vite) { await vite.close() } - } + }, }) }) } catch (e) { diff --git a/playground/ssr-pug/__tests__/ssr-pug.spec.ts b/playground/ssr-pug/__tests__/ssr-pug.spec.ts index f29b0ac33cf5d8..06074172f7ed1d 100644 --- a/playground/ssr-pug/__tests__/ssr-pug.spec.ts +++ b/playground/ssr-pug/__tests__/ssr-pug.spec.ts @@ -9,7 +9,7 @@ describe('injected inline scripts', () => { test('no injected inline scripts are present', async () => { await page.goto(url) const inlineScripts = await page.$$eval('script', (nodes) => - nodes.filter((n) => !n.getAttribute('src') && n.innerHTML) + nodes.filter((n) => !n.getAttribute('src') && n.innerHTML), ) expect(inlineScripts).toHaveLength(0) }) @@ -23,14 +23,14 @@ describe('injected inline scripts', () => { if (!src) return false return src.includes('?html-proxy&index') }) - .map((n) => n.getAttribute('src')) + .map((n) => n.getAttribute('src')), ) // assert at least 1 proxied script exists expect(proxiedScripts).not.toHaveLength(0) const scriptContents = await Promise.all( - proxiedScripts.map((src) => fetch(url + src).then((res) => res.text())) + proxiedScripts.map((src) => fetch(url + src).then((res) => res.text())), ) // all proxied scripts return code diff --git a/playground/ssr-pug/server.js b/playground/ssr-pug/server.js index 64fc87dc95589f..222b51ae216638 100644 --- a/playground/ssr-pug/server.js +++ b/playground/ssr-pug/server.js @@ -36,13 +36,13 @@ export async function createServer(root = process.cwd(), hmrPort) { // During tests we edit the files too fast and sometimes chokidar // misses change events, so enforce polling for consistency usePolling: true, - interval: 100 + interval: 100, }, hmr: { - port: hmrPort - } + port: hmrPort, + }, }, - appType: 'custom' + appType: 'custom', }) // use vite's connect instance as middleware app.use(vite.middlewares) @@ -73,6 +73,6 @@ if (!isTest) { createServer().then(({ app }) => app.listen(5173, () => { console.log('http://localhost:5173') - }) + }), ) } diff --git a/playground/ssr-resolve/vite.config.js b/playground/ssr-resolve/vite.config.js index 430c2331977703..206485d1088b8c 100644 --- a/playground/ssr-resolve/vite.config.js +++ b/playground/ssr-resolve/vite.config.js @@ -2,6 +2,6 @@ import { defineConfig } from 'vite' export default defineConfig({ build: { - ssr: './main.js' - } + ssr: './main.js', + }, }) diff --git a/playground/ssr-webworker/__tests__/serve.ts b/playground/ssr-webworker/__tests__/serve.ts index 0013d19769c299..8159cf39734510 100644 --- a/playground/ssr-webworker/__tests__/serve.ts +++ b/playground/ssr-webworker/__tests__/serve.ts @@ -21,8 +21,8 @@ export async function serve(): Promise<{ close(): Promise }> { build: { target: 'esnext', ssr: 'src/entry-worker.jsx', - outDir: 'dist/worker' - } + outDir: 'dist/worker', + }, }) const { createServer } = await import(path.resolve(rootDir, 'worker.js')) @@ -37,7 +37,7 @@ export async function serve(): Promise<{ close(): Promise }> { await new Promise((resolve) => { server.close(resolve) }) - } + }, }) }) } catch (e) { diff --git a/playground/ssr-webworker/src/entry-worker.jsx b/playground/ssr-webworker/src/entry-worker.jsx index 750926653f9e31..c5868fc229a137 100644 --- a/playground/ssr-webworker/src/entry-worker.jsx +++ b/playground/ssr-webworker/src/entry-worker.jsx @@ -17,9 +17,9 @@ addEventListener('fetch', function (event) { `, { headers: { - 'content-type': 'text/html' - } - } - ) + 'content-type': 'text/html', + }, + }, + ), ) }) diff --git a/playground/ssr-webworker/vite.config.js b/playground/ssr-webworker/vite.config.js index 3a476198813c35..af2b208bd4f3c2 100644 --- a/playground/ssr-webworker/vite.config.js +++ b/playground/ssr-webworker/vite.config.js @@ -2,33 +2,33 @@ import { defineConfig } from 'vite' export default defineConfig({ build: { - minify: false + minify: false, }, resolve: { - dedupe: ['react'] + dedupe: ['react'], }, ssr: { target: 'webworker', - noExternal: ['this-should-be-replaced-by-the-boolean'] + noExternal: ['this-should-be-replaced-by-the-boolean'], }, plugins: [ { config() { return { ssr: { - noExternal: true - } + noExternal: true, + }, } - } + }, }, { config() { return { ssr: { - noExternal: ['this-should-not-replace-the-boolean'] - } + noExternal: ['this-should-not-replace-the-boolean'], + }, } - } - } - ] + }, + }, + ], }) diff --git a/playground/ssr-webworker/worker.js b/playground/ssr-webworker/worker.js index d353688b0575eb..0f4d723a32c454 100644 --- a/playground/ssr-webworker/worker.js +++ b/playground/ssr-webworker/worker.js @@ -8,7 +8,7 @@ const isTest = !!process.env.TEST export async function createServer() { const mf = new Miniflare({ - scriptPath: path.resolve(__dirname, 'dist/worker/entry-worker.js') + scriptPath: path.resolve(__dirname, 'dist/worker/entry-worker.js'), }) const app = mf.createServer() @@ -20,6 +20,6 @@ if (!isTest) { createServer().then(({ app }) => app.listen(5173, () => { console.log('http://localhost:5173') - }) + }), ) } diff --git a/playground/tailwind-sourcemap/postcss.config.js b/playground/tailwind-sourcemap/postcss.config.js index ad6adc688915c1..1f45e3e358ac0b 100644 --- a/playground/tailwind-sourcemap/postcss.config.js +++ b/playground/tailwind-sourcemap/postcss.config.js @@ -2,6 +2,6 @@ console.log(__dirname + '/tailwind.config.js') module.exports = { plugins: { - tailwindcss: { config: __dirname + '/tailwind.config.js' } - } + tailwindcss: { config: __dirname + '/tailwind.config.js' }, + }, } diff --git a/playground/tailwind-sourcemap/tailwind.config.js b/playground/tailwind-sourcemap/tailwind.config.js index f89a536ccd742f..dd95de6c830d45 100644 --- a/playground/tailwind-sourcemap/tailwind.config.js +++ b/playground/tailwind-sourcemap/tailwind.config.js @@ -1,7 +1,7 @@ module.exports = { content: ['./index.html'], theme: { - extend: {} + extend: {}, }, - plugins: [] + plugins: [], } diff --git a/playground/tailwind-sourcemap/vite.config.js b/playground/tailwind-sourcemap/vite.config.js index 70fea77247bcd4..36815996e19f3d 100644 --- a/playground/tailwind-sourcemap/vite.config.js +++ b/playground/tailwind-sourcemap/vite.config.js @@ -3,9 +3,9 @@ */ module.exports = { css: { - devSourcemap: true + devSourcemap: true, }, build: { - sourcemap: true - } + sourcemap: true, + }, } diff --git a/playground/tailwind/__test__/tailwind.spec.ts b/playground/tailwind/__test__/tailwind.spec.ts index 64261d630b09d9..a95fd347cd75eb 100644 --- a/playground/tailwind/__test__/tailwind.spec.ts +++ b/playground/tailwind/__test__/tailwind.spec.ts @@ -6,7 +6,7 @@ import { isBuild, page, untilBrowserLogAfter, - untilUpdated + untilUpdated, } from '~utils' test('should render', async () => { @@ -22,26 +22,26 @@ if (!isBuild) { await untilBrowserLogAfter( () => editFile('src/views/Page.vue', (code) => - code.replace('|Page title|', '|Page title updated|') + code.replace('|Page title|', '|Page title updated|'), ), [ '[vite] css hot updated: /index.css', - '[vite] hot updated: /src/views/Page.vue' + '[vite] hot updated: /src/views/Page.vue', ], - true + true, ) await untilUpdated(() => el.textContent(), '|Page title updated|') await untilBrowserLogAfter( () => editFile('src/components/HelloWorld.vue', (code) => - code.replace('text-gray-800', 'text-[rgb(10,20,30)]') + code.replace('text-gray-800', 'text-[rgb(10,20,30)]'), ), [ '[vite] css hot updated: /index.css', - '[vite] hot updated: /src/components/HelloWorld.vue' + '[vite] hot updated: /src/components/HelloWorld.vue', ], - true + true, ) await untilUpdated(() => getColor(el2), 'rgb(10, 20, 30)') }) @@ -53,13 +53,13 @@ if (!isBuild) { await untilBrowserLogAfter( () => editFile('src/App.vue', (code) => - code.replace('text-black', 'text-[rgb(11,22,33)]') + code.replace('text-black', 'text-[rgb(11,22,33)]'), ), [ '[vite] css hot updated: /index.css', - '[vite] hot updated: /src/App.vue' + '[vite] hot updated: /src/App.vue', ], - true + true, ) await untilUpdated(() => getColor(el), 'rgb(11, 22, 33)') }) @@ -71,12 +71,12 @@ if (!isBuild) { await untilBrowserLogAfter( () => editFile('src/components/PugTemplate.vue', (code) => - code.replace('bg-red-400', 'bg-red-600') + code.replace('bg-red-400', 'bg-red-600'), ), [ '[vite] css hot updated: /index.css', - '[vite] hot updated: /src/components/PugTemplate.vue?vue&type=template&lang.js' - ] + '[vite] hot updated: /src/components/PugTemplate.vue?vue&type=template&lang.js', + ], ) await untilUpdated(() => getBgColor(el), 'rgb(220, 38, 38)') }) diff --git a/playground/tailwind/postcss.config.ts b/playground/tailwind/postcss.config.ts index 381d8cbd107f81..065645ac26db0c 100644 --- a/playground/tailwind/postcss.config.ts +++ b/playground/tailwind/postcss.config.ts @@ -2,6 +2,6 @@ module.exports = { plugins: { tailwindcss: { config: __dirname + '/tailwind.config.js' }, - autoprefixer: {} - } + autoprefixer: {}, + }, } diff --git a/playground/tailwind/src/router.ts b/playground/tailwind/src/router.ts index 2a8c3cd0dd966f..10e3980cb07cb8 100644 --- a/playground/tailwind/src/router.ts +++ b/playground/tailwind/src/router.ts @@ -8,9 +8,9 @@ const router = createRouter({ routes: [ { path: '/', - component: Page - } - ] + component: Page, + }, + ], }) export default router diff --git a/playground/tailwind/src/views/Page.vue b/playground/tailwind/src/views/Page.vue index 12fc2605339f1d..76f8aabf13d7d3 100644 --- a/playground/tailwind/src/views/Page.vue +++ b/playground/tailwind/src/views/Page.vue @@ -26,8 +26,8 @@ export default defineComponent({ return { name, - val + val, } - } + }, }) diff --git a/playground/tailwind/tailwind.config.js b/playground/tailwind/tailwind.config.js index d346b0549e2b35..5b9644f4f646d5 100644 --- a/playground/tailwind/tailwind.config.js +++ b/playground/tailwind/tailwind.config.js @@ -3,13 +3,13 @@ module.exports = { // Before editing this section, make sure no paths are matching with `/src/App.vue` // Look https://github.com/vitejs/vite/pull/6959 for more details __dirname + '/src/{components,views}/**/*.vue', - __dirname + '/src/App.vue' + __dirname + '/src/App.vue', ], theme: { - extend: {} + extend: {}, }, variants: { - extend: {} + extend: {}, }, - plugins: [] + plugins: [], } diff --git a/playground/tailwind/vite.config.ts b/playground/tailwind/vite.config.ts index ea895225460d48..d3680f6c39c3e3 100644 --- a/playground/tailwind/vite.config.ts +++ b/playground/tailwind/vite.config.ts @@ -4,17 +4,17 @@ import vue from '@vitejs/plugin-vue' export default defineConfig({ resolve: { alias: { - '/@': __dirname - } + '/@': __dirname, + }, }, plugins: [vue()], build: { // to make tests faster - minify: false + minify: false, }, server: { // This option caused issues with HMR, // although it should not affect the build - origin: 'http://localhost:8080' - } + origin: 'http://localhost:8080', + }, }) diff --git a/playground/test-utils.ts b/playground/test-utils.ts index 80e04bffb8bd02..d2aafaff4b2aca 100644 --- a/playground/test-utils.ts +++ b/playground/test-utils.ts @@ -29,14 +29,14 @@ export const ports = { 'ssr-webworker': 9606, 'css/postcss-caching': 5005, 'css/postcss-plugins-different-dir': 5006, - 'css/dynamic-import': 5007 + 'css/dynamic-import': 5007, } export const hmrPorts = { 'optimize-missing-deps': 24680, 'ssr-deps': 24681, 'ssr-html': 24682, 'ssr-noexternal': 24683, - 'ssr-pug': 24684 + 'ssr-pug': 24684, } const hexToNameMap: Record = {} @@ -96,7 +96,7 @@ export function readFile(filename: string): string { export function editFile( filename: string, replacer: (str: string) => string, - runInBuild: boolean = false + runInBuild: boolean = false, ): void { if (isBuild && !runInBuild) return filename = path.resolve(testDir, filename) @@ -121,7 +121,7 @@ export function listAssets(base = ''): string[] { export function findAssetFile( match: string | RegExp, base = '', - assets = 'assets' + assets = 'assets', ): string { const assetsDir = path.join(testDir, 'dist', base, assets) let files: string[] @@ -141,7 +141,7 @@ export function findAssetFile( export function readManifest(base = ''): Manifest { return JSON.parse( - fs.readFileSync(path.join(testDir, 'dist', base, 'manifest.json'), 'utf-8') + fs.readFileSync(path.join(testDir, 'dist', base, 'manifest.json'), 'utf-8'), ) } @@ -151,7 +151,7 @@ export function readManifest(base = ''): Manifest { export async function untilUpdated( poll: () => string | Promise, expected: string, - runInBuild = false + runInBuild = false, ): Promise { if (isBuild && !runInBuild) return const maxTries = process.env.CI ? 200 : 50 @@ -171,7 +171,7 @@ export async function untilUpdated( */ export async function withRetry( func: () => Promise, - runInBuild = false + runInBuild = false, ): Promise { if (isBuild && !runInBuild) return const maxTries = process.env.CI ? 200 : 50 @@ -191,18 +191,18 @@ export async function untilBrowserLogAfter( operation: () => any, target: string | RegExp | Array, expectOrder?: boolean, - callback?: UntilBrowserLogAfterCallback + callback?: UntilBrowserLogAfterCallback, ): Promise export async function untilBrowserLogAfter( operation: () => any, target: string | RegExp | Array, - callback?: UntilBrowserLogAfterCallback + callback?: UntilBrowserLogAfterCallback, ): Promise export async function untilBrowserLogAfter( operation: () => any, target: string | RegExp | Array, arg3?: boolean | UntilBrowserLogAfterCallback, - arg4?: UntilBrowserLogAfterCallback + arg4?: UntilBrowserLogAfterCallback, ): Promise { const expectOrder = typeof arg3 === 'boolean' ? arg3 : false const callback = typeof arg3 === 'boolean' ? arg4 : arg3 @@ -218,7 +218,7 @@ export async function untilBrowserLogAfter( async function untilBrowserLog( target?: string | RegExp | Array, - expectOrder = true + expectOrder = true, ): Promise { let resolve: () => void let reject: (reason: any) => void @@ -249,7 +249,7 @@ async function untilBrowserLog( const remainingMatchers = target.map(isMatch) processMsg = (text: string) => { const nextIndex = remainingMatchers.findIndex((matcher) => - matcher(text) + matcher(text), ) if (nextIndex >= 0) { remainingMatchers.splice(nextIndex, 1) @@ -300,7 +300,7 @@ export const formatSourcemapForSnapshot = (map: any): any => { // helper function to kill process, uses taskkill on windows to ensure child process is killed too export async function killProcess( - serverProcess: ExecaChildProcess + serverProcess: ExecaChildProcess, ): Promise { if (isWindows) { try { diff --git a/playground/transform-plugin/vite.config.js b/playground/transform-plugin/vite.config.js index 0b9ddb97c34304..b451ca77d6a398 100644 --- a/playground/transform-plugin/vite.config.js +++ b/playground/transform-plugin/vite.config.js @@ -17,9 +17,9 @@ const transformPlugin = { ${code} ` } - } + }, } module.exports = { - plugins: [transformPlugin] + plugins: [transformPlugin], } diff --git a/playground/tsconfig-json-load-error/__tests__/tsconfig-json-load-error.spec.ts b/playground/tsconfig-json-load-error/__tests__/tsconfig-json-load-error.spec.ts index 3ccc857c1f8a5b..5b3a0dfcd98138 100644 --- a/playground/tsconfig-json-load-error/__tests__/tsconfig-json-load-error.spec.ts +++ b/playground/tsconfig-json-load-error/__tests__/tsconfig-json-load-error.spec.ts @@ -7,14 +7,14 @@ import { isServe, page, readFile, - untilUpdated + untilUpdated, } from '~utils' describe.runIf(isBuild)('build', () => { test('should throw an error on build', () => { expect(serveError).toBeTruthy() expect(serveError.message).toMatch( - /^parsing .* failed: SyntaxError: Unexpected token \} in JSON at position \d+$/ + /^parsing .* failed: SyntaxError: Unexpected token \} in JSON at position \d+$/, ) clearServeError() // got expected error, null it here so testsuite does not fail from rethrow in afterAll }) @@ -46,7 +46,7 @@ describe.runIf(isServe)('server', () => { }) // use regex with variable filename and position values because they are different on win expect(message).toMatch( - /^parsing .* failed: SyntaxError: Unexpected token \} in JSON at position \d+$/ + /^parsing .* failed: SyntaxError: Unexpected token \} in JSON at position \d+$/, ) }) diff --git a/playground/tsconfig-json/__tests__/tsconfig-json.spec.ts b/playground/tsconfig-json/__tests__/tsconfig-json.spec.ts index f447174cf43f23..a5e2dd47d191cd 100644 --- a/playground/tsconfig-json/__tests__/tsconfig-json.spec.ts +++ b/playground/tsconfig-json/__tests__/tsconfig-json.spec.ts @@ -28,9 +28,9 @@ describe('transformWithEsbuild', () => { const result = await transformWithEsbuild(mainContent, main, { tsconfigRaw: { compilerOptions: { - useDefineForClassFields: false - } - } + useDefineForClassFields: false, + }, + }, }) // "importsNotUsedAsValues": "preserve" from tsconfig.json should still work expect(result.code).toContain('import "./not-used-type";') @@ -44,7 +44,7 @@ describe('transformWithEsbuild', () => { "compilerOptions": { "useDefineForClassFields": false } - }` + }`, }) // "importsNotUsedAsValues": "preserve" from tsconfig.json should not be read // and defaults to "remove" @@ -58,13 +58,13 @@ describe('transformWithEsbuild', () => { tsconfigRaw: { compilerOptions: { useDefineForClassFields: false, - preserveValueImports: true - } - } + preserveValueImports: true, + }, + }, }) // "importsNotUsedAsValues": "preserve" from tsconfig.json should still work expect(result.code).toContain( - 'import { MainTypeOnlyClass } from "./not-used-type";' + 'import { MainTypeOnlyClass } from "./not-used-type";', ) }) }) diff --git a/playground/vitestGlobalSetup.ts b/playground/vitestGlobalSetup.ts index 69430aaf3c3b38..7a63d6d12cc7ee 100644 --- a/playground/vitestGlobalSetup.ts +++ b/playground/vitestGlobalSetup.ts @@ -17,7 +17,7 @@ export async function setup(): Promise { headless: !process.env.VITE_DEBUG_SERVE, args: process.env.CI ? ['--no-sandbox', '--disable-setuid-sandbox'] - : undefined + : undefined, }) await fs.mkdirp(DIR) @@ -32,12 +32,12 @@ export async function setup(): Promise { filter(file) { file = file.replace(/\\/g, '/') return !file.includes('__tests__') && !file.match(/dist(\/|$)/) - } + }, }) .catch(async (error) => { if (error.code === 'EPERM' && error.syscall === 'symlink') { throw new Error( - 'Could not create symlinks. On Windows, consider activating Developer Mode to allow non-admin users to create symlinks by following the instructions at https://docs.microsoft.com/en-us/windows/apps/get-started/enable-your-device-for-development.' + 'Could not create symlinks. On Windows, consider activating Developer Mode to allow non-admin users to create symlinks by following the instructions at https://docs.microsoft.com/en-us/windows/apps/get-started/enable-your-device-for-development.', ) } else { throw error diff --git a/playground/vitestSetup.ts b/playground/vitestSetup.ts index e768f898caf58e..4a43252a0e251b 100644 --- a/playground/vitestSetup.ts +++ b/playground/vitestSetup.ts @@ -9,14 +9,14 @@ import type { PluginOption, ResolvedConfig, UserConfig, - ViteDevServer + ViteDevServer, } from 'vite' import { build, createServer, loadConfigFromFile, mergeConfig, - preview + preview, } from 'vite' import type { Browser, Page } from 'playwright-chromium' import type { RollupError, RollupWatcher, RollupWatcherEvent } from 'rollup' @@ -32,7 +32,7 @@ export const isServe = !isBuild export const isWindows = process.platform === 'win32' export const viteBinPath = path.posix.join( workspaceRoot, - 'packages/vite/bin/vite.js' + 'packages/vite/bin/vite.js', ) // #endregion @@ -151,7 +151,7 @@ beforeAll(async (s) => { const testCustomServe = [ resolve(dirname(testPath), 'serve.ts'), - resolve(dirname(testPath), 'serve.js') + resolve(dirname(testPath), 'serve.js'), ].find((i) => fs.existsSync(i)) if (testCustomServe) { @@ -196,10 +196,10 @@ function loadConfigFromDir(dir: string) { return loadConfigFromFile( { command: isBuild ? 'build' : 'serve', - mode: isBuild ? 'production' : 'development' + mode: isBuild ? 'production' : 'development', }, undefined, - dir + dir, ) } @@ -227,21 +227,21 @@ export async function startDefaultServe(): Promise { // During tests we edit the files too fast and sometimes chokidar // misses change events, so enforce polling for consistency usePolling: true, - interval: 100 + interval: 100, }, host: true, fs: { - strict: !isBuild - } + strict: !isBuild, + }, }, build: { // esbuild do not minify ES lib output since that would remove pure annotations and break tree-shaking // skip transpilation during tests to make it faster target: 'esnext', // tests are flaky when `emptyOutDir` is `true` - emptyOutDir: false + emptyOutDir: false, }, - customLogger: createInMemoryLogger(serverLogs) + customLogger: createInMemoryLogger(serverLogs), } setupConsoleWarnCollector(serverLogs) @@ -264,7 +264,7 @@ export async function startDefaultServe(): Promise { name: 'vite-plugin-watcher', configResolved(config) { resolvedConfig = config - } + }, }) options.plugins = [resolvedPlugin()] const testConfig = mergeConfig(options, config || {}) @@ -294,7 +294,7 @@ export async function startDefaultServe(): Promise { * Send the rebuild complete message in build watch */ export async function notifyRebuildComplete( - watcher: RollupWatcher + watcher: RollupWatcher, ): Promise { let resolveFn: undefined | (() => void) const callback = (event: RollupWatcherEvent): void => { @@ -335,7 +335,7 @@ function createInMemoryLogger(logs: string[]): Logger { if (opts?.error) { loggedErrors.add(opts.error) } - } + }, } return logger diff --git a/playground/wasm/__tests__/wasm.spec.ts b/playground/wasm/__tests__/wasm.spec.ts index 07f383d2eb8b48..49df35d35c7652 100644 --- a/playground/wasm/__tests__/wasm.spec.ts +++ b/playground/wasm/__tests__/wasm.spec.ts @@ -15,13 +15,13 @@ test('init function returns WebAssembly.Instance', async () => { await page.click('.init-returns-instance .run') await untilUpdated( () => page.textContent('.init-returns-instance .result'), - 'true' + 'true', ) }) test('?url', async () => { expect(await page.textContent('.url')).toMatch( - isBuild ? 'data:application/wasm' : '/light.wasm' + isBuild ? 'data:application/wasm' : '/light.wasm', ) }) diff --git a/playground/wasm/index.html b/playground/wasm/index.html index 2af0fda6847f2f..5eb5f9b532183e 100644 --- a/playground/wasm/index.html +++ b/playground/wasm/index.html @@ -41,8 +41,8 @@

worker wasm

async function testWasm(init, resultElement) { const { exported_func } = await init({ imports: { - imported_func: (res) => (resultElement.textContent = res) - } + imported_func: (res) => (resultElement.textContent = res), + }, }).then((i) => i.exports) exported_func() } @@ -54,13 +54,13 @@

worker wasm

document .querySelector('.inline-wasm .run') .addEventListener('click', async () => - testWasm(light, document.querySelector('.inline-wasm .result')) + testWasm(light, document.querySelector('.inline-wasm .result')), ) document .querySelector('.output-wasm .run') .addEventListener('click', async () => - testWasm(heavy, document.querySelector('.output-wasm .result')) + testWasm(heavy, document.querySelector('.output-wasm .result')), ) document @@ -68,12 +68,12 @@

worker wasm

.addEventListener('click', async () => { const res = await light({ imports: { - imported_func: (res) => (resultElement.textContent = res) - } + imported_func: (res) => (resultElement.textContent = res), + }, }) text( '.init-returns-instance .result', - res instanceof WebAssembly.Instance + res instanceof WebAssembly.Instance, ) }) diff --git a/playground/wasm/vite.config.ts b/playground/wasm/vite.config.ts index e52df8dc66c386..8c07ac5fd8bd34 100644 --- a/playground/wasm/vite.config.ts +++ b/playground/wasm/vite.config.ts @@ -3,6 +3,6 @@ export default defineConfig({ build: { // make cannot emit light.wasm // and emit add.wasm - assetsInlineLimit: 80 - } + assetsInlineLimit: 80, + }, }) diff --git a/playground/worker/__tests__/es/es-worker.spec.ts b/playground/worker/__tests__/es/es-worker.spec.ts index 8a890a3cd81332..39b4baddc61d31 100644 --- a/playground/worker/__tests__/es/es-worker.spec.ts +++ b/playground/worker/__tests__/es/es-worker.spec.ts @@ -8,17 +8,17 @@ test('normal', async () => { await untilUpdated( () => page.textContent('.mode'), process.env.NODE_ENV, - true + true, ) await untilUpdated( () => page.textContent('.bundle-with-plugin'), 'worker bundle with plugin success!', - true + true, ) await untilUpdated( () => page.textContent('.asset-url'), isBuild ? '/es/assets/worker_asset-vite.svg' : '/es/vite.svg', - true + true, ) }) @@ -38,17 +38,17 @@ test('worker emitted and import.meta.url in nested worker (serve)', async () => await untilUpdated( () => page.textContent('.nested-worker'), 'worker-nested-worker', - true + true, ) await untilUpdated( () => page.textContent('.nested-worker-module'), 'sub-worker', - true + true, ) await untilUpdated( () => page.textContent('.nested-worker-constructor'), '"type":"constructor"', - true + true, ) }) @@ -63,7 +63,7 @@ describe.runIf(isBuild)('build', () => { const worker = files.find((f) => f.includes('my-worker')) const workerContent = fs.readFileSync( path.resolve(assetsDir, worker), - 'utf-8' + 'utf-8', ) // worker should have all imports resolved and no exports @@ -81,12 +81,12 @@ describe.runIf(isBuild)('build', () => { await untilUpdated( () => page.textContent('.nested-worker-module'), '"type":"module"', - true + true, ) await untilUpdated( () => page.textContent('.nested-worker-constructor'), '"type":"constructor"', - true + true, ) }) }) @@ -95,17 +95,17 @@ test('module worker', async () => { await untilUpdated( () => page.textContent('.worker-import-meta-url'), 'A string', - true + true, ) await untilUpdated( () => page.textContent('.worker-import-meta-url-resolve'), 'A string', - true + true, ) await untilUpdated( () => page.textContent('.shared-worker-import-meta-url'), 'A string', - true + true, ) }) @@ -113,12 +113,12 @@ test('classic worker', async () => { await untilUpdated( () => page.textContent('.classic-worker'), 'A classic', - true + true, ) await untilUpdated( () => page.textContent('.classic-shared-worker'), 'A classic', - true + true, ) }) @@ -126,12 +126,12 @@ test('emit chunk', async () => { await untilUpdated( () => page.textContent('.emit-chunk-worker'), '["A string",{"type":"emit-chunk-sub-worker","data":"A string"},{"type":"module-and-worker:worker","data":"A string"},{"type":"module-and-worker:module","data":"module and worker"},{"type":"emit-chunk-sub-worker","data":{"module":"module and worker","msg1":"module1","msg2":"module2","msg3":"module3"}}]', - true + true, ) await untilUpdated( () => page.textContent('.emit-chunk-dynamic-import-worker'), '"A string/es/"', - true + true, ) }) @@ -139,7 +139,7 @@ test('url query worker', async () => { await untilUpdated( () => page.textContent('.simple-worker-url'), 'Hello from simple worker!', - true + true, ) }) @@ -147,7 +147,7 @@ test('import.meta.glob in worker', async () => { await untilUpdated( () => page.textContent('.importMetaGlob-worker'), '["', - true + true, ) }) @@ -155,6 +155,6 @@ test('import.meta.glob with eager in worker', async () => { await untilUpdated( () => page.textContent('.importMetaGlobEager-worker'), '["', - true + true, ) }) diff --git a/playground/worker/__tests__/iife/iife-worker.spec.ts b/playground/worker/__tests__/iife/iife-worker.spec.ts index 269f491eced410..5e81c84a777985 100644 --- a/playground/worker/__tests__/iife/iife-worker.spec.ts +++ b/playground/worker/__tests__/iife/iife-worker.spec.ts @@ -8,12 +8,12 @@ test('normal', async () => { await untilUpdated(() => page.textContent('.mode'), process.env.NODE_ENV) await untilUpdated( () => page.textContent('.bundle-with-plugin'), - 'worker bundle with plugin success!' + 'worker bundle with plugin success!', ) await untilUpdated( () => page.textContent('.asset-url'), isBuild ? '/iife/assets/worker_asset-vite.svg' : '/iife/vite.svg', - true + true, ) }) @@ -33,11 +33,11 @@ test('worker emitted and import.meta.url in nested worker (serve)', async () => await untilUpdated(() => page.textContent('.nested-worker'), '/worker-nested') await untilUpdated( () => page.textContent('.nested-worker-module'), - '/sub-worker' + '/sub-worker', ) await untilUpdated( () => page.textContent('.nested-worker-constructor'), - '"type":"constructor"' + '"type":"constructor"', ) }) @@ -52,7 +52,7 @@ describe.runIf(isBuild)('build', () => { const worker = files.find((f) => f.includes('my-worker')) const workerContent = fs.readFileSync( path.resolve(assetsDir, worker), - 'utf-8' + 'utf-8', ) // worker should have all imports resolved and no exports @@ -69,11 +69,11 @@ describe.runIf(isBuild)('build', () => { test('worker emitted and import.meta.url in nested worker (build)', async () => { await untilUpdated( () => page.textContent('.nested-worker-module'), - '"type":"module"' + '"type":"module"', ) await untilUpdated( () => page.textContent('.nested-worker-constructor'), - '"type":"constructor"' + '"type":"constructor"', ) }) }) @@ -81,15 +81,15 @@ describe.runIf(isBuild)('build', () => { test('module worker', async () => { await untilUpdated( () => page.textContent('.worker-import-meta-url'), - 'A string' + 'A string', ) await untilUpdated( () => page.textContent('.worker-import-meta-url-resolve'), - 'A string' + 'A string', ) await untilUpdated( () => page.textContent('.shared-worker-import-meta-url'), - 'A string' + 'A string', ) }) @@ -97,20 +97,20 @@ test('classic worker', async () => { await untilUpdated(() => page.textContent('.classic-worker'), 'A classic') await untilUpdated( () => page.textContent('.classic-shared-worker'), - 'A classic' + 'A classic', ) }) test('url query worker', async () => { await untilUpdated( () => page.textContent('.simple-worker-url'), - 'Hello from simple worker!' + 'Hello from simple worker!', ) }) test('import.meta.glob eager in worker', async () => { await untilUpdated( () => page.textContent('.importMetaGlobEager-worker'), - '["' + '["', ) }) diff --git a/playground/worker/__tests__/relative-base/relative-base-worker.spec.ts b/playground/worker/__tests__/relative-base/relative-base-worker.spec.ts index d38ced41d3c6e9..db8284a46b2863 100644 --- a/playground/worker/__tests__/relative-base/relative-base-worker.spec.ts +++ b/playground/worker/__tests__/relative-base/relative-base-worker.spec.ts @@ -8,17 +8,17 @@ test('normal', async () => { await untilUpdated( () => page.textContent('.mode'), process.env.NODE_ENV, - true + true, ) await untilUpdated( () => page.textContent('.bundle-with-plugin'), 'worker bundle with plugin success!', - true + true, ) await untilUpdated( () => page.textContent('.asset-url'), isBuild ? '/worker-assets/worker_asset-vite' : '/vite.svg', - true + true, ) }) @@ -39,17 +39,17 @@ test('worker emitted and import.meta.url in nested worker (serve)', async () => await untilUpdated( () => page.textContent('.nested-worker'), 'worker-nested-worker', - true + true, ) await untilUpdated( () => page.textContent('.nested-worker-module'), 'sub-worker', - true + true, ) await untilUpdated( () => page.textContent('.nested-worker-constructor'), '"type":"constructor"', - true + true, ) }) @@ -62,13 +62,13 @@ describe.runIf(isBuild)('build', () => { const content = fs.readFileSync(path.resolve(chunksDir, index), 'utf-8') const workerEntriesDir = path.resolve( testDir, - 'dist/relative-base/worker-entries' + 'dist/relative-base/worker-entries', ) const workerFiles = fs.readdirSync(workerEntriesDir) const worker = workerFiles.find((f) => f.includes('worker_entry-my-worker')) const workerContent = fs.readFileSync( path.resolve(workerEntriesDir, worker), - 'utf-8' + 'utf-8', ) // worker should have all imports resolved and no exports @@ -86,12 +86,12 @@ describe.runIf(isBuild)('build', () => { await untilUpdated( () => page.textContent('.nested-worker-module'), '"type":"module"', - true + true, ) await untilUpdated( () => page.textContent('.nested-worker-constructor'), '"type":"constructor"', - true + true, ) }) }) @@ -100,7 +100,7 @@ test('module worker', async () => { await untilUpdated( () => page.textContent('.shared-worker-import-meta-url'), 'A string', - true + true, ) }) @@ -108,12 +108,12 @@ test.runIf(isBuild)('classic worker', async () => { await untilUpdated( () => page.textContent('.classic-worker'), 'A classic', - true + true, ) await untilUpdated( () => page.textContent('.classic-shared-worker'), 'A classic', - true + true, ) }) @@ -121,12 +121,12 @@ test.runIf(isBuild)('emit chunk', async () => { await untilUpdated( () => page.textContent('.emit-chunk-worker'), '["A string",{"type":"emit-chunk-sub-worker","data":"A string"},{"type":"module-and-worker:worker","data":"A string"},{"type":"module-and-worker:module","data":"module and worker"},{"type":"emit-chunk-sub-worker","data":{"module":"module and worker","msg1":"module1","msg2":"module2","msg3":"module3"}}]', - true + true, ) await untilUpdated( () => page.textContent('.emit-chunk-dynamic-import-worker'), '"A string./"', - true + true, ) }) @@ -134,7 +134,7 @@ test('import.meta.glob in worker', async () => { await untilUpdated( () => page.textContent('.importMetaGlob-worker'), '["', - true + true, ) }) @@ -142,6 +142,6 @@ test('import.meta.glob with eager in worker', async () => { await untilUpdated( () => page.textContent('.importMetaGlobEager-worker'), '["', - true + true, ) }) diff --git a/playground/worker/__tests__/sourcemap-hidden/sourcemap-hidden-worker.spec.ts b/playground/worker/__tests__/sourcemap-hidden/sourcemap-hidden-worker.spec.ts index 38e55199121489..afcb51af117729 100644 --- a/playground/worker/__tests__/sourcemap-hidden/sourcemap-hidden-worker.spec.ts +++ b/playground/worker/__tests__/sourcemap-hidden/sourcemap-hidden-worker.spec.ts @@ -17,57 +17,57 @@ describe.runIf(isBuild)('build', () => { const worker = files.find((f) => /^my-worker-\w+\.js$/.test(f)) const workerContent = fs.readFileSync( path.resolve(assetsDir, worker), - 'utf-8' + 'utf-8', ) const workerSourcemap = getSourceMapUrl(workerContent) const sharedWorker = files.find((f) => /^my-shared-worker-\w+\.js$/.test(f)) const sharedWorkerContent = fs.readFileSync( path.resolve(assetsDir, sharedWorker), - 'utf-8' + 'utf-8', ) const sharedWorkerSourcemap = getSourceMapUrl(sharedWorkerContent) const possibleTsOutputWorker = files.find((f) => - /^possible-ts-output-worker-\w+\.js$/.test(f) + /^possible-ts-output-worker-\w+\.js$/.test(f), ) const possibleTsOutputWorkerContent = fs.readFileSync( path.resolve(assetsDir, possibleTsOutputWorker), - 'utf-8' + 'utf-8', ) const possibleTsOutputWorkerSourcemap = getSourceMapUrl( - possibleTsOutputWorkerContent + possibleTsOutputWorkerContent, ) const workerNestedWorker = files.find((f) => - /^worker-nested-worker-\w+\.js$/.test(f) + /^worker-nested-worker-\w+\.js$/.test(f), ) const workerNestedWorkerContent = fs.readFileSync( path.resolve(assetsDir, workerNestedWorker), - 'utf-8' + 'utf-8', ) const workerNestedWorkerSourcemap = getSourceMapUrl( - workerNestedWorkerContent + workerNestedWorkerContent, ) const subWorker = files.find((f) => /^sub-worker-\w+\.js$/.test(f)) const subWorkerContent = fs.readFileSync( path.resolve(assetsDir, subWorker), - 'utf-8' + 'utf-8', ) const subWorkerSourcemap = getSourceMapUrl(subWorkerContent) expect(files).toContainEqual(expect.stringMatching(/^index-\w+\.js\.map$/)) expect(files).toContainEqual( - expect.stringMatching(/^my-worker-\w+\.js\.map$/) + expect.stringMatching(/^my-worker-\w+\.js\.map$/), ) expect(files).toContainEqual( - expect.stringMatching(/^my-shared-worker-\w+\.js\.map$/) + expect.stringMatching(/^my-shared-worker-\w+\.js\.map$/), ) expect(files).toContainEqual( - expect.stringMatching(/^possible-ts-output-worker-\w+\.js\.map$/) + expect.stringMatching(/^possible-ts-output-worker-\w+\.js\.map$/), ) expect(files).toContainEqual( - expect.stringMatching(/^worker-nested-worker-\w+\.js\.map$/) + expect.stringMatching(/^worker-nested-worker-\w+\.js\.map$/), ) expect(files).toContainEqual( - expect.stringMatching(/^sub-worker-\w+\.js\.map$/) + expect.stringMatching(/^sub-worker-\w+\.js\.map$/), ) // sourcemap should exist and have a data URL @@ -88,17 +88,17 @@ describe.runIf(isBuild)('build', () => { // chunk expect(content).toMatch( - `new Worker("/iife-sourcemap-hidden/assets/my-worker` + `new Worker("/iife-sourcemap-hidden/assets/my-worker`, ) expect(content).toMatch(`new Worker("data:application/javascript;base64`) expect(content).toMatch( - `new Worker("/iife-sourcemap-hidden/assets/possible-ts-output-worker` + `new Worker("/iife-sourcemap-hidden/assets/possible-ts-output-worker`, ) expect(content).toMatch( - `new Worker("/iife-sourcemap-hidden/assets/worker-nested-worker` + `new Worker("/iife-sourcemap-hidden/assets/worker-nested-worker`, ) expect(content).toMatch( - `new SharedWorker("/iife-sourcemap-hidden/assets/my-shared-worker` + `new SharedWorker("/iife-sourcemap-hidden/assets/my-shared-worker`, ) // inlined @@ -106,7 +106,7 @@ describe.runIf(isBuild)('build', () => { expect(content).toMatch(`window.Blob`) expect(workerNestedWorkerContent).toMatch( - `new Worker("/iife-sourcemap-hidden/assets/sub-worker` + `new Worker("/iife-sourcemap-hidden/assets/sub-worker`, ) }) }) diff --git a/playground/worker/__tests__/sourcemap-inline/sourcemap-inline-worker.spec.ts b/playground/worker/__tests__/sourcemap-inline/sourcemap-inline-worker.spec.ts index 5f6aebd5917119..34c2498d8f72cc 100644 --- a/playground/worker/__tests__/sourcemap-inline/sourcemap-inline-worker.spec.ts +++ b/playground/worker/__tests__/sourcemap-inline/sourcemap-inline-worker.spec.ts @@ -17,39 +17,39 @@ describe.runIf(isBuild)('build', () => { const worker = files.find((f) => /^my-worker-\w+\.js$/.test(f)) const workerContent = fs.readFileSync( path.resolve(assetsDir, worker), - 'utf-8' + 'utf-8', ) const workerSourcemap = getSourceMapUrl(workerContent) const sharedWorker = files.find((f) => /^my-shared-worker-\w+\.js$/.test(f)) const sharedWorkerContent = fs.readFileSync( path.resolve(assetsDir, sharedWorker), - 'utf-8' + 'utf-8', ) const sharedWorkerSourcemap = getSourceMapUrl(sharedWorkerContent) const possibleTsOutputWorker = files.find((f) => - /^possible-ts-output-worker-\w+\.js$/.test(f) + /^possible-ts-output-worker-\w+\.js$/.test(f), ) const possibleTsOutputWorkerContent = fs.readFileSync( path.resolve(assetsDir, possibleTsOutputWorker), - 'utf-8' + 'utf-8', ) const possibleTsOutputWorkerSourcemap = getSourceMapUrl( - possibleTsOutputWorkerContent + possibleTsOutputWorkerContent, ) const workerNestedWorker = files.find((f) => - /^worker-nested-worker-\w+\.js$/.test(f) + /^worker-nested-worker-\w+\.js$/.test(f), ) const workerNestedWorkerContent = fs.readFileSync( path.resolve(assetsDir, workerNestedWorker), - 'utf-8' + 'utf-8', ) const workerNestedWorkerSourcemap = getSourceMapUrl( - workerNestedWorkerContent + workerNestedWorkerContent, ) const subWorker = files.find((f) => /^sub-worker-\w+\.js$/.test(f)) const subWorkerContent = fs.readFileSync( path.resolve(assetsDir, subWorker), - 'utf-8' + 'utf-8', ) const subWorkerSourcemap = getSourceMapUrl(subWorkerContent) @@ -71,17 +71,17 @@ describe.runIf(isBuild)('build', () => { // chunk expect(content).toMatch( - `new Worker("/iife-sourcemap-inline/assets/my-worker` + `new Worker("/iife-sourcemap-inline/assets/my-worker`, ) expect(content).toMatch(`new Worker("data:application/javascript;base64`) expect(content).toMatch( - `new Worker("/iife-sourcemap-inline/assets/possible-ts-output-worker` + `new Worker("/iife-sourcemap-inline/assets/possible-ts-output-worker`, ) expect(content).toMatch( - `new Worker("/iife-sourcemap-inline/assets/worker-nested-worker` + `new Worker("/iife-sourcemap-inline/assets/worker-nested-worker`, ) expect(content).toMatch( - `new SharedWorker("/iife-sourcemap-inline/assets/my-shared-worker` + `new SharedWorker("/iife-sourcemap-inline/assets/my-shared-worker`, ) // inlined @@ -89,7 +89,7 @@ describe.runIf(isBuild)('build', () => { expect(content).toMatch(`window.Blob`) expect(workerNestedWorkerContent).toMatch( - `new Worker("/iife-sourcemap-inline/assets/sub-worker` + `new Worker("/iife-sourcemap-inline/assets/sub-worker`, ) }) }) diff --git a/playground/worker/__tests__/sourcemap/sourcemap-worker.spec.ts b/playground/worker/__tests__/sourcemap/sourcemap-worker.spec.ts index 89fb5064612ac7..04f272b1487a8c 100644 --- a/playground/worker/__tests__/sourcemap/sourcemap-worker.spec.ts +++ b/playground/worker/__tests__/sourcemap/sourcemap-worker.spec.ts @@ -16,57 +16,57 @@ describe.runIf(isBuild)('build', () => { const worker = files.find((f) => /^my-worker-\w+\.js$/.test(f)) const workerContent = fs.readFileSync( path.resolve(assetsDir, worker), - 'utf-8' + 'utf-8', ) const workerSourcemap = getSourceMapUrl(workerContent) const sharedWorker = files.find((f) => /^my-shared-worker-\w+\.js$/.test(f)) const sharedWorkerContent = fs.readFileSync( path.resolve(assetsDir, sharedWorker), - 'utf-8' + 'utf-8', ) const sharedWorkerSourcemap = getSourceMapUrl(sharedWorkerContent) const possibleTsOutputWorker = files.find((f) => - /^possible-ts-output-worker-\w+\.js$/.test(f) + /^possible-ts-output-worker-\w+\.js$/.test(f), ) const possibleTsOutputWorkerContent = fs.readFileSync( path.resolve(assetsDir, possibleTsOutputWorker), - 'utf-8' + 'utf-8', ) const possibleTsOutputWorkerSourcemap = getSourceMapUrl( - possibleTsOutputWorkerContent + possibleTsOutputWorkerContent, ) const workerNestedWorker = files.find((f) => - /^worker-nested-worker-\w+\.js$/.test(f) + /^worker-nested-worker-\w+\.js$/.test(f), ) const workerNestedWorkerContent = fs.readFileSync( path.resolve(assetsDir, workerNestedWorker), - 'utf-8' + 'utf-8', ) const workerNestedWorkerSourcemap = getSourceMapUrl( - workerNestedWorkerContent + workerNestedWorkerContent, ) const subWorker = files.find((f) => /^sub-worker-\w+\.js$/.test(f)) const subWorkerContent = fs.readFileSync( path.resolve(assetsDir, subWorker), - 'utf-8' + 'utf-8', ) const subWorkerSourcemap = getSourceMapUrl(subWorkerContent) expect(files).toContainEqual(expect.stringMatching(/^index-\w+\.js\.map$/)) expect(files).toContainEqual( - expect.stringMatching(/^my-worker-\w+\.js\.map$/) + expect.stringMatching(/^my-worker-\w+\.js\.map$/), ) expect(files).toContainEqual( - expect.stringMatching(/^my-shared-worker-\w+\.js\.map$/) + expect.stringMatching(/^my-shared-worker-\w+\.js\.map$/), ) expect(files).toContainEqual( - expect.stringMatching(/^possible-ts-output-worker-\w+\.js\.map$/) + expect.stringMatching(/^possible-ts-output-worker-\w+\.js\.map$/), ) expect(files).toContainEqual( - expect.stringMatching(/^worker-nested-worker-\w+\.js\.map$/) + expect.stringMatching(/^worker-nested-worker-\w+\.js\.map$/), ) expect(files).toContainEqual( - expect.stringMatching(/^sub-worker-\w+\.js\.map$/) + expect.stringMatching(/^sub-worker-\w+\.js\.map$/), ) // sourcemap should exist and have a data URL @@ -74,10 +74,10 @@ describe.runIf(isBuild)('build', () => { expect(workerSourcemap).toMatch(/^my-worker-\w+\.js\.map$/) expect(sharedWorkerSourcemap).toMatch(/^my-shared-worker-\w+\.js\.map$/) expect(possibleTsOutputWorkerSourcemap).toMatch( - /^possible-ts-output-worker-\w+\.js\.map$/ + /^possible-ts-output-worker-\w+\.js\.map$/, ) expect(workerNestedWorkerSourcemap).toMatch( - /^worker-nested-worker-\w+\.js\.map$/ + /^worker-nested-worker-\w+\.js\.map$/, ) expect(subWorkerSourcemap).toMatch(/^sub-worker-\w+\.js\.map$/) @@ -93,13 +93,13 @@ describe.runIf(isBuild)('build', () => { expect(content).toMatch(`new Worker("/iife-sourcemap/assets/my-worker`) expect(content).toMatch(`new Worker("data:application/javascript;base64`) expect(content).toMatch( - `new Worker("/iife-sourcemap/assets/possible-ts-output-worker` + `new Worker("/iife-sourcemap/assets/possible-ts-output-worker`, ) expect(content).toMatch( - `new Worker("/iife-sourcemap/assets/worker-nested-worker` + `new Worker("/iife-sourcemap/assets/worker-nested-worker`, ) expect(content).toMatch( - `new SharedWorker("/iife-sourcemap/assets/my-shared-worker` + `new SharedWorker("/iife-sourcemap/assets/my-shared-worker`, ) // inlined @@ -107,7 +107,7 @@ describe.runIf(isBuild)('build', () => { expect(content).toMatch(`window.Blob`) expect(workerNestedWorkerContent).toMatch( - `new Worker("/iife-sourcemap/assets/sub-worker` + `new Worker("/iife-sourcemap/assets/sub-worker`, ) }) }) diff --git a/playground/worker/emit-chunk-nested-worker.js b/playground/worker/emit-chunk-nested-worker.js index 629322033f3d9b..4f23af6e913b29 100644 --- a/playground/worker/emit-chunk-nested-worker.js +++ b/playground/worker/emit-chunk-nested-worker.js @@ -4,26 +4,26 @@ const subWorker = new SubWorker() subWorker.onmessage = (event) => { self.postMessage({ type: 'emit-chunk-sub-worker', - data: event.data + data: event.data, }) } const moduleWorker = new Worker( new URL('./module-and-worker.js', import.meta.url), - { type: 'module' } + { type: 'module' }, ) moduleWorker.onmessage = (event) => { self.postMessage({ type: 'module-and-worker:worker', - data: event.data + data: event.data, }) } import('./module-and-worker').then((res) => { self.postMessage({ type: 'module-and-worker:module', - data: res.module + data: res.module, }) }) diff --git a/playground/worker/emit-chunk-sub-worker.js b/playground/worker/emit-chunk-sub-worker.js index 60d302e20bbb8a..16391db42dc3e0 100644 --- a/playground/worker/emit-chunk-sub-worker.js +++ b/playground/worker/emit-chunk-sub-worker.js @@ -1,7 +1,7 @@ Promise.all([ import('./module-and-worker'), import('./modules/module2'), - import('./modules/module3') + import('./modules/module3'), ]).then((data) => { const _data = { ...data[0], ...data[1], ...data[2] } self.postMessage(_data) diff --git a/playground/worker/vite.config-es.js b/playground/worker/vite.config-es.js index 16eaefe41d28d4..9ec9f2c540bef6 100644 --- a/playground/worker/vite.config-es.js +++ b/playground/worker/vite.config-es.js @@ -6,8 +6,8 @@ module.exports = vite.defineConfig({ enforce: 'pre', resolve: { alias: { - '@': __dirname - } + '@': __dirname, + }, }, worker: { format: 'es', @@ -16,9 +16,9 @@ module.exports = vite.defineConfig({ output: { assetFileNames: 'assets/worker_asset-[name].[ext]', chunkFileNames: 'assets/worker_chunk-[name].js', - entryFileNames: 'assets/worker_entry-[name].js' - } - } + entryFileNames: 'assets/worker_entry-[name].js', + }, + }, }, build: { outDir: 'dist/es', @@ -26,9 +26,9 @@ module.exports = vite.defineConfig({ output: { assetFileNames: 'assets/[name].[ext]', chunkFileNames: 'assets/[name].js', - entryFileNames: 'assets/[name].js' - } - } + entryFileNames: 'assets/[name].js', + }, + }, }, plugins: [ { @@ -38,10 +38,10 @@ module.exports = vite.defineConfig({ if (id.includes('main.js')) { return code.replace( `/* flag: will replace in vite config import("./format-es.js") */`, - `import("./main-format-es")` + `import("./main-format-es")`, ) } - } - } - ] + }, + }, + ], }) diff --git a/playground/worker/vite.config-iife.js b/playground/worker/vite.config-iife.js index cf05e278d2a1f7..80a8fb4d005418 100644 --- a/playground/worker/vite.config-iife.js +++ b/playground/worker/vite.config-iife.js @@ -5,8 +5,8 @@ module.exports = vite.defineConfig({ base: '/iife/', resolve: { alias: { - '@': __dirname - } + '@': __dirname, + }, }, worker: { format: 'iife', @@ -19,22 +19,22 @@ module.exports = vite.defineConfig({ worker: { rollupOptions: { output: { - entryFileNames: 'assets/worker_entry-[name].js' - } - } - } + entryFileNames: 'assets/worker_entry-[name].js', + }, + }, + }, } - } - } + }, + }, ], rollupOptions: { output: { assetFileNames: 'assets/worker_asset-[name].[ext]', chunkFileNames: 'assets/worker_chunk-[name].js', // should fix by config-test plugin - entryFileNames: 'assets/worker_-[name].js' - } - } + entryFileNames: 'assets/worker_-[name].js', + }, + }, }, build: { outDir: 'dist/iife', @@ -42,8 +42,8 @@ module.exports = vite.defineConfig({ output: { assetFileNames: 'assets/[name].[ext]', chunkFileNames: 'assets/[name].js', - entryFileNames: 'assets/[name].js' - } - } - } + entryFileNames: 'assets/[name].js', + }, + }, + }, }) diff --git a/playground/worker/vite.config-relative-base.js b/playground/worker/vite.config-relative-base.js index 019194e7441c95..d1750034910a5d 100644 --- a/playground/worker/vite.config-relative-base.js +++ b/playground/worker/vite.config-relative-base.js @@ -6,8 +6,8 @@ module.exports = vite.defineConfig({ base: './', resolve: { alias: { - '@': __dirname - } + '@': __dirname, + }, }, worker: { format: 'es', @@ -16,9 +16,9 @@ module.exports = vite.defineConfig({ output: { assetFileNames: 'worker-assets/worker_asset-[name]-[hash].[ext]', chunkFileNames: 'worker-chunks/worker_chunk-[name]-[hash].js', - entryFileNames: 'worker-entries/worker_entry-[name]-[hash].js' - } - } + entryFileNames: 'worker-entries/worker_entry-[name]-[hash].js', + }, + }, }, build: { outDir: 'dist/relative-base', @@ -26,12 +26,12 @@ module.exports = vite.defineConfig({ output: { assetFileNames: 'other-assets/[name]-[hash].[ext]', chunkFileNames: 'chunks/[name]-[hash].js', - entryFileNames: 'entries/[name]-[hash].js' - } - } + entryFileNames: 'entries/[name]-[hash].js', + }, + }, }, testConfig: { - baseRoute: '/relative-base/' + baseRoute: '/relative-base/', }, plugins: [ { @@ -40,10 +40,10 @@ module.exports = vite.defineConfig({ if (id.includes('main.js')) { return code.replace( `/* flag: will replace in vite config import("./format-es.js") */`, - `import("./main-format-es")` + `import("./main-format-es")`, ) } - } - } - ] + }, + }, + ], }) diff --git a/playground/worker/vite.config-sourcemap.js b/playground/worker/vite.config-sourcemap.js index e8ea73ca74489d..380e4bcc014d8e 100644 --- a/playground/worker/vite.config-sourcemap.js +++ b/playground/worker/vite.config-sourcemap.js @@ -12,8 +12,8 @@ module.exports = vite.defineConfig((sourcemap) => { }/`, resolve: { alias: { - '@': __dirname - } + '@': __dirname, + }, }, worker: { format: 'iife', @@ -22,9 +22,9 @@ module.exports = vite.defineConfig((sourcemap) => { output: { assetFileNames: 'assets/[name]-worker_asset[hash].[ext]', chunkFileNames: 'assets/[name]-worker_chunk[hash].js', - entryFileNames: 'assets/[name]-worker_entry[hash].js' - } - } + entryFileNames: 'assets/[name]-worker_entry[hash].js', + }, + }, }, build: { outDir: `dist/iife-${ @@ -35,9 +35,9 @@ module.exports = vite.defineConfig((sourcemap) => { output: { assetFileNames: 'assets/[name]-[hash].[ext]', chunkFileNames: 'assets/[name]-[hash].js', - entryFileNames: 'assets/[name]-[hash].js' - } - } - } + entryFileNames: 'assets/[name]-[hash].js', + }, + }, + }, } }) diff --git a/playground/worker/worker-nested-worker.js b/playground/worker/worker-nested-worker.js index f49c020754c957..e451edc608660c 100644 --- a/playground/worker/worker-nested-worker.js +++ b/playground/worker/worker-nested-worker.js @@ -14,17 +14,17 @@ self.postMessage(self.location.href) subWorker.onmessage = (ev) => { self.postMessage({ type: 'module', - data: ev.data + data: ev.data, }) } const classicWorker = new Worker(new URL('./url-worker.js', import.meta.url), { - type: 'module' + type: 'module', }) classicWorker.addEventListener('message', (ev) => { self.postMessage({ type: 'constructor', - data: ev.data + data: ev.data, }) }) @@ -35,7 +35,7 @@ importMetaGlobEagerWorker.postMessage('1') importMetaGlobEagerWorker.addEventListener('message', (ev) => { self.postMessage({ type: 'importMetaGlobEager', - data: ev.data + data: ev.data, }) }) diff --git a/playground/worker/worker/main-classic.js b/playground/worker/worker/main-classic.js index 39b8cbbe560ece..ed1c7392877190 100644 --- a/playground/worker/worker/main-classic.js +++ b/playground/worker/worker/main-classic.js @@ -4,7 +4,7 @@ function text(el, text) { } let classicWorker = new Worker( - new URL('../classic-worker.js', import.meta.url) /* , */ + new URL('../classic-worker.js', import.meta.url) /* , */, // test comment ) diff --git a/playground/worker/worker/main-format-es.js b/playground/worker/worker/main-format-es.js index 2a385556c58684..fc9af128e72b62 100644 --- a/playground/worker/worker/main-format-es.js +++ b/playground/worker/worker/main-format-es.js @@ -16,17 +16,17 @@ nestedWorker.addEventListener('message', (ev) => { '.emit-chunk-worker', JSON.stringify( dataList.sort( - (a, b) => JSON.stringify(a).length - JSON.stringify(b).length - ) - ) + (a, b) => JSON.stringify(a).length - JSON.stringify(b).length, + ), + ), ) }) const dynamicImportWorker = new Worker( new URL('../emit-chunk-dynamic-import-worker.js', import.meta.url), { - type: 'module' - } + type: 'module', + }, ) dynamicImportWorker.addEventListener('message', (ev) => { text('.emit-chunk-dynamic-import-worker', JSON.stringify(ev.data)) @@ -34,7 +34,7 @@ dynamicImportWorker.addEventListener('message', (ev) => { const moduleWorker = new Worker( new URL('../module-and-worker.js', import.meta.url), - { type: 'module' } + { type: 'module' }, ) moduleWorker.addEventListener('message', (ev) => { diff --git a/playground/worker/worker/main-module.js b/playground/worker/worker/main-module.js index 21c1dcadb853a9..1e5242935cdbb8 100644 --- a/playground/worker/worker/main-module.js +++ b/playground/worker/worker/main-module.js @@ -59,19 +59,19 @@ const workerOptions = { type: 'module' } // url import worker const w = new Worker( new URL('../url-worker.js', import.meta.url), - /* @vite-ignore */ workerOptions + /* @vite-ignore */ workerOptions, ) w.addEventListener('message', (ev) => - text('.worker-import-meta-url', JSON.stringify(ev.data)) + text('.worker-import-meta-url', JSON.stringify(ev.data)), ) // url import worker with alias path const wResolve = new Worker( new URL('@/url-worker.js', import.meta.url), - /* @vite-ignore */ workerOptions + /* @vite-ignore */ workerOptions, ) wResolve.addEventListener('message', (ev) => - text('.worker-import-meta-url-resolve', JSON.stringify(ev.data)) + text('.worker-import-meta-url-resolve', JSON.stringify(ev.data)), ) const genWorkerName = () => 'module' @@ -80,8 +80,8 @@ const w2 = new SharedWorker( { /* @vite-ignore */ name: genWorkerName(), - type: 'module' - } + type: 'module', + }, ) w2.port.addEventListener('message', (ev) => { text('.shared-worker-import-meta-url', JSON.stringify(ev.data)) @@ -90,7 +90,7 @@ w2.port.start() const workers = import.meta.glob('../importMetaGlobEager.*.js', { as: 'worker', - eager: true + eager: true, }) const importMetaGlobEagerWorker = new workers[ '../importMetaGlobEager.worker.js' diff --git a/scripts/publishCI.ts b/scripts/publishCI.ts index 903eb5f36f8733..02dbef74908032 100644 --- a/scripts/publishCI.ts +++ b/scripts/publishCI.ts @@ -4,7 +4,7 @@ import { getActiveVersion, getPackageInfo, publishPackage, - step + step, } from './releaseUtils' async function main() { @@ -25,7 +25,7 @@ async function main() { const { currentVersion, pkgDir } = getPackageInfo(pkgName) if (currentVersion !== version) throw new Error( - `Package version from tag "${version}" mismatches with current version "${currentVersion}"` + `Package version from tag "${version}" mismatches with current version "${currentVersion}"`, ) const activeVersion = await getActiveVersion(pkgName) diff --git a/scripts/release.ts b/scripts/release.ts index 36d9b22f397726..b17f328518bcf1 100644 --- a/scripts/release.ts +++ b/scripts/release.ts @@ -12,7 +12,7 @@ import { runIfNotDry, step, updateTemplateVersions, - updateVersion + updateVersion, } from './releaseUtils' async function main(): Promise { @@ -22,7 +22,7 @@ async function main(): Promise { type: 'select', name: 'pkg', message: 'Select package', - choices: packages.map((i) => ({ value: i, title: i })) + choices: packages.map((i) => ({ value: i, title: i })), }) if (!pkg) return @@ -36,7 +36,7 @@ async function main(): Promise { type: 'select', name: 'release', message: 'Select release type', - choices: getVersionChoices(currentVersion) + choices: getVersionChoices(currentVersion), }) if (release === 'custom') { @@ -44,7 +44,7 @@ async function main(): Promise { type: 'text', name: 'version', message: 'Input custom version', - initial: currentVersion + initial: currentVersion, }) targetVersion = res.version } else { @@ -69,7 +69,7 @@ async function main(): Promise { const { yes }: { yes: boolean } = await prompts({ type: 'confirm', name: 'yes', - message: `Releasing ${colors.yellow(tag)} Confirm?` + message: `Releasing ${colors.yellow(tag)} Confirm?`, }) if (!yes) { @@ -89,7 +89,7 @@ async function main(): Promise { 'CHANGELOG.md', '-s', '--commit-path', - '.' + '.', ] if (pkgName !== 'vite') changelogArgs.push('--lerna-package', pkgName) await run('npx', changelogArgs, { cwd: pkgDir }) @@ -114,8 +114,8 @@ async function main(): Promise { } else { console.log( colors.green( - '\nPushed, publishing should starts shortly on CI.\nhttps://github.com/vitejs/vite/actions/workflows/publish.yml' - ) + '\nPushed, publishing should starts shortly on CI.\nhttps://github.com/vitejs/vite/actions/workflows/publish.yml', + ), ) } diff --git a/scripts/releaseUtils.ts b/scripts/releaseUtils.ts index 48dff6bde229b1..9a7d18d2d99e8d 100644 --- a/scripts/releaseUtils.ts +++ b/scripts/releaseUtils.ts @@ -25,7 +25,7 @@ export const packages = ['vite', 'create-vite', 'plugin-legacy'] export const versionIncrements: ReleaseType[] = [ 'patch', 'minor', - 'major' + 'major', // 'prepatch', // 'preminor', // 'premajor', @@ -63,14 +63,14 @@ export function getPackageInfo(pkgName: string): { pkgName, pkgDir, pkgPath, - currentVersion + currentVersion, } } export async function run( bin: string, args: string[], - opts: ExecaOptions = {} + opts: ExecaOptions = {}, ): Promise> { return execa(bin, args, { stdio: 'inherit', ...opts }) } @@ -78,11 +78,11 @@ export async function run( export async function dryRun( bin: string, args: string[], - opts?: ExecaOptions + opts?: ExecaOptions, ): Promise { return console.log( colors.blue(`[dryrun] ${bin} ${args.join(' ')}`), - opts || '' + opts || '', ) } @@ -108,46 +108,46 @@ export function getVersionChoices(currentVersion: string): VersionChoice[] { let versionChoices: VersionChoice[] = [ { title: 'next', - value: inc(isStable ? 'patch' : 'prerelease') - } + value: inc(isStable ? 'patch' : 'prerelease'), + }, ] if (isStable) { versionChoices.push( { title: 'beta-minor', - value: inc('preminor') + value: inc('preminor'), }, { title: 'beta-major', - value: inc('premajor') + value: inc('premajor'), }, { title: 'alpha-minor', - value: inc('preminor', 'alpha') + value: inc('preminor', 'alpha'), }, { title: 'alpha-major', - value: inc('premajor', 'alpha') + value: inc('premajor', 'alpha'), }, { title: 'minor', - value: inc('minor') + value: inc('minor'), }, { title: 'major', - value: inc('major') - } + value: inc('major'), + }, ) } else if (currentAlpha) { versionChoices.push({ title: 'beta', - value: inc('patch') + '-beta.0' + value: inc('patch') + '-beta.0', }) } else { versionChoices.push({ title: 'stable', - value: inc('patch') + value: inc('patch'), }) } versionChoices.push({ value: 'custom', title: 'custom' }) @@ -168,14 +168,14 @@ export function updateVersion(pkgPath: string, version: string): void { export async function publishPackage( pkdDir: string, - tag?: string + tag?: string, ): Promise { const publicArgs = ['publish', '--access', 'public'] if (tag) { publicArgs.push(`--tag`, tag) } await runIfNotDry('npm', publicArgs, { - cwd: pkdDir + cwd: pkdDir, }) } @@ -203,14 +203,14 @@ export async function logRecentCommits(pkgName: string): Promise { const tag = await getLatestTag(pkgName) if (!tag) return const sha = await run('git', ['rev-list', '-n', '1', tag], { - stdio: 'pipe' + stdio: 'pipe', }).then((res) => res.stdout.trim()) console.log( colors.bold( `\n${colors.blue(`i`)} Commits of ${colors.green( - pkgName - )} since ${colors.green(tag)} ${colors.gray(`(${sha.slice(0, 5)})`)}` - ) + pkgName, + )} since ${colors.green(tag)} ${colors.gray(`(${sha.slice(0, 5)})`)}`, + ), ) await run( 'git', @@ -220,9 +220,9 @@ export async function logRecentCommits(pkgName: string): Promise { `${sha}..HEAD`, '--oneline', '--', - `packages/${pkgName}` + `packages/${pkgName}`, ], - { stdio: 'inherit' } + { stdio: 'inherit' }, ) console.log() } @@ -236,7 +236,7 @@ export async function updateTemplateVersions(): Promise { const dir = path.resolve(__dirname, '../packages/create-vite') const templates = readdirSync(dir).filter((dir) => - dir.startsWith('template-') + dir.startsWith('template-'), ) for (const template of templates) { const pkgPath = path.join(dir, template, `package.json`) @@ -247,7 +247,7 @@ export async function updateTemplateVersions(): Promise { `^` + ( await fs.readJSON( - path.resolve(__dirname, '../packages/plugin-vue/package.json') + path.resolve(__dirname, '../packages/plugin-vue/package.json'), ) ).version } @@ -256,7 +256,7 @@ export async function updateTemplateVersions(): Promise { `^` + ( await fs.readJSON( - path.resolve(__dirname, '../packages/plugin-react/package.json') + path.resolve(__dirname, '../packages/plugin-react/package.json'), ) ).version } diff --git a/scripts/rollupLicensePlugin.mjs b/scripts/rollupLicensePlugin.mjs index fedbd34b4fd660..3d527afb0129f7 100644 --- a/scripts/rollupLicensePlugin.mjs +++ b/scripts/rollupLicensePlugin.mjs @@ -18,7 +18,7 @@ function licensePlugin(licenseFilePath, licenseTitle, packageName) { // https://github.com/rollup/rollup/blob/master/build-plugins/generate-license-file.js // MIT Licensed https://github.com/rollup/rollup/blob/master/LICENSE-CORE.md const coreLicense = fs.readFileSync( - new URL('../LICENSE', import.meta.url) + new URL('../LICENSE', import.meta.url), ) function sortLicenses(licenses) { let withParenthesis = [] @@ -49,7 +49,7 @@ function licensePlugin(licenseFilePath, licenseTitle, packageName) { author, maintainers, contributors, - repository + repository, }) => { let text = `## ${name}\n` if (license) { @@ -74,11 +74,11 @@ function licensePlugin(licenseFilePath, licenseTitle, packageName) { try { const pkgDir = path.dirname( resolve.sync(path.join(name, 'package.json'), { - preserveSymlinks: false - }) + preserveSymlinks: false, + }), ) const licenseFile = fg.sync(`${pkgDir}/LICENSE*`, { - caseSensitiveMatch: false + caseSensitiveMatch: false, })[0] if (licenseFile) { licenseText = fs.readFileSync(licenseFile, 'utf-8') @@ -98,7 +98,7 @@ function licensePlugin(licenseFilePath, licenseTitle, packageName) { } licenses.add(license) return text - } + }, ) .join('\n---------------------------------------\n\n') const licenseText = @@ -115,11 +115,11 @@ function licensePlugin(licenseFilePath, licenseTitle, packageName) { fs.writeFileSync(licenseFilePath, licenseText) console.warn( colors.yellow( - '\nLICENSE.md updated. You should commit the updated file.\n' - ) + '\nLICENSE.md updated. You should commit the updated file.\n', + ), ) } - } + }, }) } diff --git a/scripts/verifyCommit.ts b/scripts/verifyCommit.ts index 92bf5c46bd7bb6..6a47d4c835076c 100644 --- a/scripts/verifyCommit.ts +++ b/scripts/verifyCommit.ts @@ -15,14 +15,14 @@ if (!releaseRE.test(msg) && !commitRE.test(msg)) { console.log() console.error( ` ${colors.bgRed(colors.white(' ERROR '))} ${colors.red( - `invalid commit message format.` + `invalid commit message format.`, )}\n\n` + colors.red( - ` Proper commit message format is required for automated changelog generation. Examples:\n\n` + ` Proper commit message format is required for automated changelog generation. Examples:\n\n`, ) + ` ${colors.green(`feat: add 'comments' option`)}\n` + ` ${colors.green(`fix: handle events on blur (close #28)`)}\n\n` + - colors.red(` See .github/commit-convention.md for more details.\n`) + colors.red(` See .github/commit-convention.md for more details.\n`), ) process.exit(1) } diff --git a/vitest.config.e2e.ts b/vitest.config.e2e.ts index da47d97de9abea..fe474509ecc210 100644 --- a/vitest.config.e2e.ts +++ b/vitest.config.e2e.ts @@ -6,8 +6,8 @@ const timeout = process.env.CI ? 50000 : 30000 export default defineConfig({ resolve: { alias: { - '~utils': resolve(__dirname, './playground/test-utils') - } + '~utils': resolve(__dirname, './playground/test-utils'), + }, }, test: { include: ['./playground/**/*.spec.[tj]s'], @@ -19,9 +19,9 @@ export default defineConfig({ onConsoleLog(log) { if (log.match(/experimental|jit engine|emitted file|tailwind/i)) return false - } + }, }, esbuild: { - target: 'node14' - } + target: 'node14', + }, }) diff --git a/vitest.config.ts b/vitest.config.ts index 0a8f8c2ff22648..f86aad8dd8b15b 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -6,11 +6,11 @@ export default defineConfig({ '**/node_modules/**', '**/dist/**', './playground/**/*.*', - './playground-temp/**/*.*' + './playground-temp/**/*.*', ], - testTimeout: 20000 + testTimeout: 20000, }, esbuild: { - target: 'node14' - } + target: 'node14', + }, })