svelte-plugin.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // @ts-nocheck
  2. import { promises as fs } from 'node:fs';
  3. import { dirname, isAbsolute, join, relative } from 'node:path';
  4. import { compile } from 'svelte/compiler';
  5. const convertMessage = ({ message, start, end, filename, frame }) => ({
  6. text: message,
  7. location: start &&
  8. end && {
  9. file: filename,
  10. line: start.line,
  11. column: start.column,
  12. length: start.line === end.line ? end.column - start.column : 0,
  13. lineText: frame,
  14. },
  15. });
  16. const handleLoad = async (args, generate, { isDev }) => {
  17. const { path } = args;
  18. const source = await fs.readFile(path, 'utf8');
  19. const filename = relative(process.cwd(), path);
  20. try {
  21. let compileOptions = { dev: isDev, css: false, generate, hydratable: true };
  22. let { js, warnings } = compile(source, { ...compileOptions, filename });
  23. let contents = js.code + `\n//# sourceMappingURL=` + js.map.toUrl();
  24. return {
  25. loader: 'js',
  26. contents,
  27. resolveDir: dirname(path),
  28. warnings: warnings.map((w) => convertMessage(w)),
  29. };
  30. } catch (e) {
  31. return { errors: [convertMessage(e)] };
  32. }
  33. };
  34. export default function sveltePlugin({ isDev = false }) {
  35. return {
  36. name: 'svelte-esbuild',
  37. setup(build) {
  38. build.onResolve({ filter: /\.svelte$/ }, (args) => {
  39. let path = args.path.replace(/\.(?:client|server)/, '');
  40. path = isAbsolute(path) ? path : join(args.resolveDir, path);
  41. if (/\.client\.svelte$/.test(args.path)) {
  42. return {
  43. path,
  44. namespace: 'svelte:client',
  45. };
  46. }
  47. if (/\.server\.svelte$/.test(args.path)) {
  48. return {
  49. path,
  50. namespace: 'svelte:server',
  51. };
  52. }
  53. });
  54. build.onLoad({ filter: /.*/, namespace: 'svelte:client' }, (args) =>
  55. handleLoad(args, 'dom', { isDev })
  56. );
  57. build.onLoad({ filter: /.*/, namespace: 'svelte:server' }, (args) =>
  58. handleLoad(args, 'ssr', { isDev })
  59. );
  60. },
  61. };
  62. }