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
|
import fsMod from 'node:fs';
import * as path from 'node:path';
import type { Plugin } from 'vite';
import { normalizePath } from 'vite';
import type { AstroSettings } from '../@types/astro.js';
import { appendForwardSlash, prependForwardSlash } from '../core/path.js';
import { VIRTUAL_MODULE_ID } from './consts.js';
import { getContentEntryExts, getContentPaths } from './utils.js';
interface AstroContentVirtualModPluginParams {
settings: AstroSettings;
}
export function astroContentVirtualModPlugin({
settings,
}: AstroContentVirtualModPluginParams): Plugin {
const contentPaths = getContentPaths(settings.config);
const relContentDir = normalizePath(
appendForwardSlash(
prependForwardSlash(
path.relative(settings.config.root.pathname, contentPaths.contentDir.pathname)
)
)
);
const contentEntryExts = getContentEntryExts(settings);
const assetsDir = settings.config.experimental.assets
? contentPaths.assetsDir.toString()
: 'undefined';
const extGlob =
contentEntryExts.length === 1
? // Wrapping {...} breaks when there is only one extension
contentEntryExts[0]
: `{${contentEntryExts.join(',')}}`;
const entryGlob = `${relContentDir}**/*${extGlob}`;
const virtualModContents = fsMod
.readFileSync(contentPaths.virtualModTemplate, 'utf-8')
.replace('@@CONTENT_DIR@@', relContentDir)
.replace('@@ENTRY_GLOB_PATH@@', entryGlob)
.replace('@@RENDER_ENTRY_GLOB_PATH@@', entryGlob);
const virtualAssetsModContents = fsMod
.readFileSync(contentPaths.virtualAssetsModTemplate, 'utf-8')
.replace('@@ASSETS_DIR@@', assetsDir);
const astroContentVirtualModuleId = '\0' + VIRTUAL_MODULE_ID;
const allContents = settings.config.experimental.assets
? virtualModContents + virtualAssetsModContents
: virtualModContents;
return {
name: 'astro-content-virtual-mod-plugin',
enforce: 'pre',
resolveId(id) {
if (id === VIRTUAL_MODULE_ID) {
return astroContentVirtualModuleId;
}
},
load(id) {
if (id === astroContentVirtualModuleId) {
return {
code: allContents,
};
}
},
};
}
|