Skip to content

refactor(load-config): remove support for cjs and add support for ts #1142

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/nasty-ghosts-warn.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@sveltejs/vite-plugin-svelte': major
---

remove support for loading commonjs svelte config files
5 changes: 5 additions & 0 deletions .changeset/tall-rivers-sleep.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@sveltejs/vite-plugin-svelte': minor
---

add support for loading typescript svelte config files in runtimes that support it
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import { it, expect } from 'vitest';
import { editViteConfig, isBuild, page, e2eServer } from '~utils';
import { versions } from 'node:process';

const isNodeWithoutTypeStripping = Number(versions.node?.split('.', 1)[0]) < 22;

it('should load default config and work', async () => {
expect(e2eServer.logs.server.out).toContain('default svelte config loaded');
Expand All @@ -11,11 +14,11 @@ it('should load default config and work', async () => {
if (!isBuild) {
// editing vite config does not work in build tests, build only runs once
// TODO split into different tests
it('should load custom cjs config and work', async () => {
it.skipIf(isNodeWithoutTypeStripping)('should load custom ts config and work', async () => {
await editViteConfig((c) =>
c.replace(/svelte\([^)]*\)/, "svelte({configFile:'svelte.config.custom.cjs'})")
c.replace(/svelte\([^)]*\)/, "svelte({configFile:'svelte.config.custom.ts'})")
);
expect(e2eServer.logs.server.out).toContain('custom svelte config loaded cjs');
expect(e2eServer.logs.server.out).toContain('custom svelte config loaded ts');
expect(await page.textContent('h1')).toMatch('Hello world!');
expect(await page.textContent('#test-child')).toBe('test-child');
expect(await page.textContent('#dependency-import')).toBe('dependency-import');
Expand Down
4 changes: 2 additions & 2 deletions packages/e2e-tests/configfile-custom/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
"private": true,
"version": "1.0.0",
"scripts": {
"dev": "vite",
"build": "vite build",
"dev": "cross-env NODE_OPTIONS=\"--experimental-strip-types\" vite",
"build": "cross-env NODE_OPTIONS=\"--experimental-strip-types\" vite build",
"preview": "vite preview"
},
"dependencies": {
Expand Down
6 changes: 0 additions & 6 deletions packages/e2e-tests/configfile-custom/svelte.config.custom.cjs

This file was deleted.

8 changes: 8 additions & 0 deletions packages/e2e-tests/configfile-custom/svelte.config.custom.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
console.log('custom svelte config loaded ts');
import type { SvelteConfig } from '@sveltejs/vite-plugin-svelte';
const config: SvelteConfig = {
vitePlugin: {
emitCss: false
}
};
export default config;
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
console.log('default svelte config loaded');
module.exports = {};
export default {};
12 changes: 6 additions & 6 deletions packages/e2e-tests/hmr/__tests__/hmr.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,10 +164,10 @@ if (!isBuild) {
});

test('should work with emitCss: false in svelte config', async () => {
addFile('svelte.config.cjs', 'module.exports={vitePlugin:{emitCss:false}}');
addFile('svelte.config.js', 'export default {vitePlugin:{emitCss:false}}');
await waitForServerRestartAndPageReload();
expect(await getColor('#hmr-test-1 .label')).toBe('red');
removeFile('svelte.config.cjs');
removeFile('svelte.config.js');
});

test('should detect changes in svelte config and restart', async () => {
Expand All @@ -182,8 +182,8 @@ if (!isBuild) {
}
};
await addFile(
'svelte.config.cjs',
`module.exports = {
'svelte.config.js',
`export default {
preprocess:[{markup:${injectPreprocessor.toString()}}]};`
);
await waitForServerRestartAndPageReload();
Expand All @@ -196,7 +196,7 @@ if (!isBuild) {
await updateHmrTest((content) => content.replace('color: red', 'color: green'));
expect(await getColor('#hmr-test-1 .label')).toBe('green');
expect(await getText('#hmr-test-1 .counter')).toBe('1');
await editFile('svelte.config.cjs', (content) =>
await editFile('svelte.config.js', (content) =>
content
.replace('preprocess-inject', 'preprocess-inject-2')
.replace('Injected', 'Injected 2')
Expand All @@ -212,7 +212,7 @@ if (!isBuild) {
await updateHmrTest((content) => content.replace('color: green', 'color: red'));
expect(await getColor('#hmr-test-1 .label')).toBe('red');
expect(await getText('#hmr-test-1 .counter')).toBe('1');
await removeFile('svelte.config.cjs');
await removeFile('svelte.config.js');
await waitForServerRestartAndPageReload();
expect(await getEl('#preprocess-inject-2')).toBe(null);
expect(await getEl('#preprocess-inject')).toBe(null);
Expand Down
11 changes: 11 additions & 0 deletions packages/e2e-tests/vitestSetup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,17 @@ beforeAll(
if (fs.existsSync(logsDir)) {
fs.rmSync(logsDir, { recursive: true, force: true });
}
// remove strip types flag for node < 22, it doesn't work there
// TODO: remove once node20 is no longer part of CI
if (Number(process.versions.node?.split('.', 1)[0]) < 22) {
const pkgFile = path.join(tempDir, 'package.json');
const pkgContent = fs.readFileSync(pkgFile, 'utf-8');
const newContent = pkgContent.replaceAll(
'cross-env NODE_OPTIONS=\\"--experimental-strip-types\\" ',
''
);
fs.writeFileSync(pkgFile, newContent, 'utf-8');
}
await fs.mkdir(logsDir);
const customServerScript = path.resolve(path.dirname(testPath), 'serve.js');
const defaultServerScript = path.resolve(e2eTestsRoot, 'e2e-server.js');
Expand Down
78 changes: 18 additions & 60 deletions packages/vite-plugin-svelte/src/utils/load-svelte-config.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,12 @@
import { createRequire } from 'node:module';
import path from 'node:path';
import process from 'node:process';
import fs from 'node:fs';
import { pathToFileURL } from 'node:url';
import { log } from './log.js';

// used to require cjs config in esm.
// NOTE dynamic import() cjs technically works, but timestamp query cache bust
// have no effect, likely because it has another internal cache?
/** @type {NodeRequire}*/
let esmRequire;

export const knownSvelteConfigNames = [
'svelte.config.js',
'svelte.config.cjs',
'svelte.config.mjs'
];
export const knownSvelteConfigNames = ['js', 'ts', 'mjs', 'mts'].map(
(ext) => `svelte.config.${ext}`
);

/**
* @param {string} filePath
Expand All @@ -36,56 +27,23 @@ export async function loadSvelteConfig(viteConfig, inlineOptions) {
}
const configFile = findConfigToLoad(viteConfig, inlineOptions);
if (configFile) {
let err;
// try to use dynamic import for svelte.config.js first
if (configFile.endsWith('.js') || configFile.endsWith('.mjs')) {
try {
const result = await dynamicImportDefault(
pathToFileURL(configFile).href,
fs.statSync(configFile).mtimeMs
);
if (result != null) {
return {
...result,
configFile
};
} else {
throw new Error(`invalid export in ${configFile}`);
}
} catch (e) {
log.error(`failed to import config ${configFile}`, e);
err = e;
}
}
// cjs or error with dynamic import
if (!configFile.endsWith('.mjs')) {
try {
// identify which require function to use (esm and cjs mode)
const _require = import.meta.url
? (esmRequire ?? (esmRequire = createRequire(import.meta.url)))
: // eslint-disable-next-line no-undef
require;

// avoid loading cached version on reload
delete _require.cache[_require.resolve(configFile)];
const result = _require(configFile);
if (result != null) {
return {
...result,
configFile
};
} else {
throw new Error(`invalid export in ${configFile}`);
}
} catch (e) {
log.error(`failed to require config ${configFile}`, e);
if (!err) {
err = e;
}
try {
const result = await dynamicImportDefault(
pathToFileURL(configFile).href,
fs.statSync(configFile).mtimeMs
);
if (result != null) {
return {
...result,
configFile
};
} else {
throw new Error(`invalid export in ${configFile}`);
}
} catch (e) {
log.error(`failed to import config ${configFile}`, e);
throw e;
}
// failed to load existing config file
throw err;
}
}

Expand Down
2 changes: 1 addition & 1 deletion packages/vite-plugin-svelte/types/index.d.ts.map
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,6 @@
null,
null
],
"mappings": ";;;;aAIYA,OAAOA;;WAETC,mBAAmBA;;;;;;;;;;;kBAWZC,aAAaA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBAgGbC,YAAYA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;WAiDnBC,mBAAmBA;;;;;;;;;;;;;;;;WAgBnBC,oBAAoBA;;;;;;;;;;;;;;;MAezBC,SAASA;;kBAEGC,qBAAqBA;;;;;;;;;;;;;iBC/JtBC,MAAMA;iBCXNC,cAAcA;iBCORC,gBAAgBA",
"mappings": ";;;;aAIYA,OAAOA;;WAETC,mBAAmBA;;;;;;;;;;;kBAWZC,aAAaA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBAgGbC,YAAYA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;WAiDnBC,mBAAmBA;;;;;;;;;;;;;;;;WAgBnBC,oBAAoBA;;;;;;;;;;;;;;;MAezBC,SAASA;;kBAEGC,qBAAqBA;;;;;;;;;;;;;iBC/JtBC,MAAMA;iBCXNC,cAAcA;iBCFRC,gBAAgBA",
"ignoreList": []
}
Loading