generated from obsidianmd/obsidian-sample-plugin
-
-
Notifications
You must be signed in to change notification settings - Fork 177
/
esbuild.config.mjs
263 lines (234 loc) · 7.32 KB
/
esbuild.config.mjs
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
import builtins from 'builtin-modules';
import esbuild from 'esbuild';
import { lessLoader } from 'esbuild-plugin-less';
import fs from 'fs';
import MagicString from 'magic-string';
import path from 'path';
import process from 'process';
const toFunction = (functionOrValue) => {
if (typeof functionOrValue === 'function') return functionOrValue;
return () => functionOrValue;
};
const escape = (str) => str.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&');
const longest = (a, b) => b.length - a.length;
const mapToFunctions = (options) => {
const values = options.values ? Object.assign({}, options.values) : Object.assign({}, options);
delete values.delimiters;
delete values.include;
delete values.exclude;
return Object.keys(values).reduce((fns, key) => {
const functions = Object.assign({}, fns);
functions[key] = toFunction(values[key]);
return functions;
}, {});
};
const generateFilter = (options) => {
let include = /.*/;
let exclude = null;
let hasValidInclude = false;
if (options.include) {
if (Object.prototype.toString.call(options.include) !== '[object RegExp]') {
console.warn(
`Options.include must be a RegExp object, but gets an '${typeof options.include}' type.`
);
} else {
hasValidInclude = true;
include = options.include;
}
}
if (options.exclude) {
if (Object.prototype.toString.call(options.exclude) !== '[object RegExp]') {
console.warn(
`Options.exclude must be a RegExp object, but gets an '${typeof options.exclude}' type.`
);
} else if (!hasValidInclude) {
// Only if `options.include` not set, take `options.exclude`
exclude = options.exclude;
}
}
return { include, exclude };
};
const replaceCode = (code, id, pattern, functionValues) => {
const magicString = new MagicString(code);
let match = null;
while ((match = pattern.exec(code))) {
const start = match.index;
if (code[start - 1] === '.') continue;
const end = start + match[0].length;
const replacement = String(functionValues[match[1]](id));
magicString.overwrite(start, end, replacement);
}
return magicString.toString();
};
// todo: add preventAssignment option & support sourceMap
const replace = (options = {}) => {
const { include, exclude } = generateFilter(options);
const functionValues = mapToFunctions(options);
const empty = Object.keys(functionValues).length === 0;
const keys = Object.keys(functionValues).sort(longest).map(escape);
const { delimiters } = options;
const pattern = delimiters
? new RegExp(`${escape(delimiters[0])}(${keys.join('|')})${escape(delimiters[1])}`, 'g')
: new RegExp(`\\b(${keys.join('|')})\\b`, 'g');
return {
name: 'replace',
setup(build) {
build.onLoad({ filter: include }, async (args) => {
// if match exclude, skip
if (exclude && args.path.match(exclude)) {
return;
}
const source = await fs.promises.readFile(args.path, 'utf8');
const contents = empty ? source : replaceCode(source, args.path, pattern, functionValues);
return { contents, loader: 'default' };
});
},
};
};
const isProd = process.argv[2] === 'production';
const renamePlugin = {
name: 'rename-styles',
setup(build) {
build.onEnd(() => {
const { outfile } = build.initialOptions;
const outcss = outfile.replace(/\.js$/, '.css');
const fixcss = outfile.replace(/main\.js$/, 'styles.css');
if (fs.existsSync(outcss)) {
console.log('Renaming', outcss, 'to', fixcss);
fs.renameSync(outcss, fixcss);
}
});
},
};
const NAME = 'node-modules-polyfills';
const NAMESPACE = NAME;
function NodeModulesPolyfillPlugin(options = {}) {
const { namespace = NAMESPACE, name = NAME } = options;
if (namespace.endsWith('commonjs')) {
throw new Error(`namespace ${namespace} must not end with commonjs`);
}
// this namespace is needed to make ES modules expose their default export to require: require('assert') will give you import('assert').default
const commonjsNamespace = namespace + '-commonjs';
return {
name,
setup: function setup({ onLoad, onResolve }) {
// TODO these polyfill module cannot import anything, is that ok?
async function loader(args) {
try {
const isCommonjs = args.namespace.endsWith('commonjs');
const resolved = args.path === 'buffer' ? path.resolve('./buffer-es6.mjs') : null;
const contents = (await fs.promises.readFile(resolved)).toString();
let resolveDir = path.dirname(resolved);
if (isCommonjs) {
return {
loader: 'js',
contents: commonJsTemplate({
importPath: args.path,
}),
resolveDir,
};
}
return {
loader: 'js',
contents,
resolveDir,
};
} catch (e) {
console.error('node-modules-polyfill', e);
return {
contents: `export {}`,
loader: 'js',
};
}
}
onLoad({ filter: /.*/, namespace }, loader);
onLoad({ filter: /.*/, namespace: commonjsNamespace }, loader);
const filter = /buffer/;
async function resolver(args) {
const ignoreRequire = args.namespace === commonjsNamespace;
if (args.path !== 'buffer') {
return;
}
const isCommonjs = !ignoreRequire && args.kind === 'require-call';
return {
namespace: isCommonjs ? commonjsNamespace : namespace,
path: args.path,
};
}
onResolve({ filter }, resolver);
},
};
}
function commonJsTemplate({ importPath }) {
return `
const polyfill = require('${importPath}')
if (polyfill && polyfill.default) {
module.exports = polyfill.default
for (let k in polyfill) {
module.exports[k] = polyfill[k]
}
} else if (polyfill) {
module.exports = polyfill
}
`;
}
const context = await esbuild.context({
entryPoints: ['./src/main.ts', './src/styles.less'],
bundle: true,
define: {
global: 'window',
},
plugins: [
NodeModulesPolyfillPlugin(),
lessLoader(),
replace({
include: /node_modules\/.*/,
values: {
setTimeout: 'activeWindow.setTimeout',
clearTimeout: 'activeWindow.clearTimeout',
requestAnimationFrame: 'activeWindow.requestAnimationFrame',
cancelAnimationFrame: 'activeWindow.cancelAnimationFrame',
},
}),
],
external: [
'obsidian',
'electron',
'@codemirror/autocomplete',
'@codemirror/closebrackets',
'@codemirror/collab',
'@codemirror/commands',
'@codemirror/comment',
'@codemirror/fold',
'@codemirror/gutter',
'@codemirror/highlight',
'@codemirror/history',
'@codemirror/language',
'@codemirror/lint',
'@codemirror/matchbrackets',
'@codemirror/panel',
'@codemirror/rangeset',
'@codemirror/rectangular-selection',
'@codemirror/search',
'@codemirror/state',
'@codemirror/stream-parser',
'@codemirror/text',
'@codemirror/tooltip',
'@codemirror/view',
'node:*',
...builtins,
],
format: 'cjs',
target: 'es2018',
logLevel: 'info',
sourcemap: isProd ? false : 'inline',
treeShaking: true,
outdir: './',
minify: isProd,
});
if (isProd) {
await context.rebuild();
process.exit(0);
} else {
await context.watch();
}