Skip to content

Commit f95ba3e

Browse files
committed
refactor: enhance RawPluginOptions interface and improve loader handling
1 parent ff090cd commit f95ba3e

1 file changed

Lines changed: 17 additions & 9 deletions

File tree

lib/src/index.ts

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ export interface RawPluginOptions {
2525

2626
/**
2727
* Custom loader for file processing.
28+
* Overridden by import query suffix (?text, ?base64, etc).
2829
* @defaultValue "text"
2930
*/
3031
loader?: "text" | "base64" | "dataurl" | "file" | "binary" | "default";
@@ -33,6 +34,11 @@ export interface RawPluginOptions {
3334
* Extensions to be treated as text files.
3435
*/
3536
textExtensions?: string[];
37+
38+
/**
39+
* Extension name in case you are using some other extension with conflicting names.
40+
*/
41+
name?: string;
3642
}
3743

3844
/**
@@ -43,12 +49,13 @@ export interface RawPluginOptions {
4349
* extensions in order of priority and handling custom loaders.
4450
*/
4551
export const raw = (options?: RawPluginOptions): Plugin => ({
46-
name: "esbuild-raw-plugin",
52+
name: options?.name || "esbuild-raw-plugin",
4753
setup(build: PluginBuild) {
48-
const ext = options?.ext ?? DEFAULT_EXT_ORDER_LIST;
54+
const ext = options?.ext?.map(e => e.replace(/^\./, "")) ?? DEFAULT_EXT_ORDER_LIST;
4955

5056
build.onResolve({ filter: /\?(raw|text|buffer|binary|base64|dataurl|file)$/ }, args => {
51-
const [filepath, query] = args.path.split("?");
57+
const query = args.path.split("?").pop();
58+
const filepath = args.path.replace(new RegExp(`\\?${query}$`), "");
5259
return {
5360
path: filepath,
5461
namespace: "raw",
@@ -68,9 +75,7 @@ export const raw = (options?: RawPluginOptions): Plugin => ({
6875
}
6976

7077
if (!fs.existsSync(filePath)) {
71-
const resolved = ext
72-
.map(e => e.replace(/^\./, ""))
73-
.find(e => fs.existsSync(`${filePath}.${e}`));
78+
const resolved = ext.find(e => fs.existsSync(`${filePath}.${e}`));
7479
if (resolved) {
7580
filePath += `.${resolved}`;
7681
}
@@ -87,17 +92,20 @@ export const raw = (options?: RawPluginOptions): Plugin => ({
8792

8893
let loader = options?.loader ?? "text";
8994
switch (suffix) {
90-
case "text":
91-
loader = "text";
92-
break;
9395
case "buffer":
9496
case "binary":
9597
loader = "binary";
9698
break;
99+
case "text":
97100
case "file":
98101
case "base64":
99102
case "dataurl":
100103
loader = suffix;
104+
break;
105+
case "raw":
106+
break;
107+
default:
108+
console.warn(`?${suffix} not supported. Falling back to ${loader}`);
101109
}
102110

103111
return { contents: buffer, loader };

0 commit comments

Comments
 (0)