feat: runes globals error (#9773)

* feat: runes globals error

throw descriptive error for using runes globals outside of Svelte-compiled files

* less hacky/more future-proof treeshaking check

* tweak

---------

Co-authored-by: Rich Harris <rich.harris@vercel.com>
pull/9792/head
Simon H 1 year ago committed by GitHub
parent 24777c335a
commit 9c3516dd3d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -0,0 +1,5 @@
---
'svelte': patch
---
feat: throw descriptive error for using runes globals outside of Svelte-compiled files

@ -2,6 +2,7 @@ import fs from 'node:fs';
import path from 'node:path'; import path from 'node:path';
import { rollup } from 'rollup'; import { rollup } from 'rollup';
import virtual from '@rollup/plugin-virtual'; import virtual from '@rollup/plugin-virtual';
import { nodeResolve } from '@rollup/plugin-node-resolve';
const pkg = JSON.parse(fs.readFileSync('package.json', 'utf8')); const pkg = JSON.parse(fs.readFileSync('package.json', 'utf8'));
@ -27,6 +28,9 @@ for (const key in pkg.exports) {
plugins: [ plugins: [
virtual({ virtual({
__entry__: `import ${JSON.stringify(resolved)}` __entry__: `import ${JSON.stringify(resolved)}`
}),
nodeResolve({
exportConditions: ['production', 'import', 'browser', 'default']
}) })
], ],
onwarn: (warning, handle) => { onwarn: (warning, handle) => {
@ -40,16 +44,17 @@ for (const key in pkg.exports) {
throw new Error('errr what'); throw new Error('errr what');
} }
const code = output[0].code.replace(/import\s+([^'"]+from\s+)?(['"])[^'"]+\2\s*;?/, ''); const code = output[0].code.trim();
if (code.trim()) {
if (code === '') {
// eslint-disable-next-line no-console
console.error(`${subpackage} (${type})`);
} else {
// eslint-disable-next-line no-console // eslint-disable-next-line no-console
console.error(code); console.error(code);
// eslint-disable-next-line no-console // eslint-disable-next-line no-console
console.error(`${subpackage} (${type})`); console.error(`${subpackage} (${type})`);
failed = true; failed = true;
} else {
// eslint-disable-next-line no-console
console.error(`${subpackage} (${type})`);
} }
} }
} }

@ -1875,3 +1875,22 @@ export function unwrap(value) {
// @ts-ignore // @ts-ignore
return value; return value;
} }
if (DEV) {
/** @param {string} rune */
function throw_rune_error(rune) {
if (!(rune in globalThis)) {
// @ts-ignore
globalThis[rune] = () => {
// TODO if people start adjusting the "this can contain runes" config through v-p-s more, adjust this message
throw new Error(`${rune} is only available inside .svelte and .svelte.js/ts files`);
};
}
}
throw_rune_error('$state');
throw_rune_error('$effect');
throw_rune_error('$derived');
throw_rune_error('$inspect');
throw_rune_error('$props');
}

Loading…
Cancel
Save