forked from claviska/esbuild-plugin-inline-import
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
59 lines (52 loc) · 1.88 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
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) {
build.onResolve({ filter }, args => {
const realPath = args.path.replace(filter, '');
return {
path: path.resolve(args.resolveDir, realPath),
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,
loader: 'text'
};
});
}
};
};