-
Notifications
You must be signed in to change notification settings - Fork 6
/
integration.ts
70 lines (61 loc) · 3.03 KB
/
integration.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import url from "node:url"
import path from "node:path"
import fs from "node:fs"
import type { AstroConfig, AstroIntegration, AstroIntegrationLogger } from "astro"
import { PROPAGATED_ASSET_FLAG } from "./node_modules/astro/dist/content/consts.js"
interface Options {}
export default function (_?: Options): AstroIntegration {
return {
name: "astro-dynamic-import",
hooks: {
"astro:config:setup" ({ config, updateConfig, logger }) {
const srcDirName = path.relative(url.fileURLToPath(config.root), url.fileURLToPath(config.srcDir)).replaceAll("\\", "/")
updateConfig({ vite: {
optimizeDeps: {
exclude: ["astro-dynamic-import:internal"],
},
plugins: [{
name: "astro-dynamic-import/vite",
resolveId(source) {
if (source === "astro:import") { return this.resolve("astro-dynamic-import/runtime/virtual-module.ts") }
if (source === "astro-dynamic-import:internal") return source
},
load(id) {
if (id === "astro-dynamic-import:internal") {
return `export const srcDirName = ${JSON.stringify(srcDirName)}\n` +
`export const lookupMap = import.meta.glob('/${srcDirName}/components/**/*.astro', { query: { ${PROPAGATED_ASSET_FLAG}: true } })\n`
}
}
}, {
name: "astro-dynamic-import/vite/types",
enforce: "post",
async config() {
injectEnvDTS(config, logger, "astro-dynamic-import/client")
}
}] } })
}
}
}
}
function injectEnvDTS(config: AstroConfig, logger: AstroIntegrationLogger, specifier: URL | string) {
const envDTsPath = url.fileURLToPath(new URL("env.d.ts", config.srcDir))
if (specifier instanceof URL) {
specifier = url.fileURLToPath(specifier)
specifier = path.relative(url.fileURLToPath(config.srcDir), specifier)
specifier = specifier.replaceAll("\\", "/")
}
let envDTsContents = fs.readFileSync(envDTsPath, "utf-8")
if (envDTsContents.includes(`/// <reference types='${specifier}' />`)) { return }
if (envDTsContents.includes(`/// <reference types="${specifier}" />`)) { return }
const newEnvDTsContents = envDTsContents.replace(
`/// <reference types='astro/client' />`,
`/// <reference types='astro/client' />\n/// <reference types='${specifier}' />\n`
).replace(
`/// <reference types="astro/client" />`,
`/// <reference types="astro/client" />\n/// <reference types="${specifier}" />\n`
)
// the odd case where the user changed the reference to astro/client
if (newEnvDTsContents === envDTsContents) { return }
fs.writeFileSync(envDTsPath, newEnvDTsContents)
logger.info("Updated env.d.ts types")
}