2021-05-03 18:18:08 +00:00
|
|
|
// @ts-nocheck
|
2023-07-18 00:17:59 +00:00
|
|
|
import { promises as fs } from 'node:fs';
|
|
|
|
import { dirname, isAbsolute, join, relative } from 'node:path';
|
2021-05-03 18:18:08 +00:00
|
|
|
import { compile } from 'svelte/compiler';
|
|
|
|
|
|
|
|
const convertMessage = ({ message, start, end, filename, frame }) => ({
|
2021-12-22 21:11:05 +00:00
|
|
|
text: message,
|
|
|
|
location: start &&
|
|
|
|
end && {
|
|
|
|
file: filename,
|
|
|
|
line: start.line,
|
|
|
|
column: start.column,
|
|
|
|
length: start.line === end.line ? end.column - start.column : 0,
|
|
|
|
lineText: frame,
|
|
|
|
},
|
2021-05-03 18:26:10 +00:00
|
|
|
});
|
2021-05-03 18:18:08 +00:00
|
|
|
|
2021-05-13 14:29:23 +00:00
|
|
|
const handleLoad = async (args, generate, { isDev }) => {
|
2021-12-22 21:11:05 +00:00
|
|
|
const { path } = args;
|
|
|
|
const source = await fs.readFile(path, 'utf8');
|
|
|
|
const filename = relative(process.cwd(), path);
|
2021-05-03 18:18:08 +00:00
|
|
|
|
2021-12-22 21:11:05 +00:00
|
|
|
try {
|
|
|
|
let compileOptions = { dev: isDev, css: false, generate, hydratable: true };
|
2021-05-03 18:18:08 +00:00
|
|
|
|
2021-12-22 21:11:05 +00:00
|
|
|
let { js, warnings } = compile(source, { ...compileOptions, filename });
|
|
|
|
let contents = js.code + `\n//# sourceMappingURL=` + js.map.toUrl();
|
2021-05-03 18:18:08 +00:00
|
|
|
|
2022-04-02 20:15:41 +00:00
|
|
|
return {
|
|
|
|
loader: 'js',
|
|
|
|
contents,
|
|
|
|
resolveDir: dirname(path),
|
|
|
|
warnings: warnings.map((w) => convertMessage(w)),
|
|
|
|
};
|
2021-12-22 21:11:05 +00:00
|
|
|
} catch (e) {
|
|
|
|
return { errors: [convertMessage(e)] };
|
|
|
|
}
|
2021-05-03 18:26:10 +00:00
|
|
|
};
|
2021-05-03 18:18:08 +00:00
|
|
|
|
2021-05-13 14:29:23 +00:00
|
|
|
export default function sveltePlugin({ isDev = false }) {
|
2021-12-22 21:11:05 +00:00
|
|
|
return {
|
|
|
|
name: 'svelte-esbuild',
|
|
|
|
setup(build) {
|
|
|
|
build.onResolve({ filter: /\.svelte$/ }, (args) => {
|
|
|
|
let path = args.path.replace(/\.(?:client|server)/, '');
|
|
|
|
path = isAbsolute(path) ? path : join(args.resolveDir, path);
|
|
|
|
|
|
|
|
if (/\.client\.svelte$/.test(args.path)) {
|
|
|
|
return {
|
|
|
|
path,
|
|
|
|
namespace: 'svelte:client',
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
if (/\.server\.svelte$/.test(args.path)) {
|
|
|
|
return {
|
|
|
|
path,
|
|
|
|
namespace: 'svelte:server',
|
|
|
|
};
|
|
|
|
}
|
|
|
|
});
|
2022-04-02 20:15:41 +00:00
|
|
|
build.onLoad({ filter: /.*/, namespace: 'svelte:client' }, (args) =>
|
|
|
|
handleLoad(args, 'dom', { isDev })
|
|
|
|
);
|
|
|
|
build.onLoad({ filter: /.*/, namespace: 'svelte:server' }, (args) =>
|
|
|
|
handleLoad(args, 'ssr', { isDev })
|
|
|
|
);
|
2021-12-22 21:11:05 +00:00
|
|
|
},
|
|
|
|
};
|
2021-05-03 18:18:08 +00:00
|
|
|
}
|