forked from bazilio91/ejs-compiled-loader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
57 lines (49 loc) · 1.72 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
const path = require('node:path');
const ejs = require('ejs');
const terser = require('terser');
const htmlmin = require('html-minifier-terser');
/**
* @typedef {Object} Options
* @property {boolean} client
* @property {boolean} compileDebug
* @property {boolean} minimize
* @property {boolean} beautify
* @property {boolean} htmlmin
* @property {import('html-minifier-terser').Options} htmlminOptions
* @property {import('terser').MinifyOptions} terserOptions
*/
/**
* @type {import('webpack').LoaderDefinitionFunction<Options>}
* @this {import('webpack').LoaderContext<Options>}
*/
module.exports = function (source, sourceMaps, meta) {
const callback = this.async();
(async () => {
this.cacheable();
const options = this.getOptions();
/** @type {Options} */
const defaults = {
client: true,
compileDebug: this.mode === 'development',
minimize: this.mode === 'production',
beautify: false,
htmlmin: this.mode === 'production',
htmlminOptions: {},
terserOptions: {},
};
const opts = { ...defaults, ...options };
// minify html
if (opts.htmlmin) {
source = await htmlmin.minify(source, opts.htmlminOptions);
}
// compile template
let template = ejs
.compile(source, { ...opts, filename: path.relative(process.cwd(), this.resourcePath) })
.toString();
// minify js with terser
if (opts.minimize) {
template = (await terser.minify(template, opts.terserOptions)).code ?? '';
}
callback(null, 'module.exports = ' + template, sourceMaps, meta);
})().catch((err) => callback(err));
};