()
| 3 | import type { Plugin, OnLoadArgs } from 'esbuild'; |
| 4 | |
| 5 | export function inlineFilePlugin(): Plugin { |
| 6 | const { filter, namespace, transform } = { |
| 7 | /** |
| 8 | * A regex filter to match the desired import. Defaults to imports that start with `inline:`, e.g. |
| 9 | * import 'inline:./file.ext'; |
| 10 | */ |
| 11 | filter: /^inline:/, |
| 12 | |
| 13 | /** |
| 14 | * The namespace to use. If you use more than one instance of this plugin, each one should have a unique |
| 15 | * namespace. This is a random string by default, so you won't need to change it unless you're targeting a |
| 16 | * specific namespace. |
| 17 | */ |
| 18 | namespace: '_' + Math.random().toString(36).substr(2, 9), |
| 19 | |
| 20 | /** |
| 21 | * A function to transform the contents of the imported file. This can be a simple string replace or a more |
| 22 | * complex operation, such as a call to PostCSS, Sass, etc. The function must return a string. |
| 23 | * |
| 24 | * The contents argument will be a string containing the file's contents. The args argument is passed through from |
| 25 | * esbuild, but the most useful is probably args.path which references the file path. |
| 26 | * |
| 27 | * Note that heavy operations here can impact esbuild's performance! |
| 28 | */ |
| 29 | transform: async (contents: string, args: OnLoadArgs) => contents, |
| 30 | }; |
| 31 | |
| 32 | return { |
| 33 | name: 'esbuild-inline-plugin', |
| 34 | setup(build) { |
| 35 | build.onResolve({ filter }, (args) => { |
| 36 | const realPath = args.path.replace(filter, ''); |
| 37 | return { |
| 38 | path: path.resolve(args.resolveDir, realPath), |
| 39 | namespace, |
| 40 | }; |
| 41 | }); |
| 42 | |
| 43 | build.onLoad({ filter: /.*/, namespace }, async (args) => { |
| 44 | let contents = await fs.readFile(args.path, 'utf8'); |
| 45 | |
| 46 | if (typeof transform === 'function') { |
| 47 | contents = await transform(contents, args); |
| 48 | } |
| 49 | |
| 50 | return { |
| 51 | contents, |
| 52 | loader: 'text', |
| 53 | }; |
| 54 | }); |
| 55 | }, |
| 56 | }; |
| 57 | } |
nothing calls this directly
no outgoing calls
no test coverage detected