|
| 1 | +import type { PluginItem } from "@babel/core"; |
| 2 | +import babel from "@babel/core"; |
| 3 | +import * as t from "@babel/types"; |
| 4 | +import { sep as osSep } from "path"; |
| 5 | +import { basename, relative, sep } from "path/posix"; |
| 6 | +import { PluginOption } from "vite"; |
| 7 | + |
| 8 | +const idTransform = (id: string): PluginItem => { |
| 9 | + return { |
| 10 | + visitor: { |
| 11 | + Program(path) { |
| 12 | + path.node.body.unshift( |
| 13 | + t.exportNamedDeclaration( |
| 14 | + t.variableDeclaration("const", [ |
| 15 | + t.variableDeclarator(t.identifier("id$$"), t.stringLiteral(id)) |
| 16 | + ]) |
| 17 | + ) |
| 18 | + ); |
| 19 | + } |
| 20 | + } |
| 21 | + }; |
| 22 | +}; |
| 23 | + |
| 24 | +const importTransform = (): PluginItem => { |
| 25 | + return { |
| 26 | + visitor: { |
| 27 | + ImportDeclaration(path) { |
| 28 | + if (path.node.source.value !== "solid-js") return; |
| 29 | + path.traverse({ |
| 30 | + ImportSpecifier(subPath) { |
| 31 | + if (subPath.node.local.name !== "lazy") return; |
| 32 | + subPath.remove(); |
| 33 | + path.insertAfter( |
| 34 | + t.importDeclaration( |
| 35 | + [t.importSpecifier(t.identifier("lazy"), t.identifier("lazy"))], |
| 36 | + t.stringLiteral("@solidjs/start") |
| 37 | + ) |
| 38 | + ); |
| 39 | + } |
| 40 | + }); |
| 41 | + } |
| 42 | + } |
| 43 | + }; |
| 44 | +}; |
| 45 | + |
| 46 | +const lazy = (): PluginOption => { |
| 47 | + const cwd = process.cwd().replaceAll(osSep, sep); |
| 48 | + return { |
| 49 | + name: "solid-lazy-css", |
| 50 | + enforce: "pre", |
| 51 | + async transform(src, id) { |
| 52 | + // TODO: Try to exclude files by dynamicImport info in moduleGraph |
| 53 | + |
| 54 | + if (!id.match(/(ts|js)x(\?.*)?$/)) return; |
| 55 | + |
| 56 | + // The transformed files either import "lazy" or css files |
| 57 | + // Therefore we skip, if the src doesn't have any import |
| 58 | + if (src.indexOf("import") === -1) return; |
| 59 | + |
| 60 | + const hasLazy = src.indexOf("lazy") !== -1; |
| 61 | + const localId = relative(cwd, id); |
| 62 | + |
| 63 | + const transformed = await babel.transformAsync(src, { |
| 64 | + plugins: |
| 65 | + hasLazy |
| 66 | + ? [idTransform(localId), importTransform()] |
| 67 | + : [idTransform(localId)], |
| 68 | + parserOpts: { |
| 69 | + plugins: ["jsx", "typescript"] |
| 70 | + }, |
| 71 | + filename: basename(id), |
| 72 | + ast: false, |
| 73 | + sourceMaps: true, |
| 74 | + configFile: false, |
| 75 | + babelrc: false, |
| 76 | + sourceFileName: id |
| 77 | + }); |
| 78 | + |
| 79 | + if (!transformed?.code) return; |
| 80 | + |
| 81 | + const { code, map } = transformed; |
| 82 | + return { code, map }; |
| 83 | + } |
| 84 | + }; |
| 85 | +}; |
| 86 | + |
| 87 | +export default lazy; |
0 commit comments