-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
64 lines (53 loc) · 1.8 KB
/
index.js
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
const path = require('path');
const fs = require('fs');
const { loadEnv } = require('vite');
const resolve = p => path.resolve(process.cwd(), p);
const readHtmlTemplate = async filePath => {
return await fs.promises.readFile(filePath, { encoding: 'utf8' });
};
const getHtmlContent = async (filePath, mode, options) => {
try {
filePath = resolve(filePath);
let content = await readHtmlTemplate(filePath);
const envs = loadEnv(mode, process.cwd()) || {};
const { transform, replacements = {} } = options;
if (transform) {
content = transform(content);
}
Object.keys(replacements).forEach(key => {
content = content.replace(new RegExp('%' + key + '%'), replacements[key]);
});
Object.keys(envs).forEach(key => {
content = content.replace(new RegExp('%' + key + '%'), envs[key]);
});
return content;
} catch (error) {
console.error(error);
}
};
const insertContentHtmlPlugin = (options = {}) => {
let _env;
return {
name: 'vite-plugin-html-insert',
config(_, env) {
_env = env;
},
configureServer({ middlewares, config }) {
middlewares.use(async (req, res, next) => {
const url = req._parsedUrl.pathname;
if (path.extname(url) !== '.html' && url !== '/') {
return next();
}
const content = await getHtmlContent('.' + url, config.mode, options);
res.end(content);
});
},
load(id) {
if (path.extname(id) === '.html') {
return getHtmlContent(id, _env.mode, options);
}
return null;
}
};
};
module.exports = insertContentHtmlPlugin;