-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlinaria-esbuild.config.js
94 lines (79 loc) · 2.59 KB
/
linaria-esbuild.config.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
const path = require("path");
const fs = require("fs");
const { slugify, transform } = require("@linaria/babel-preset");
const { transformSync } = require("esbuild");
const nodeModulesRegex = /^(?:.*[\\/])?node_modules(?:[\\/].*)?$/;
function linaria({ sourceMap, preprocessor, esbuildOptions, ...rest } = {}) {
return {
name: "linaria",
setup(build) {
const cssLookup = new Map();
build.onResolve({ filter: /\.linaria\.css$/ }, (args) => {
return {
namespace: "linaria",
path: args.path,
};
});
build.onLoad({ filter: /.*/, namespace: "linaria" }, (args) => {
return {
contents: cssLookup.get(args.path),
loader: "file",
resolveDir: path.basename(args.path),
};
});
build.onLoad({ filter: /\.(js|jsx|ts|tsx)$/ }, (args) => {
const rawCode = fs.readFileSync(args.path, "utf8");
const { ext, name: filename } = path.parse(args.path);
const loader = ext.replace(/^\./, "");
if (nodeModulesRegex.test(args.path)) {
return {
loader,
contents: rawCode,
};
}
if (typeof esbuildOptions === "undefined") {
esbuildOptions = {};
if ("jsxFactory" in build.initialOptions) {
esbuildOptions.jsxFactory = build.initialOptions.jsxFactory;
}
if ("jsxFragment" in build.initialOptions) {
esbuildOptions.jsxFragment = build.initialOptions.jsxFragment;
}
}
const { code } = transformSync(rawCode, {
...esbuildOptions,
loader,
});
const result = transform(code, {
filename: args.path,
preprocessor,
pluginOptions: rest,
});
if (!result.cssText) {
return {
contents: code,
loader,
resolveDir: path.dirname(args.path),
};
}
let { cssText } = result;
const slug = slugify(cssText);
const cssFilename = `${filename}_${slug}.linaria.css`;
if (sourceMap && result.cssSourceMapText) {
const map = Buffer.from(result.cssSourceMapText).toString("base64");
cssText += `/*# sourceMappingURL=data:application/json;base64,${map}*/`;
}
cssLookup.set(cssFilename, cssText);
return {
contents: `
import __linariaStyle from ${JSON.stringify(cssFilename)};
${result.code}
`,
loader,
resolveDir: path.dirname(args.path),
};
});
},
};
}
module.exports = linaria;