forked from solidjs/solid-playground
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrollup.config.js
209 lines (186 loc) · 6.44 KB
/
rollup.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
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
import mime from 'mime';
import jsx from 'acorn-jsx';
import { cwd } from 'process';
import { rollup } from 'rollup';
import { walk } from 'estree-walker';
import del from 'rollup-plugin-delete';
import { readFile } from 'fs/promises';
import MagicString from 'magic-string';
import json from '@rollup/plugin-json';
import css from 'rollup-plugin-import-css';
import { babel } from '@rollup/plugin-babel';
import replace from '@rollup/plugin-replace';
import WindiCSS from 'rollup-plugin-windicss';
import commonjs from '@rollup/plugin-commonjs';
import { renameSync, ensureDirSync } from 'fs-extra';
import { basename, join, extname, resolve, dirname } from 'path';
import { nodeResolve } from '@rollup/plugin-node-resolve';
import { createReadStream, createWriteStream, readFileSync } from 'fs';
const extensions = ['.ts', '.tsx', '.js', '.jsx', '.json', '.mjs', '.d.ts'];
const copies = Object.create(null);
copies['public/eruda.css'] = 'eruda.css';
function copyFile(src, dest) {
return new Promise((resolve, reject) => {
const read = createReadStream(src);
read.on('error', reject);
const write = createWriteStream(dest);
write.on('error', reject);
write.on('finish', resolve);
read.pipe(write);
});
}
let nextId = 0;
function getJsxName(node) {
if (node.type === 'JSXMemberExpression') {
return `${getJsxName(node.object)}.${getJsxName(node.property)}`;
}
return node.name;
}
// Taken from https://github.com/sebastian-software/preppy/blob/master/src/jsxPlugin.js
const preppy = {
name: 'jsx',
transform(code) {
const magicString = new MagicString(code);
const idsByName = new Map();
const tree = this.parse(code);
walk(tree, {
enter(node) {
if (node.type === 'JSXOpeningElement' || node.type === 'JSXClosingElement') {
const name = getJsxName(node.name);
const tagId = idsByName.get(name) || `PREPPY_JSX_ID_${(nextId += 1)}`;
// overwrite all JSX tags with artificial tag ids so that we can find them again later
magicString.overwrite(node.name.start, node.name.end, tagId);
idsByName.set(name, tagId);
}
// do not treat the children as separate identifiers
else if (node.type === 'JSXMemberExpression') {
this.skip();
}
},
});
if (idsByName.size > 0) {
const usedNamesAndIds = [...idsByName].map(([name, tagId]) => `/*${tagId}*/${name}`);
magicString.append(`;__PREPPY_JSX_NAMES__(${usedNamesAndIds.join(',')});`);
return {
code: magicString.toString(),
map: magicString.generateMap({
includeContent: true,
hires: true,
}),
};
}
return null;
},
renderChunk(code) {
const replacements = new Map();
return {
code: code
// this finds all injected artificial usages from the transform hook, removes them
// and collects the new variable names as a side-effect
.replace(/__PREPPY_JSX_NAMES__\(([^)]*)\);/g, (matchedCall, usedList) => {
usedList
.split(',')
// this extracts the artificial tag id from the comment and the possibly renamed variable
// name from the variable via two capture groups
.map((replacementAndVariable) => replacementAndVariable.match(/^\s*?\/\*([^*]*)\*\/\s*?(\S*)$/))
.filter(Boolean)
.forEach(([usedEntry, tagId, updatedName]) => replacements.set(tagId, updatedName));
// clearing out the actual values
return '';
})
// this replaces the artificial tag ids in the actual JSX tags
.replace(/PREPPY_JSX_ID_\d+/g, (tagId) => replacements.get(tagId)),
map: null,
};
},
};
rollup({
input: [
'src/index.ts',
'src/workers/compiler.ts',
'src/workers/formatter.ts',
'src/workers/linter.ts',
'src/components/repl.tsx',
],
external: ['solid-js', 'solid-js/web', 'solid-js/store', 'monaco-editor'],
acornInjectPlugins: [jsx()],
plugins: [
del({ targets: 'lib/*' }),
{
name: 'raw',
load(id) {
if (!id.endsWith('?raw')) {
return;
}
return `export default ${JSON.stringify(readFileSync(id.slice(0, -4)).toString())};`;
},
resolveId(source, importer) {
if (source.endsWith('?raw')) {
if (source.startsWith('./')) {
return resolve(dirname(importer), source);
} else if (source.startsWith('/')) {
return resolve(source.slice(1));
}
return source;
}
return null;
},
},
nodeResolve({ extensions, exportConditions: ['solid'], preferBuiltins: false }),
json(),
...WindiCSS(),
css(),
commonjs(),
{
name: 'url',
load(id) {
if (!id.endsWith('?url')) {
return null;
}
let base64 = false; // ideally, we wouldn't have to do this, but current end user bundlers can't handle non base64
let url = id.slice(0, -4);
if (base64) {
const mimetype = mime.getType(url);
return readFile(url).then((x) => `export default "data:${mimetype};base64,${x.toString('base64')}"`);
} else {
const ext = extname(url);
const name = basename(url, ext);
copies[url] = `./${name}${ext}`;
return `import ${name}urlImport from "${copies[url]}?url";
export default ${name}urlImport`;
}
},
async generateBundle(outputOptions) {
const base = outputOptions.dir;
ensureDirSync(base);
await Promise.all(
Object.keys(copies).map(async (name) => {
const output = copies[name];
return copyFile(name, join(base, output));
}),
);
},
},
replace({
'process.env.BABEL_TYPES_8_BREAKING': 'true',
'process.env.NODE_DEBUG': 'false',
'preventAssignment': true,
}),
babel({
extensions: extensions,
babelHelpers: 'bundled',
presets: [
// We don't use dom-expressions to preserve jsx
['@babel/preset-typescript', { jsx: 'preserve' }],
],
plugins: ['@babel/plugin-syntax-jsx'],
}),
preppy,
],
}).then((builder) => {
builder.write({ dir: 'lib', chunkFileNames: (info) => (info.isEntry ? '[name].jsx' : '[name].js') }).then(() => {
const basePath = cwd();
renameSync(resolve(basePath, 'lib/index.js'), resolve(basePath, 'lib/index.jsx'));
renameSync(resolve(basePath, 'lib/repl.js'), resolve(basePath, 'lib/repl.jsx'));
});
});