-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvite.config.ts
280 lines (241 loc) · 9.58 KB
/
vite.config.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
import { resolve } from "path"
import { defineConfig, loadEnv } from "vite"
import { viteStaticCopy } from "vite-plugin-static-copy"
import livereload from "rollup-plugin-livereload"
import { svelte } from "@sveltejs/vite-plugin-svelte"
import zipPack from "vite-plugin-zip-pack";
import fg from 'fast-glob';
import vitePluginYamlI18n from './yaml-plugin';
const env = process.env;
const isSrcmap = env.VITE_SOURCEMAP === 'inline';
const isDev = env.NODE_ENV === 'development';
const minify = env.NO_MINIFY ? false : true;
const outputDir = isDev ? "dev" : "dist";
console.log("isDev=>", isDev);
console.log("isSrcmap=>", isSrcmap);
console.log("outputDir=>", outputDir);
export default defineConfig({
resolve: {
alias: {
"@": resolve(__dirname, "src"),
}
},
plugins: [
svelte(),
vitePluginYamlI18n({
inDir: 'public/i18n',
outDir: `${outputDir}/i18n`
}),
viteStaticCopy({
targets: [
{ src: "./README*.md", dest: "./" },
{ src: "./plugin.json", dest: "./" },
{ src: "./preview.png", dest: "./" },
{ src: "./icon.png", dest: "./" }
],
}),
],
define: {
"process.env.DEV_MODE": JSON.stringify(isDev),
"process.env.NODE_ENV": JSON.stringify(env.NODE_ENV)
},
build: {
outDir: outputDir,
emptyOutDir: false,
minify: minify ?? true,
sourcemap: isSrcmap ? 'inline' : false,
lib: {
entry: resolve(__dirname, "src/index.ts"),
fileName: "index",
formats: ["cjs"],
},
rollupOptions: {
plugins: [
...(isDev ? [
livereload(outputDir),
{
name: 'watch-external',
async buildStart() {
const files = await fg([
'public/i18n/**',
'./README*.md',
'./plugin.json'
]);
for (let file of files) {
this.addWatchFile(file);
}
}
},
replaceMDVars(outputDir),
replaceMDImgUrl(outputDir)
] : [
// Clean up unnecessary files under dist dir
cleanupDistFiles({
patterns: ['i18n/*.yaml', 'i18n/*.md'],
distDir: outputDir
}),
replaceMDVars(outputDir),
replaceMDImgUrl(outputDir),
zipPack({
inDir: './dist',
outDir: './',
outFileName: 'package.zip'
})
])
],
external: ["siyuan", "process"],
output: {
entryFileNames: "[name].js",
assetFileNames: (assetInfo) => {
if (assetInfo.name === "style.css") {
return "index.css"
}
return assetInfo.name
},
},
},
}
});
/**
* Clean up some dist files after compiled
* @author frostime
* @param options:
* @returns
*/
function cleanupDistFiles(options: { patterns: string[], distDir: string }) {
const {
patterns,
distDir
} = options;
return {
name: 'rollup-plugin-cleanup',
enforce: 'post',
writeBundle: {
sequential: true,
order: 'post' as 'post',
async handler() {
const fg = await import('fast-glob');
const fs = await import('fs');
// const path = await import('path');
// 使用 glob 语法,确保能匹配到文件
const distPatterns = patterns.map(pat => `${distDir}/${pat}`);
console.debug('Cleanup searching patterns:', distPatterns);
const files = await fg.default(distPatterns, {
dot: true,
absolute: true,
onlyFiles: false
});
// console.info('Files to be cleaned up:', files);
for (const file of files) {
try {
if (fs.default.existsSync(file)) {
const stat = fs.default.statSync(file);
if (stat.isDirectory()) {
fs.default.rmSync(file, { recursive: true });
} else {
fs.default.unlinkSync(file);
}
console.log(`Cleaned up: ${file}`);
}
} catch (error) {
console.error(`Failed to clean up ${file}:`, error);
}
}
}
}
};
}
function replaceMDVars(dirname: string) {
return {
name: 'rollup-plugin-replace-md-vars',
enforce: 'post',
writeBundle: {
sequential: true,
order: 'post' as 'post',
async handler() {
const path = await import('path');
const fs = await import('fs');
const readFile = (filepath: string) => {
return fs.readFileSync(filepath, 'utf8');
}
const replaceMDFileVar = (dirname: string, varVal: Record<string, string>) => {
const replace = (filepath: string) => {
let md = readFile(filepath);
for (const [key, value] of Object.entries(varVal)) {
//@ts-ignore
md = md.replaceAll(key, value);
}
fs.writeFileSync(filepath, md);
}
// 遍历所有 README*.md 文件
const files = fs.readdirSync(dirname).filter(file => file.startsWith('README') && file.endsWith('.md'));
for (const file of files) {
replace(path.join(dirname, file));
}
}
console.log('Replace MD vars under:', dirname);
const jsonfile = './types/types.d.ts.json';
const cache = JSON.parse(fs.readFileSync(jsonfile, 'utf8'));
replaceMDFileVar(dirname, cache);
}
}
};
}
function replaceMDImgUrl(dirname: string) {
return {
name: 'rollup-plugin-replace-md-img-url',
enforce: 'post',
writeBundle: {
sequential: true,
order: 'post' as 'post',
async handler() {
const fs = await import('fs');
const { resolve } = await import('path');
console.log('Replace MD image URLs under:', dirname);
const replace = async (readmePath: string, prefix: string) => {
if (prefix.endsWith('/')) {
prefix = prefix.slice(0, -1);
}
function replaceImageUrl(url: string) {
// Replace with your desired image hosting URL
if (url.startsWith('assets/')) {
return `${prefix}/${url}`;
}
return url;
}
try {
let readmeContent = fs.readFileSync(readmePath, 'utf-8');
// Regular expression to match Markdown image syntax
// Matches both with and without title/alt text
const imageRegex = /!\[([^\]]*)\]\(([^)\s"]+)(?:\s+"([^"]*)")?\)/g;
// Replace all image URLs in the content
const updatedReadmeContent = readmeContent.replace(
imageRegex,
(match, alt, url, title) => {
const newUrl = replaceImageUrl(url);
// If there was a title, include it in the new markdown
if (title) {
return `![${alt}](${newUrl} "${title}")`;
}
// Otherwise just return the image with alt text
return `![${alt}](${newUrl})`;
}
);
// Write the updated content back to the file
fs.writeFileSync(readmePath, updatedReadmeContent, 'utf-8');
console.log(`Successfully updated ${readmePath}`);
} catch (error) {
console.error(`Error processing ${readmePath}:`, error);
}
}
const prefix_github = 'https://github.com/frostime/sy-query-view/raw/main';
const prefix_cdn = 'https://cdn.jsdelivr.net/gh/frostime/sy-query-view@main';
// const prefix_cdn = 'https://ghgo.xyz/https://github.com/frostime/sy-query-view/raw/main';
let readmePath = resolve(dirname, 'README.md');
await replace(readmePath, prefix_github);
readmePath = resolve(dirname, 'README_zh_CN.md');
await replace(readmePath, prefix_cdn);
}
}
};
}