@sveltejs/vite-plugin-svelte 1.0.0-next.37 → 1.0.0-next.40

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sveltejs/vite-plugin-svelte",
3
- "version": "1.0.0-next.37",
3
+ "version": "1.0.0-next.40",
4
4
  "license": "MIT",
5
5
  "author": "dominikg",
6
6
  "files": [
@@ -40,11 +40,11 @@
40
40
  },
41
41
  "homepage": "https://github.com/sveltejs/vite-plugin-svelte#readme",
42
42
  "dependencies": {
43
- "@rollup/pluginutils": "^4.1.2",
43
+ "@rollup/pluginutils": "^4.2.0",
44
44
  "debug": "^4.3.3",
45
45
  "kleur": "^4.1.4",
46
- "magic-string": "^0.25.7",
47
- "svelte-hmr": "^0.14.9"
46
+ "magic-string": "^0.26.1",
47
+ "svelte-hmr": "^0.14.11"
48
48
  },
49
49
  "peerDependencies": {
50
50
  "diff-match-patch": "^1.0.5",
@@ -60,11 +60,11 @@
60
60
  "@types/debug": "^4.1.7",
61
61
  "@types/diff-match-patch": "^1.0.32",
62
62
  "diff-match-patch": "^1.0.5",
63
- "esbuild": "^0.14.14",
64
- "rollup": "^2.66.1",
65
- "svelte": "^3.46.3",
66
- "tsup": "^5.11.13",
67
- "vite": "^2.7.13"
63
+ "esbuild": "^0.14.26",
64
+ "rollup": "^2.70.1",
65
+ "svelte": "^3.46.4",
66
+ "tsup": "^5.12.1",
67
+ "vite": "^2.8.6"
68
68
  },
69
69
  "scripts": {
70
70
  "dev": "pnpm run build:ci -- --sourcemap --watch src",
package/src/index.ts CHANGED
@@ -27,7 +27,6 @@ export function svelte(inlineOptions?: Partial<Options>): Plugin {
27
27
  }
28
28
  validateInlineOptions(inlineOptions);
29
29
  const cache = new VitePluginSvelteCache();
30
- const pkg_resolve_errors = new Set();
31
30
  // updated in configResolved hook
32
31
  let requestParser: IdParser;
33
32
  let options: ResolvedOptions;
@@ -56,7 +55,7 @@ export function svelte(inlineOptions?: Partial<Options>): Plugin {
56
55
  // @ts-expect-error temporarily lend the options variable until fixed in configResolved
57
56
  options = await preResolveOptions(inlineOptions, config, configEnv);
58
57
  // extra vite config
59
- const extraViteConfig = buildExtraViteConfig(options, config, configEnv);
58
+ const extraViteConfig = buildExtraViteConfig(options, config);
60
59
  log.debug('additional vite config', extraViteConfig);
61
60
  return extraViteConfig;
62
61
  },
@@ -135,37 +134,28 @@ export function svelte(inlineOptions?: Partial<Options>): Plugin {
135
134
  }
136
135
  return resolvedSvelteSSR;
137
136
  }
138
-
139
137
  try {
140
138
  const resolved = resolveViaPackageJsonSvelte(importee, importer, cache);
141
139
  if (resolved) {
142
140
  log.debug(`resolveId resolved ${resolved} via package.json svelte field of ${importee}`);
143
141
  return resolved;
144
142
  }
145
- } catch (err) {
146
- pkg_resolve_errors.add(importee);
143
+ } catch (e) {
144
+ log.debug.once(
145
+ `error trying to resolve ${importee} from ${importer} via package.json svelte field `,
146
+ e
147
+ );
148
+ // this error most likely happens due to non-svelte related importee/importers so swallow it here
149
+ // in case it really way a svelte library, users will notice anyway. (lib not working due to failed resolve)
147
150
  }
148
151
  },
149
152
 
150
153
  async transform(code, id, opts) {
151
154
  const ssr = !!opts?.ssr;
152
155
  const svelteRequest = requestParser(id, ssr);
153
- if (!svelteRequest) {
156
+ if (!svelteRequest || svelteRequest.query.svelte) {
154
157
  return;
155
158
  }
156
- const { filename, query } = svelteRequest;
157
-
158
- if (query.svelte) {
159
- if (query.type === 'style') {
160
- const css = cache.getCSS(svelteRequest);
161
- if (css) {
162
- log.debug(`transform returns css for ${filename}`);
163
- return css; // TODO return code arg instead? it's the code from load hook.
164
- }
165
- }
166
- log.error('failed to transform tagged svelte request', svelteRequest);
167
- throw new Error(`failed to transform tagged svelte request for id ${id}`);
168
- }
169
159
  let compileData;
170
160
  try {
171
161
  compileData = await compileSvelte(svelteRequest, code, options);
@@ -179,7 +169,7 @@ export function svelte(inlineOptions?: Partial<Options>): Plugin {
179
169
  ensureWatchedFile(options.server!.watcher, d, options.root);
180
170
  });
181
171
  }
182
- log.debug(`transform returns compiled js for ${filename}`);
172
+ log.debug(`transform returns compiled js for ${svelteRequest.filename}`);
183
173
  return compileData.compiled.js;
184
174
  },
185
175
 
@@ -191,20 +181,6 @@ export function svelte(inlineOptions?: Partial<Options>): Plugin {
191
181
  if (svelteRequest) {
192
182
  return handleHotUpdate(compileSvelte, ctx, svelteRequest, cache, options);
193
183
  }
194
- },
195
-
196
- /**
197
- * All resolutions done; display warnings wrt `package.json` access.
198
- */
199
- // TODO generateBundle isn't called by vite, is buildEnd enough or should it be logged once per violation in resolve
200
- buildEnd() {
201
- if (pkg_resolve_errors.size > 0) {
202
- log.warn(
203
- `vite-plugin-svelte was unable to find package.json of the following packages and wasn't able to resolve via their "svelte" field.
204
- If you had difficulties importing svelte components from a package, then please contact the author and ask them to export the package.json file.
205
- ${Array.from(pkg_resolve_errors, (s) => `- ${s}`).join('\n')}`.replace(/\t/g, '')
206
- );
207
- }
208
184
  }
209
185
  };
210
186
  }
@@ -1,15 +1,16 @@
1
- import { findRootSvelteDependencies } from '../dependencies';
1
+ import { findRootSvelteDependencies, needsOptimization } from '../dependencies';
2
2
  import * as path from 'path';
3
+ import { createRequire } from 'module';
3
4
 
4
5
  describe('dependencies', () => {
5
6
  describe('findRootSvelteDependencies', () => {
6
- it('should find svelte dependencies in packages/e2e-test/hmr', async () => {
7
+ it('should find svelte dependencies in packages/e2e-test/hmr', () => {
7
8
  const deps = findRootSvelteDependencies(path.resolve('packages/e2e-tests/hmr'));
8
9
  expect(deps).toHaveLength(1);
9
10
  expect(deps[0].name).toBe('e2e-test-dep-svelte-simple');
10
11
  expect(deps[0].path).toEqual([]);
11
12
  });
12
- it('should find nested svelte dependencies in packages/e2e-test/package-json-svelte-field', async () => {
13
+ it('should find nested svelte dependencies in packages/e2e-test/package-json-svelte-field', () => {
13
14
  const deps = findRootSvelteDependencies(
14
15
  path.resolve('packages/e2e-tests/package-json-svelte-field')
15
16
  );
@@ -26,4 +27,14 @@ describe('dependencies', () => {
26
27
  expect(simple.path[0]).toBe('e2e-test-dep-svelte-nested');
27
28
  });
28
29
  });
30
+ describe('needsOptimization', () => {
31
+ it('should optimize cjs deps only', () => {
32
+ const localRequire = createRequire(path.resolve('packages/e2e-tests/dependencies'));
33
+ expect(needsOptimization('e2e-test-dep-cjs-and-esm', localRequire)).toBe(false);
34
+ expect(needsOptimization('e2e-test-dep-cjs-only', localRequire)).toBe(true);
35
+ expect(needsOptimization('e2e-test-dep-esm-only', localRequire)).toBe(false);
36
+ expect(needsOptimization('e2e-test-dep-index-only', localRequire)).toBe(true);
37
+ expect(needsOptimization('e2e-test-dep-types-only', localRequire)).toBe(false);
38
+ });
39
+ });
29
40
  });
@@ -187,12 +187,23 @@ export function needsOptimization(dep: string, localRequire: NodeRequire): boole
187
187
  const pkg = depData.pkg;
188
188
  // only optimize if is cjs, using the below as heuristic
189
189
  // see https://github.com/sveltejs/vite-plugin-svelte/issues/162
190
- const isCjs = pkg.main && !pkg.module && !pkg.exports;
191
- if (!isCjs) return false;
192
- // ensure entry is js so vite can prebundle it
193
- // see https://github.com/sveltejs/vite-plugin-svelte/issues/233
194
- const entryExt = path.extname(pkg.main);
195
- return !entryExt || entryExt === '.js' || entryExt === '.cjs';
190
+ const hasEsmFields = pkg.module || pkg.exports;
191
+ if (hasEsmFields) return false;
192
+ if (pkg.main) {
193
+ // ensure entry is js so vite can prebundle it
194
+ // see https://github.com/sveltejs/vite-plugin-svelte/issues/233
195
+ const entryExt = path.extname(pkg.main);
196
+ return !entryExt || entryExt === '.js' || entryExt === '.cjs';
197
+ } else {
198
+ // check if has implicit index.js entrypoint
199
+ // https://github.com/sveltejs/vite-plugin-svelte/issues/281
200
+ try {
201
+ localRequire.resolve(`${dep}/index.js`);
202
+ return true;
203
+ } catch {
204
+ return false;
205
+ }
206
+ }
196
207
  }
197
208
 
198
209
  interface DependencyData {
@@ -16,11 +16,10 @@ const PREBUNDLE_SENSITIVE_OPTIONS: (keyof ResolvedOptions)[] = [
16
16
  export async function handleOptimizeDeps(options: ResolvedOptions, viteConfig: ResolvedConfig) {
17
17
  if (!options.experimental.prebundleSvelteLibraries || !viteConfig.cacheDir) return;
18
18
 
19
- const viteMetadataPath = path.resolve(viteConfig.cacheDir, '_metadata.json');
19
+ const viteMetadataPath = findViteMetadataPath(viteConfig.cacheDir);
20
+ if (!viteMetadataPath) return;
20
21
 
21
- if (!fs.existsSync(viteMetadataPath)) return;
22
-
23
- const svelteMetadataPath = path.resolve(viteConfig.cacheDir, '_svelte_metadata.json');
22
+ const svelteMetadataPath = path.resolve(viteMetadataPath, '../_svelte_metadata.json');
24
23
  const currentSvelteMetadata = JSON.stringify(generateSvelteMetadata(options), (_, value) => {
25
24
  return typeof value === 'function' ? value.toString() : value;
26
25
  });
@@ -41,3 +40,11 @@ function generateSvelteMetadata(options: ResolvedOptions) {
41
40
  }
42
41
  return metadata;
43
42
  }
43
+
44
+ function findViteMetadataPath(cacheDir: string) {
45
+ const metadataPaths = ['_metadata.json', 'deps/_metadata.json'];
46
+ for (const metadataPath of metadataPaths) {
47
+ const viteMetadataPath = path.resolve(cacheDir, metadataPath);
48
+ if (fs.existsSync(viteMetadataPath)) return viteMetadataPath;
49
+ }
50
+ }
@@ -184,8 +184,7 @@ function resolveViteRoot(viteConfig: UserConfig): string | undefined {
184
184
 
185
185
  export function buildExtraViteConfig(
186
186
  options: PreResolvedOptions,
187
- config: UserConfig,
188
- configEnv: ConfigEnv
187
+ config: UserConfig
189
188
  ): Partial<UserConfig> {
190
189
  // extra handling for svelte dependencies in the project
191
190
  const svelteDeps = findRootSvelteDependencies(options.root);
@@ -200,7 +199,7 @@ export function buildExtraViteConfig(
200
199
  // knownJsSrcExtensions: options.extensions
201
200
  };
202
201
 
203
- if (configEnv.command === 'serve') {
202
+ if (options.isServe) {
204
203
  extraViteConfig.optimizeDeps = buildOptimizeDepsForSvelte(
205
204
  svelteDeps,
206
205
  options,
@@ -209,7 +208,7 @@ export function buildExtraViteConfig(
209
208
  }
210
209
 
211
210
  // @ts-ignore
212
- extraViteConfig.ssr = buildSSROptionsForSvelte(svelteDeps, options, config);
211
+ extraViteConfig.ssr = buildSSROptionsForSvelte(svelteDeps, options, config, extraViteConfig);
213
212
 
214
213
  return extraViteConfig;
215
214
  }
@@ -294,7 +293,7 @@ function buildSSROptionsForSvelte(
294
293
  // add svelte to ssr.noExternal unless it is present in ssr.external
295
294
  // so we can resolve it with svelte/ssr
296
295
  if (options.isBuild && config.build?.ssr) {
297
- // @ts-ignore
296
+ // @ts-expect-error ssr still flagged in vite
298
297
  if (!config.ssr?.external?.includes('svelte')) {
299
298
  noExternal.push('svelte');
300
299
  }
@@ -309,13 +308,30 @@ function buildSSROptionsForSvelte(
309
308
  // add svelte dependencies to ssr.noExternal unless present in ssr.external or optimizeDeps.include
310
309
  noExternal.push(
311
310
  ...Array.from(new Set(svelteDeps.map((s) => s.name))).filter((x) => {
312
- // @ts-ignore
311
+ // @ts-expect-error ssr still flagged in vite
313
312
  return !config.ssr?.external?.includes(x) && !config.optimizeDeps?.include?.includes(x);
314
313
  })
315
314
  );
316
- return {
315
+ const ssr = {
317
316
  noExternal
318
317
  };
318
+
319
+ if (options.isServe) {
320
+ // during dev, we have to externalize transitive dependencies, see https://github.com/sveltejs/vite-plugin-svelte/issues/281
321
+ // @ts-expect-error ssr still flagged in vite
322
+ ssr.external = Array.from(
323
+ new Set(svelteDeps.flatMap((dep) => Object.keys(dep.pkg.dependencies || {})))
324
+ ).filter(
325
+ (dep) =>
326
+ !ssr.noExternal.includes(dep) &&
327
+ // @ts-expect-error ssr still flagged in vite
328
+ !config.ssr?.noExternal?.includes(dep) &&
329
+ // @ts-expect-error ssr still flagged in vite
330
+ !config.ssr?.external?.includes(dep)
331
+ );
332
+ }
333
+
334
+ return ssr;
319
335
  }
320
336
 
321
337
  export function patchResolvedViteConfig(viteConfig: ResolvedConfig, options: ResolvedOptions) {
@@ -27,8 +27,6 @@ export function resolveViaPackageJsonSvelte(
27
27
  cache.setResolvedSvelteField(importee, importer, result);
28
28
  return result;
29
29
  }
30
- } else {
31
- throw new Error(`failed to resolve package.json of ${importee} imported by ${importer}`);
32
30
  }
33
31
  }
34
32
  }