-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
71 lines (62 loc) · 2.25 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
65
66
67
68
69
70
71
const path = require('path');
const fs = require('fs').promises;
module.exports = options => {
const { filter, namespace, transform } = Object.assign(
{
/**
* A regex filter to match the desired import. Defaults to imports that start with `inline:`, e.g.
* import 'inline:./file.ext';
*/
filter: /^inline:/,
/**
* The namespace to use. If you use more than one instance of this plugin, each one should have a unique
* namespace. This is a random string by default, so you won't need to change it unless you're targeting a
* specific namespace.
*/
namespace: '_' + Math.random().toString(36).substr(2, 9),
/**
* A function to transform the contents of the imported file. This can be a simple string replace or a more
* complex operation, such as a call to PostCSS, Sass, etc. The function must return a string.
*
* The contents argument will be a string containing the file's contents. The args argument is passed through from
* esbuild, but the most useful is probably args.path which references the file path.
*
* Note that heavy operations here can impact esbuild's performance!
*/
transform: async (contents, args) => contents
},
options
);
return {
name: 'esbuild-inline-plugin',
setup(build) {
let alias = Object.entries(build.initialOptions.alias ?? {});
build.onResolve({ filter }, async args => {
let inputPath = alias.reduce((path, [key, val]) => {
return path.replace(key, val);
}, args.path);
let filePath = path.resolve(args.resolveDir, inputPath);
try {
await fs.access(filePath);
} catch {
filePath = path.resolve(args.resolveDir, inputPath.replace(filter, ''));
}
return {
path: filePath,
namespace
};
});
build.onLoad({ filter: /.*/, namespace }, async args => {
let contents = await fs.readFile(args.path, 'utf8');
if (typeof transform === 'function') {
contents = await transform(contents, args);
}
return {
contents,
watchFiles: [args.path],
loader: 'text'
};
});
}
};
};