Skip to content

Commit ca46019

Browse files
committed
fix: change cjs loading strategy
1 parent 4980dd2 commit ca46019

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

packages/vite-plugin-svelte/src/utils/load-svelte-config.ts

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
1+
import { createRequire } from 'module';
12
import path from 'path';
23
import fs from 'fs';
34
import { pathToFileURL } from 'url';
45
import { log } from './log';
56
import { Options } from './options';
67
import { UserConfig } from 'vite';
78

9+
const _require = createRequire(import.meta.url);
10+
811
export const knownSvelteConfigNames = [
912
'svelte.config.js',
1013
'svelte.config.cjs',
@@ -27,7 +30,7 @@ export async function loadSvelteConfig(
2730
if (configFile) {
2831
let err;
2932
// try to use dynamic import for svelte.config.js first
30-
if (configFile.endsWith('.js') || configFile.endsWith('.mjs') || configFile.endsWith('.cjs')) {
33+
if (configFile.endsWith('.js') || configFile.endsWith('.mjs')) {
3134
try {
3235
const result = await dynamicImportDefault(pathToFileURL(configFile).href);
3336
if (result != null) {
@@ -44,6 +47,27 @@ export async function loadSvelteConfig(
4447
}
4548
}
4649
// cjs or error with dynamic import
50+
if (!configFile.endsWith('.mjs')) {
51+
try {
52+
// avoid loading cached version on reload
53+
delete _require.cache[_require.resolve(configFile)];
54+
const result = _require(configFile);
55+
if (result != null) {
56+
return {
57+
...result,
58+
configFile
59+
};
60+
} else {
61+
throw new Error(`invalid export in ${configFile}`);
62+
}
63+
} catch (e) {
64+
log.error(`failed to require config ${configFile}`, e);
65+
if (!err) {
66+
err = e;
67+
}
68+
}
69+
}
70+
// cjs but project is using `type: module`
4771
if (!configFile.endsWith('.mjs')) {
4872
try {
4973
// avoid loading cached version on reload

0 commit comments

Comments
 (0)