vite 2.5.5 → 2.5.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of vite might be problematic. Click here for more details.

Files changed (36) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/dist/node/chunks/{dep-07ec9cdd.js → dep-05fcddd5.js} +258 -222
  3. package/dist/node/chunks/dep-05fcddd5.js.map +1 -0
  4. package/dist/node/chunks/{dep-a247570d.js → dep-499befab.js} +2 -2
  5. package/dist/node/chunks/{dep-a247570d.js.map → dep-499befab.js.map} +1 -1
  6. package/dist/node/chunks/{dep-8a1f5a00.js → dep-58243dfd.js} +2 -2
  7. package/dist/node/chunks/{dep-8a1f5a00.js.map → dep-58243dfd.js.map} +1 -1
  8. package/dist/node/chunks/{dep-ebe44577.js → dep-fcb82982.js} +2 -2
  9. package/dist/node/chunks/{dep-ebe44577.js.map → dep-fcb82982.js.map} +1 -1
  10. package/dist/node/cli.js +4 -4
  11. package/dist/node/index.d.ts +13 -8
  12. package/dist/node/index.js +2 -1
  13. package/dist/node/index.js.map +1 -1
  14. package/package.json +1 -1
  15. package/src/node/__tests__/build.spec.ts +39 -4
  16. package/src/node/__tests__/packages/name/package.json +3 -0
  17. package/src/node/__tests__/packages/noname/package.json +1 -0
  18. package/src/node/build.ts +15 -10
  19. package/src/node/config.ts +9 -1
  20. package/src/node/index.ts +2 -0
  21. package/src/node/optimizer/esbuildDepPlugin.ts +3 -2
  22. package/src/node/plugin.ts +2 -2
  23. package/src/node/plugins/esbuild.ts +51 -33
  24. package/src/node/plugins/importAnalysis.ts +6 -4
  25. package/src/node/plugins/importAnalysisBuild.ts +1 -1
  26. package/src/node/server/index.ts +5 -21
  27. package/src/node/server/middlewares/spaFallback.ts +32 -0
  28. package/src/node/server/pluginContainer.ts +0 -13
  29. package/src/node/server/transformRequest.ts +1 -0
  30. package/src/node/ssr/__tests__/ssrTransform.spec.ts +22 -22
  31. package/src/node/ssr/ssrExternal.ts +10 -4
  32. package/src/node/ssr/ssrTransform.ts +6 -1
  33. package/.DS_Store +0 -0
  34. package/dist/node/chunks/dep-07ec9cdd.js.map +0 -1
  35. package/src/node/.DS_Store +0 -0
  36. package/yarn-error.log +0 -8027
package/dist/node/cli.js CHANGED
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  var require$$0$1 = require('events');
4
- var build = require('./chunks/dep-07ec9cdd.js');
4
+ var build = require('./chunks/dep-05fcddd5.js');
5
5
  var path = require('path');
6
6
  var require$$0$2 = require('tty');
7
7
  var require$$0$3 = require('util');
@@ -14002,7 +14002,7 @@ cli
14002
14002
  .action(async (root, options) => {
14003
14003
  // output structure is preserved even after bundling so require()
14004
14004
  // is ok here
14005
- const { createServer } = await Promise.resolve().then(function () { return require('./chunks/dep-07ec9cdd.js'); }).then(function (n) { return n.index$1; });
14005
+ const { createServer } = await Promise.resolve().then(function () { return require('./chunks/dep-05fcddd5.js'); }).then(function (n) { return n.index$1; });
14006
14006
  try {
14007
14007
  const server = await createServer({
14008
14008
  root,
@@ -14036,7 +14036,7 @@ cli
14036
14036
  .option('--emptyOutDir', `[boolean] force empty outDir when it's outside of root`)
14037
14037
  .option('-w, --watch', `[boolean] rebuilds when modules have changed on disk`)
14038
14038
  .action(async (root, options) => {
14039
- const { build: build$1 } = await Promise.resolve().then(function () { return require('./chunks/dep-07ec9cdd.js'); }).then(function (n) { return n.build$1; });
14039
+ const { build: build$1 } = await Promise.resolve().then(function () { return require('./chunks/dep-05fcddd5.js'); }).then(function (n) { return n.build$1; });
14040
14040
  const buildOptions = cleanOptions(options);
14041
14041
  try {
14042
14042
  await build$1({
@@ -14059,7 +14059,7 @@ cli
14059
14059
  .command('optimize [root]')
14060
14060
  .option('--force', `[boolean] force the optimizer to ignore the cache and re-bundle`)
14061
14061
  .action(async (root, options) => {
14062
- const { optimizeDeps } = await Promise.resolve().then(function () { return require('./chunks/dep-07ec9cdd.js'); }).then(function (n) { return n.index; });
14062
+ const { optimizeDeps } = await Promise.resolve().then(function () { return require('./chunks/dep-05fcddd5.js'); }).then(function (n) { return n.index; });
14063
14063
  try {
14064
14064
  const config = await build.resolveConfig({
14065
14065
  root,
@@ -1,8 +1,8 @@
1
1
  /// <reference types="node" />
2
2
 
3
3
  import { BuildOptions as BuildOptions_2 } from 'esbuild';
4
- import { ChangeEvent } from 'rollup';
5
4
  import { CustomPluginOptions } from 'rollup';
5
+ import { TransformOptions as EsbuildTransformOptions } from 'esbuild';
6
6
  import * as events from 'events';
7
7
  import * as fs from 'fs';
8
8
  import * as http from 'http';
@@ -29,7 +29,6 @@ import { ServerResponse } from 'http';
29
29
  import { SourceDescription } from 'rollup';
30
30
  import { SourceMap } from 'rollup';
31
31
  import * as stream from 'stream';
32
- import { TransformOptions as TransformOptions_2 } from 'esbuild';
33
32
  import { TransformPluginContext } from 'rollup';
34
33
  import { TransformResult as TransformResult_2 } from 'rollup';
35
34
  import { TransformResult as TransformResult_3 } from 'esbuild';
@@ -90,7 +89,7 @@ export declare interface BuildOptions {
90
89
  * For custom targets, see https://esbuild.github.io/api/#target and
91
90
  * https://esbuild.github.io/content-types/#javascript for more details.
92
91
  */
93
- target?: 'modules' | TransformOptions_2['target'] | false;
92
+ target?: 'modules' | EsbuildTransformOptions['target'] | false;
94
93
  /**
95
94
  * whether to inject module preload polyfill.
96
95
  * Note: does not apply to library mode.
@@ -472,12 +471,14 @@ export declare interface ErrorPayload {
472
471
  }
473
472
  }
474
473
 
475
- export declare interface ESBuildOptions extends TransformOptions_2 {
474
+ export declare interface ESBuildOptions extends EsbuildTransformOptions {
476
475
  include?: string | RegExp | string[] | RegExp[];
477
476
  exclude?: string | RegExp | string[] | RegExp[];
478
477
  jsxInject?: string;
479
478
  }
480
479
 
480
+ export { EsbuildTransformOptions }
481
+
481
482
  export declare type ESBuildTransformResult = Omit<TransformResult_3, 'map'> & {
482
483
  map: SourceMap;
483
484
  };
@@ -1072,9 +1073,9 @@ export declare interface Plugin extends Plugin_2 {
1072
1073
  */
1073
1074
  enforce?: 'pre' | 'post';
1074
1075
  /**
1075
- * Apply the plugin only for serve or for build.
1076
+ * Apply the plugin only for serve or build, or on certain conditions.
1076
1077
  */
1077
- apply?: 'serve' | 'build';
1078
+ apply?: 'serve' | 'build' | ((config: UserConfig, env: ConfigEnv) => boolean);
1078
1079
  /**
1079
1080
  * Modify vite config before it's resolved. The hook can either mutate the
1080
1081
  * passed-in config directly, or return a partial config object that will be
@@ -1143,7 +1144,6 @@ export declare interface Plugin extends Plugin_2 {
1143
1144
  export declare interface PluginContainer {
1144
1145
  options: InputOptions;
1145
1146
  buildStart(options: InputOptions): Promise<void>;
1146
- watchChange(id: string, event?: ChangeEvent): void;
1147
1147
  resolveId(id: string, importer?: string, skip?: Set<Plugin>, ssr?: boolean): Promise<PartialResolvedId | null>;
1148
1148
  transform(code: string, id: string, inMap?: SourceDescription['map'], ssr?: boolean): Promise<SourceDescription | null>;
1149
1149
  load(id: string, ssr?: boolean): Promise<LoadResult | null>;
@@ -1683,8 +1683,11 @@ export declare interface TransformResult {
1683
1683
  map: SourceMap | null;
1684
1684
  etag?: string;
1685
1685
  deps?: string[];
1686
+ dynamicDeps?: string[];
1686
1687
  }
1687
1688
 
1689
+ export declare function transformWithEsbuild(code: string, filename: string, options?: EsbuildTransformOptions, inMap?: object): Promise<ESBuildTransformResult>;
1690
+
1688
1691
  export declare interface Update {
1689
1692
  type: 'js-update' | 'css-update'
1690
1693
  path: string
@@ -1871,8 +1874,10 @@ export declare interface ViteDevServer {
1871
1874
  /**
1872
1875
  * Util for transforming a file with esbuild.
1873
1876
  * Can be useful for certain plugins.
1877
+ *
1878
+ * @deprecated import `transformWithEsbuild` from `vite` instead
1874
1879
  */
1875
- transformWithEsbuild(code: string, filename: string, options?: TransformOptions_2, inMap?: object): Promise<ESBuildTransformResult>;
1880
+ transformWithEsbuild(code: string, filename: string, options?: EsbuildTransformOptions, inMap?: object): Promise<ESBuildTransformResult>;
1876
1881
  /**
1877
1882
  * Load a given URL as an instantiated module for SSR.
1878
1883
  */
@@ -2,7 +2,7 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var build = require('./chunks/dep-07ec9cdd.js');
5
+ var build = require('./chunks/dep-05fcddd5.js');
6
6
  require('fs');
7
7
  require('path');
8
8
  require('os');
@@ -47,4 +47,5 @@ exports.resolvePackageData = build.resolvePackageData;
47
47
  exports.resolvePackageEntry = build.resolvePackageEntry;
48
48
  exports.send = build.send;
49
49
  exports.sortUserPlugins = build.sortUserPlugins;
50
+ exports.transformWithEsbuild = build.transformWithEsbuild;
50
51
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vite",
3
- "version": "2.5.5",
3
+ "version": "2.5.9",
4
4
  "license": "MIT",
5
5
  "author": "Evan You",
6
6
  "description": "Native-ESM powered web dev build tool",
@@ -1,4 +1,5 @@
1
1
  import { resolveLibFilename } from '../build'
2
+ import { resolve } from 'path'
2
3
 
3
4
  describe('resolveLibFilename', () => {
4
5
  test('custom filename function', () => {
@@ -8,7 +9,7 @@ describe('resolveLibFilename', () => {
8
9
  entry: 'mylib.js'
9
10
  },
10
11
  'es',
11
- 'mylib'
12
+ resolve(__dirname, 'packages/name')
12
13
  )
13
14
 
14
15
  expect(filename).toBe('custom-filename-function.es.js')
@@ -16,17 +17,51 @@ describe('resolveLibFilename', () => {
16
17
 
17
18
  test('custom filename string', () => {
18
19
  const filename = resolveLibFilename(
19
- { fileName: 'custom-filename', entry: 'mylib.js' },
20
+ {
21
+ fileName: 'custom-filename',
22
+ entry: 'mylib.js'
23
+ },
20
24
  'es',
21
- 'mylib'
25
+ resolve(__dirname, 'packages/name')
22
26
  )
23
27
 
24
28
  expect(filename).toBe('custom-filename.es.js')
25
29
  })
26
30
 
27
31
  test('package name as filename', () => {
28
- const filename = resolveLibFilename({ entry: 'mylib.js' }, 'es', 'mylib')
32
+ const filename = resolveLibFilename(
33
+ {
34
+ entry: 'mylib.js'
35
+ },
36
+ 'es',
37
+ resolve(__dirname, 'packages/name')
38
+ )
29
39
 
30
40
  expect(filename).toBe('mylib.es.js')
31
41
  })
42
+
43
+ test('custom filename and no package name', () => {
44
+ const filename = resolveLibFilename(
45
+ {
46
+ fileName: 'custom-filename',
47
+ entry: 'mylib.js'
48
+ },
49
+ 'es',
50
+ resolve(__dirname, 'packages/noname')
51
+ )
52
+
53
+ expect(filename).toBe('custom-filename.es.js')
54
+ })
55
+
56
+ test('missing filename', () => {
57
+ expect(() => {
58
+ resolveLibFilename(
59
+ {
60
+ entry: 'mylib.js'
61
+ },
62
+ 'es',
63
+ resolve(__dirname, 'packages/noname')
64
+ )
65
+ }).toThrow()
66
+ })
32
67
  })
@@ -0,0 +1,3 @@
1
+ {
2
+ "name": "mylib"
3
+ }
package/src/node/build.ts CHANGED
@@ -422,8 +422,6 @@ async function doBuild(
422
422
  }
423
423
 
424
424
  try {
425
- const pkgName = libOptions && getPkgName(config.root)
426
-
427
425
  const buildOutputOptions = (output: OutputOptions = {}): OutputOptions => {
428
426
  return {
429
427
  dir: outDir,
@@ -434,7 +432,7 @@ async function doBuild(
434
432
  entryFileNames: ssr
435
433
  ? `[name].js`
436
434
  : libOptions
437
- ? resolveLibFilename(libOptions, output.format || 'es', pkgName)
435
+ ? resolveLibFilename(libOptions, output.format || 'es', config.root)
438
436
  : path.posix.join(options.assetsDir, `[name].[hash].js`),
439
437
  chunkFileNames: libOptions
440
438
  ? `[name].js`
@@ -576,9 +574,7 @@ function prepareOutDir(
576
574
  function getPkgName(root: string) {
577
575
  const { name } = JSON.parse(lookupFile(root, ['package.json']) || `{}`)
578
576
 
579
- if (!name) throw new Error('no name found in package.json')
580
-
581
- return name.startsWith('@') ? name.split('/')[1] : name
577
+ return name?.startsWith('@') ? name.split('/')[1] : name
582
578
  }
583
579
 
584
580
  function createMoveToVendorChunkFn(config: ResolvedConfig): GetManualChunk {
@@ -633,11 +629,20 @@ function staticImportedByEntry(
633
629
  export function resolveLibFilename(
634
630
  libOptions: LibraryOptions,
635
631
  format: ModuleFormat,
636
- pkgName: string
632
+ root: string
637
633
  ): string {
638
- return typeof libOptions.fileName === 'function'
639
- ? libOptions.fileName(format)
640
- : `${libOptions.fileName || pkgName}.${format}.js`
634
+ if (typeof libOptions.fileName === 'function') {
635
+ return libOptions.fileName(format)
636
+ }
637
+
638
+ const name = libOptions.fileName || getPkgName(root)
639
+
640
+ if (!name)
641
+ throw new Error(
642
+ 'Name in package.json is required if option "build.lib.fileName" is not provided.'
643
+ )
644
+
645
+ return `${name}.${format}.js`
641
646
  }
642
647
 
643
648
  function resolveBuildOutputs(
@@ -285,7 +285,15 @@ export async function resolveConfig(
285
285
 
286
286
  // resolve plugins
287
287
  const rawUserPlugins = (config.plugins || []).flat().filter((p) => {
288
- return p && (!p.apply || p.apply === command)
288
+ if (!p) {
289
+ return false
290
+ } else if (!p.apply) {
291
+ return true
292
+ } else if (typeof p.apply === 'function') {
293
+ return p.apply({ ...config, mode }, configEnv)
294
+ } else {
295
+ return p.apply === command
296
+ }
289
297
  }) as Plugin[]
290
298
  const [prePlugins, normalPlugins, postPlugins] =
291
299
  sortUserPlugins(rawUserPlugins)
package/src/node/index.ts CHANGED
@@ -4,6 +4,7 @@ export { build } from './build'
4
4
  export { optimizeDeps } from './optimizer'
5
5
  export { send } from './server/send'
6
6
  export { createLogger } from './logger'
7
+ export { transformWithEsbuild } from './plugins/esbuild'
7
8
  export { resolvePackageData, resolvePackageEntry } from './plugins/resolve'
8
9
  export { normalizePath } from './utils'
9
10
 
@@ -51,6 +52,7 @@ export type {
51
52
  } from './plugins/html'
52
53
  export type { CSSOptions, CSSModulesOptions } from './plugins/css'
53
54
  export type { JsonOptions } from './plugins/json'
55
+ export type { TransformOptions as EsbuildTransformOptions } from 'esbuild'
54
56
  export type { ESBuildOptions, ESBuildTransformResult } from './plugins/esbuild'
55
57
  export type { Manifest, ManifestChunk } from './plugins/manifest'
56
58
  export type {
@@ -6,7 +6,8 @@ import {
6
6
  isRunningWithYarnPnp,
7
7
  flattenId,
8
8
  normalizePath,
9
- isExternalUrl
9
+ isExternalUrl,
10
+ isBuiltin
10
11
  } from '../utils'
11
12
  import { browserExternalId } from '../plugins/resolve'
12
13
  import { ExportsData } from '.'
@@ -119,7 +120,7 @@ export function esbuildDepPlugin(
119
120
  namespace: 'browser-external'
120
121
  }
121
122
  }
122
- if (isExternalUrl(resolved)) {
123
+ if (isExternalUrl(resolved) || (ssr && isBuiltin(id))) {
123
124
  return {
124
125
  path: resolved,
125
126
  external: true
@@ -50,9 +50,9 @@ export interface Plugin extends RollupPlugin {
50
50
  */
51
51
  enforce?: 'pre' | 'post'
52
52
  /**
53
- * Apply the plugin only for serve or for build.
53
+ * Apply the plugin only for serve or build, or on certain conditions.
54
54
  */
55
- apply?: 'serve' | 'build'
55
+ apply?: 'serve' | 'build' | ((config: UserConfig, env: ConfigEnv) => boolean)
56
56
  /**
57
57
  * Modify vite config before it's resolved. The hook can either mutate the
58
58
  * passed-in config directly, or return a partial config object that will be
@@ -50,52 +50,70 @@ export async function transformWithEsbuild(
50
50
  options?: TransformOptions,
51
51
  inMap?: object
52
52
  ): Promise<ESBuildTransformResult> {
53
- // if the id ends with a valid ext, use it (e.g. vue blocks)
54
- // otherwise, cleanup the query before checking the ext
55
- const ext = path.extname(
56
- /\.\w+$/.test(filename) ? filename : cleanUrl(filename)
57
- )
53
+ let loader = options?.loader
54
+
55
+ if (!loader) {
56
+ // if the id ends with a valid ext, use it (e.g. vue blocks)
57
+ // otherwise, cleanup the query before checking the ext
58
+ const ext = path
59
+ .extname(/\.\w+$/.test(filename) ? filename : cleanUrl(filename))
60
+ .slice(1)
58
61
 
59
- let loader = ext.slice(1)
60
- if (loader === 'cjs' || loader === 'mjs') {
61
- loader = 'js'
62
+ if (ext === 'cjs' || ext === 'mjs') {
63
+ loader = 'js'
64
+ } else {
65
+ loader = ext as Loader
66
+ }
62
67
  }
63
68
 
64
- // these fields would affect the compilation result
65
- // https://esbuild.github.io/content-types/#tsconfig-json
66
- const meaningfulFields: Array<keyof TSCompilerOptions> = [
67
- 'jsxFactory',
68
- 'jsxFragmentFactory',
69
- 'useDefineForClassFields',
70
- 'importsNotUsedAsValues'
71
- ]
72
- const compilerOptionsForFile: TSCompilerOptions = {}
73
- if (loader === 'ts' || loader === 'tsx') {
74
- const loadedTsconfig = await loadTsconfigJsonForFile(filename)
75
- const loadedCompilerOptions = loadedTsconfig.compilerOptions ?? {}
76
-
77
- for (const field of meaningfulFields) {
78
- if (field in loadedCompilerOptions) {
79
- // @ts-ignore TypeScript can't tell they are of the same type
80
- compilerOptionsForFile[field] = loadedCompilerOptions[field]
69
+ let tsconfigRaw = options?.tsconfigRaw
70
+
71
+ // if options provide tsconfigraw in string, it takes highest precedence
72
+ if (typeof tsconfigRaw !== 'string') {
73
+ // these fields would affect the compilation result
74
+ // https://esbuild.github.io/content-types/#tsconfig-json
75
+ const meaningfulFields: Array<keyof TSCompilerOptions> = [
76
+ 'jsxFactory',
77
+ 'jsxFragmentFactory',
78
+ 'useDefineForClassFields',
79
+ 'importsNotUsedAsValues'
80
+ ]
81
+ const compilerOptionsForFile: TSCompilerOptions = {}
82
+ if (loader === 'ts' || loader === 'tsx') {
83
+ const loadedTsconfig = await loadTsconfigJsonForFile(filename)
84
+ const loadedCompilerOptions = loadedTsconfig.compilerOptions ?? {}
85
+
86
+ for (const field of meaningfulFields) {
87
+ if (field in loadedCompilerOptions) {
88
+ // @ts-ignore TypeScript can't tell they are of the same type
89
+ compilerOptionsForFile[field] = loadedCompilerOptions[field]
90
+ }
91
+ }
92
+
93
+ // align with TypeScript 4.3
94
+ // https://github.com/microsoft/TypeScript/pull/42663
95
+ if (loadedCompilerOptions.target?.toLowerCase() === 'esnext') {
96
+ compilerOptionsForFile.useDefineForClassFields =
97
+ loadedCompilerOptions.useDefineForClassFields ?? true
81
98
  }
82
99
  }
83
100
 
84
- // align with TypeScript 4.3
85
- // https://github.com/microsoft/TypeScript/pull/42663
86
- if (loadedCompilerOptions.target?.toLowerCase() === 'esnext') {
87
- compilerOptionsForFile.useDefineForClassFields =
88
- loadedCompilerOptions.useDefineForClassFields ?? true
101
+ tsconfigRaw = {
102
+ ...tsconfigRaw,
103
+ compilerOptions: {
104
+ ...compilerOptionsForFile,
105
+ ...tsconfigRaw?.compilerOptions
106
+ }
89
107
  }
90
108
  }
91
109
 
92
110
  const resolvedOptions = {
93
- loader: loader as Loader,
94
111
  sourcemap: true,
95
112
  // ensure source file name contains full query
96
113
  sourcefile: filename,
97
- tsconfigRaw: { compilerOptions: compilerOptionsForFile },
98
- ...options
114
+ ...options,
115
+ loader,
116
+ tsconfigRaw
99
117
  } as ESBuildOptions
100
118
 
101
119
  delete resolvedOptions.include
@@ -118,7 +118,7 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
118
118
  }
119
119
  try {
120
120
  imports = parseImports(source)[0]
121
- } catch (e) {
121
+ } catch (e: any) {
122
122
  const isVue = importer.endsWith('.vue')
123
123
  const maybeJSX = !isVue && isJSRequest(importer)
124
124
 
@@ -189,6 +189,7 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
189
189
  }
190
190
 
191
191
  const isRelative = url.startsWith('.')
192
+ const isSelfImport = !isRelative && cleanUrl(url) === cleanUrl(importer)
192
193
 
193
194
  // normalize all imports into resolved URLs
194
195
  // e.g. `import 'foo'` -> `import '/@fs/.../node_modules/foo/index.js`
@@ -219,10 +220,11 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
219
220
  // mark non-js/css imports with `?import`
220
221
  url = markExplicitImport(url)
221
222
 
222
- // for relative js/css imports, inherit importer's version query
223
+ // for relative js/css imports, or self-module virtual imports
224
+ // (e.g. vue blocks), inherit importer's version query
223
225
  // do not do this for unknown type imports, otherwise the appended
224
226
  // query can break 3rd party plugin's extension checks.
225
- if (isRelative && !/[\?&]import=?\b/.test(url)) {
227
+ if ((isRelative || isSelfImport) && !/[\?&]import=?\b/.test(url)) {
226
228
  const versionMatch = importer.match(DEP_VERSION_RE)
227
229
  if (versionMatch) {
228
230
  url = injectQuery(url, versionMatch[1])
@@ -237,7 +239,7 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
237
239
  if (depModule.lastHMRTimestamp > 0) {
238
240
  url = injectQuery(url, `t=${depModule.lastHMRTimestamp}`)
239
241
  }
240
- } catch (e) {
242
+ } catch (e: any) {
241
243
  // it's possible that the dep fails to resolve (non-existent import)
242
244
  // attach location to the missing import
243
245
  e.pos = pos
@@ -264,7 +264,7 @@ export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin {
264
264
  const cssFiles = chunkToEmittedCssFileMap.get(chunk)
265
265
  if (cssFiles && cssFiles.size > 0) {
266
266
  cssFiles.forEach((file) => {
267
- deps.add(config.base + file)
267
+ deps.add(file)
268
268
  })
269
269
  hasRemovedPureCssChunk = true
270
270
  }
@@ -15,12 +15,12 @@ import { FSWatcher, WatchOptions } from 'types/chokidar'
15
15
  import { createWebSocketServer, WebSocketServer } from './ws'
16
16
  import { baseMiddleware } from './middlewares/base'
17
17
  import { proxyMiddleware, ProxyOptions } from './middlewares/proxy'
18
+ import { spaFallbackMiddleware } from './middlewares/spaFallback'
18
19
  import { transformMiddleware } from './middlewares/transform'
19
20
  import {
20
21
  createDevHtmlTransformFn,
21
22
  indexHtmlMiddleware
22
23
  } from './middlewares/indexHtml'
23
- import history from 'connect-history-api-fallback'
24
24
  import {
25
25
  serveRawFsMiddleware,
26
26
  servePublicMiddleware,
@@ -29,7 +29,7 @@ import {
29
29
  import { timeMiddleware } from './middlewares/time'
30
30
  import { ModuleGraph, ModuleNode } from './moduleGraph'
31
31
  import { Connect } from 'types/connect'
32
- import { createDebugger, ensureLeadingSlash, normalizePath } from '../utils'
32
+ import { ensureLeadingSlash, normalizePath } from '../utils'
33
33
  import { errorMiddleware, prepareError } from './middlewares/error'
34
34
  import { handleHMRUpdate, HmrOptions, handleFileAddUnlink } from './hmr'
35
35
  import { openBrowser } from './openBrowser'
@@ -237,6 +237,8 @@ export interface ViteDevServer {
237
237
  /**
238
238
  * Util for transforming a file with esbuild.
239
239
  * Can be useful for certain plugins.
240
+ *
241
+ * @deprecated import `transformWithEsbuild` from `vite` instead
240
242
  */
241
243
  transformWithEsbuild(
242
244
  code: string,
@@ -502,25 +504,7 @@ export async function createServer(
502
504
 
503
505
  // spa fallback
504
506
  if (!middlewareMode || middlewareMode === 'html') {
505
- middlewares.use(
506
- history({
507
- logger: createDebugger('vite:spa-fallback'),
508
- // support /dir/ without explicit index.html
509
- rewrites: [
510
- {
511
- from: /\/$/,
512
- to({ parsedUrl }: any) {
513
- const rewritten = parsedUrl.pathname + 'index.html'
514
- if (fs.existsSync(path.join(root, rewritten))) {
515
- return rewritten
516
- } else {
517
- return `/index.html`
518
- }
519
- }
520
- }
521
- ]
522
- })
523
- )
507
+ middlewares.use(spaFallbackMiddleware(root))
524
508
  }
525
509
 
526
510
  // run post config hooks
@@ -0,0 +1,32 @@
1
+ import fs from 'fs'
2
+ import history from 'connect-history-api-fallback'
3
+ import path from 'path'
4
+ import { Connect } from 'types/connect'
5
+ import { createDebugger } from '../../utils'
6
+
7
+ export function spaFallbackMiddleware(
8
+ root: string
9
+ ): Connect.NextHandleFunction {
10
+ const historySpaFallbackMiddleware = history({
11
+ logger: createDebugger('vite:spa-fallback'),
12
+ // support /dir/ without explicit index.html
13
+ rewrites: [
14
+ {
15
+ from: /\/$/,
16
+ to({ parsedUrl }: any) {
17
+ const rewritten = parsedUrl.pathname + 'index.html'
18
+ if (fs.existsSync(path.join(root, rewritten))) {
19
+ return rewritten
20
+ } else {
21
+ return `/index.html`
22
+ }
23
+ }
24
+ }
25
+ ]
26
+ })
27
+
28
+ // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
29
+ return function viteSpaFallbackMiddleware(req, res, next) {
30
+ return historySpaFallbackMiddleware(req, res, next)
31
+ }
32
+ }
@@ -38,7 +38,6 @@ import {
38
38
  OutputOptions,
39
39
  ModuleInfo,
40
40
  NormalizedInputOptions,
41
- ChangeEvent,
42
41
  PartialResolvedId,
43
42
  ResolvedId,
44
43
  PluginContext as RollupPluginContext,
@@ -82,7 +81,6 @@ export interface PluginContainerOptions {
82
81
  export interface PluginContainer {
83
82
  options: InputOptions
84
83
  buildStart(options: InputOptions): Promise<void>
85
- watchChange(id: string, event?: ChangeEvent): void
86
84
  resolveId(
87
85
  id: string,
88
86
  importer?: string,
@@ -531,17 +529,6 @@ export async function createPluginContainer(
531
529
  }
532
530
  },
533
531
 
534
- watchChange(id, event = 'update') {
535
- const ctx = new Context()
536
- if (watchFiles.has(id)) {
537
- for (const plugin of plugins) {
538
- if (!plugin.watchChange) continue
539
- ctx._activePlugin = plugin
540
- plugin.watchChange.call(ctx as any, id, { event })
541
- }
542
- }
543
- },
544
-
545
532
  async close() {
546
533
  if (closed) return
547
534
  const ctx = new Context()
@@ -29,6 +29,7 @@ export interface TransformResult {
29
29
  map: SourceMap | null
30
30
  etag?: string
31
31
  deps?: string[]
32
+ dynamicDeps?: string[]
32
33
  }
33
34
 
34
35
  export interface TransformOptions {