-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.mjs
81 lines (68 loc) · 2.25 KB
/
index.mjs
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
import crypto from "node:crypto";
import path from "node:path";
import fs from "node:fs/promises";
import postcss from 'postcss';
import postcssModules from 'postcss-modules';
const md5 = str => crypto.createHash('md5').update(str).digest('hex');
export default function(options) {
async function processCSSModules(css, filename) {
let cssModulesJSON = {};
const result = await postcss([
postcssModules({
generateScopedName: function (name, filename, css) {
const file = path.basename(filename, '.module.css');
const hash = btoa(md5(filename + name + css)).substring(0, 5);
return `${file}_${name}__${hash}`.replace('global_', '');
},
getJSON: (cssFileName, json) => {
cssModulesJSON = json;
},
...options
}),
]).process(css, { from: filename });
return {
css: result.css,
cssModulesJSON,
};
}
return {
name: 'css-modules',
setup(build) {
const cssContents = new Map();
build.onResolve({ filter: /\.module\.css$/ }, args => {
return {
path: path.resolve(args.resolveDir, args.path),
namespace: 'css-modules',
};
});
build.onLoad({ filter: /.*/, namespace: 'css-modules' }, async args => {
const css = await fs.readFile(args.path, 'utf8');
const { css: processedCSS, cssModulesJSON } = await processCSSModules(css, args.path);
const key = `css:${md5(args.path)}`;
// Store the processed CSS in memory
cssContents.set(key, processedCSS);
// Create a virtual module that exports the class names
const virtualModule = `
import "${key}";
export default ${JSON.stringify(cssModulesJSON)};
`;
return {
contents: virtualModule,
loader: 'js',
watchFiles: [args.path],
};
});
// Handle the virtual CSS files
build.onResolve({ filter: /^css:/ }, args => {
return { path: args.path, namespace: 'virtual-css' };
});
build.onLoad({ filter: /.*/, namespace: 'virtual-css' }, args => {
const css = cssContents.get(args.path);
return {
contents: css || '',
loader: 'css',
};
});
},
};
}