forked from sveltejs/rollup-plugin-svelte
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
328 lines (273 loc) · 8.05 KB
/
index.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
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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
const fs = require('fs');
const path = require('path');
const relative = require('require-relative');
const { version } = require('svelte/package.json');
const { createFilter } = require('rollup-pluginutils');
const { encode, decode } = require('sourcemap-codec');
const major_version = +version[0];
const { compile, preprocess } = major_version >= 3
? require('svelte/compiler.js')
: require('svelte');
function sanitize(input) {
return path
.basename(input)
.replace(path.extname(input), '')
.replace(/[^a-zA-Z_$0-9]+/g, '_')
.replace(/^_/, '')
.replace(/_$/, '')
.replace(/^(\d)/, '_$1');
}
function capitalize(str) {
return str[0].toUpperCase() + str.slice(1);
}
const pluginOptions = {
include: true,
exclude: true,
extensions: true,
emitCss: true,
preprocess: true,
// legacy — we might want to remove/change these in a future version
onwarn: true,
shared: true
};
function tryRequire(id) {
try {
return require(id);
} catch (err) {
return null;
}
}
function tryResolve(pkg, importer) {
try {
return relative.resolve(pkg, importer);
} catch (err) {
if (err.code === 'MODULE_NOT_FOUND') return null;
throw err;
}
}
function exists(file) {
try {
fs.statSync(file);
return true;
} catch (err) {
if (err.code === 'ENOENT') return false;
throw err;
}
}
class CssWriter {
constructor (code, filename, map, warn, bundle) {
this.code = code;
this.filename = filename;
this.map = {
version: 3,
file: null,
sources: map.sources,
sourcesContent: map.sourcesContent,
names: [],
mappings: map.mappings
};
this.warn = warn;
this.bundle = bundle;
}
write(dest = this.filename, map) {
const basename = path.basename(dest);
if (map !== false) {
this.bundle.emitFile({type: 'asset', fileName: dest, source: `${this.code}\n/*# sourceMappingURL=${basename}.map */`});
this.bundle.emitFile({type: 'asset', fileName: `${dest}.map`, source: JSON.stringify({
version: 3,
file: basename,
sources: this.map.sources.map(source => path.relative(path.dirname(dest), source)),
sourcesContent: this.map.sourcesContent,
names: [],
mappings: this.map.mappings
}, null, ' ')});
} else {
this.bundle.emitFile({type: 'asset', fileName: dest, source: this.code});
}
}
toString() {
this.warn('[DEPRECATION] As of rollup-plugin-svelte@3, the argument to the `css` function is an object, not a string — use `css.write(file)`. Consult the documentation for more information: https://github.com/rollup/rollup-plugin-svelte');
return this.code;
}
}
module.exports = function svelte(options = {}) {
const filter = createFilter(options.include, options.exclude);
const extensions = options.extensions || ['.html', '.svelte'];
const fixed_options = {};
Object.keys(options).forEach(key => {
// add all options except include, exclude, extensions, and shared
if (pluginOptions[key]) return;
fixed_options[key] = options[key];
});
if (major_version >= 3) {
fixed_options.format = 'esm';
fixed_options.sveltePath = options.sveltePath || 'svelte';
} else {
fixed_options.format = 'es';
fixed_options.shared = require.resolve(options.shared || 'svelte/shared.js');
}
// handle CSS extraction
if ('css' in options) {
if (typeof options.css !== 'function' && typeof options.css !== 'boolean') {
throw new Error('options.css must be a boolean or a function');
}
}
let css = options.css && typeof options.css === 'function'
? options.css
: null;
const cssLookup = new Map();
if (css || options.emitCss) {
fixed_options.css = false;
}
return {
name: 'svelte',
load(id) {
if (!cssLookup.has(id)) return null;
return cssLookup.get(id);
},
resolveId(importee, importer) {
if (cssLookup.has(importee)) { return importee; }
if (!importer || importee[0] === '.' || importee[0] === '\0' || path.isAbsolute(importee))
return null;
// if this is a bare import, see if there's a valid pkg.svelte
const parts = importee.split('/');
let name = parts.shift();
if (name[0] === '@') name += `/${parts.shift()}`;
const resolved = tryResolve(
`${name}/package.json`,
path.dirname(importer)
);
if (!resolved) return null;
const pkg = tryRequire(resolved);
if (!pkg) return null;
const dir = path.dirname(resolved);
if (parts.length === 0) {
// use pkg.svelte
if (pkg.svelte) {
return path.resolve(dir, pkg.svelte);
}
} else {
if (pkg['svelte.root']) {
// TODO remove this. it's weird and unnecessary
const sub = path.resolve(dir, pkg['svelte.root'], parts.join('/'));
if (exists(sub)) return sub;
}
}
},
transform(code, id) {
if (!filter(id)) return null;
const extension = path.extname(id);
if (!~extensions.indexOf(extension)) return null;
const dependencies = [];
let preprocessPromise;
if (options.preprocess) {
if (major_version < 3) {
const preprocessOptions = {};
for (const key in options.preprocess) {
preprocessOptions[key] = (...args) => {
return Promise.resolve(options.preprocess[key](...args)).then(
resp => {
if (resp && resp.dependencies) {
dependencies.push(...resp.dependencies);
}
return resp;
}
);
};
}
preprocessPromise = preprocess(
code,
Object.assign(preprocessOptions, { filename: id })
).then(code => code.toString());
} else {
preprocessPromise = preprocess(code, options.preprocess, {
filename: id
}).then(processed => {
if (processed.dependencies) {
dependencies.push(...processed.dependencies);
}
return processed.toString();
});
}
} else {
preprocessPromise = Promise.resolve(code);
}
return preprocessPromise.then(code => {
let warnings = [];
const base_options = major_version < 3
? {
onwarn: warning => warnings.push(warning)
}
: {};
const compiled = compile(
code,
Object.assign(base_options, fixed_options, {
filename: id
}, major_version >= 3 ? null : {
name: capitalize(sanitize(id))
})
);
if (major_version >= 3) warnings = compiled.warnings || compiled.stats.warnings;
warnings.forEach(warning => {
if ((options.css || !options.emitCss) && warning.code === 'css-unused-selector') return;
if (options.onwarn) {
options.onwarn(warning, warning => this.warn(warning));
} else {
this.warn(warning);
}
});
if ((css || options.emitCss) && compiled.css.code) {
let fname = id.replace(new RegExp(`\\${extension}$`), '.css');
if (options.emitCss) {
const source_map_comment = `/*# sourceMappingURL=${compiled.css.map.toUrl()} */`;
compiled.css.code += `\n${source_map_comment}`;
compiled.js.code += `\nimport ${JSON.stringify(fname)};\n`;
}
cssLookup.set(fname, compiled.css);
}
if (this.addWatchFile) {
dependencies.forEach(dependency => this.addWatchFile(dependency));
} else {
compiled.js.dependencies = dependencies;
}
return compiled.js;
});
},
generateBundle(options, bundle) {
if (css) {
// write out CSS file. TODO would be nice if there was a
// a more idiomatic way to do this in Rollup
let result = '';
const mappings = [];
const sources = [];
const sourcesContent = [];
const chunks = Array.from(cssLookup.keys()).sort().map(key => cssLookup.get(key));
for (let chunk of chunks) {
if (!chunk.code) continue;
result += chunk.code + '\n';
if (chunk.map) {
const i = sources.length;
sources.push(chunk.map.sources[0]);
sourcesContent.push(chunk.map.sourcesContent[0]);
const decoded = decode(chunk.map.mappings);
if (i > 0) {
decoded.forEach(line => {
line.forEach(segment => {
segment[1] = i;
});
});
}
mappings.push(...decoded);
}
}
const filename = Object.keys(bundle)[0].split('.').shift() + '.css';
const writer = new CssWriter(result, filename, {
sources,
sourcesContent,
mappings: encode(mappings)
}, this.warn, this);
css(writer);
}
}
};
};