Skip to content

Commit

Permalink
Fix vite plugin
Browse files Browse the repository at this point in the history
  • Loading branch information
paoloricciuti committed Feb 8, 2023
1 parent 09eb588 commit 2c16c2b
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 18 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "sveltekit-defer",
"version": "0.0.4",
"version": "0.0.5",
"repository": "git+https://github.com/paoloricciuti/sveltekit-defer.git",
"author": "Paolo Ricciuti",
"license": "MIT",
Expand Down
70 changes: 53 additions & 17 deletions src/lib/vite/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { SveltekitDeferOptions } from '$lib/constants';
import type { Plugin } from 'vite';
import MagicString from 'magic-string';
import fs from 'fs';

export const env_parser: {
[K in keyof SveltekitDeferOptions]?: (
Expand All @@ -13,28 +14,63 @@ export const env_parser: {
}
};

function fix_code(code: string, options: SveltekitDeferOptions) {
if (code.startsWith('/// @sveltekit-defer-constants')) {
const magicCode = new MagicString(code);
Object.keys(options).forEach((_key) => {
const key = _key as keyof typeof options;
const to_replace = env_parser[key]?.(options[key]) ?? options[key];
if (to_replace) {
magicCode.replace(
new RegExp(`${key}:\\s\\'.*\\',?\\r?\\n`),
`${key}: '${to_replace}',\r\n`
);
}
});
return {
code: magicCode.toString(),
map: magicCode.generateMap()
};
}
}

export function sveltekit_defer(options: SveltekitDeferOptions): Plugin {
return {
name: 'vite-plugin-sveltekit-defer',
config() {
return {
optimizeDeps: {
force: true,
esbuildOptions: {
plugins: [
{
name: 'esbuild-plugin',
setup(build) {
build.onLoad(
{
filter: /constants/
},
({ path }) => {
if (!path.includes('sveltekit-defer')) return;
const code = fs.readFileSync(path, 'utf-8');
const contents = fix_code(code, options)?.code;
return contents
? {
contents
}
: undefined;
}
);
}
}
]
}
}
};
},
transform(code, id) {
if (id.endsWith('node_modules/sveltekit-defer/constants.js')) {
if (code.startsWith('/// @sveltekit-defer-constants')) {
const magicCode = new MagicString(code);
Object.keys(options).forEach((_key) => {
const key = _key as keyof typeof options;
const to_replace = env_parser[key]?.(options[key]) ?? options[key];
if (to_replace) {
magicCode.replace(
new RegExp(`${key}:\\s\\'.*\\',?\\r?\\n`),
`${key}: '${to_replace}',\r\n`
);
}
});
return {
code: magicCode.toString(),
map: magicCode.generateMap()
};
}
return fix_code(code, options);
}
}
};
Expand Down

0 comments on commit 2c16c2b

Please sign in to comment.