forked from rollup/plugins
-
Notifications
You must be signed in to change notification settings - Fork 0
/
as-input-plugin.js
464 lines (405 loc) · 13 KB
/
as-input-plugin.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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
import * as nodePath from 'path';
import * as fs from 'fs';
import test from 'ava';
import { rollup } from 'rollup';
import { SourceMapConsumer } from 'source-map';
import jsonPlugin from '@rollup/plugin-json';
import nodeResolvePlugin from '@rollup/plugin-node-resolve';
import { getCode } from '../../../util/test';
import babelPlugin, { getBabelOutputPlugin, createBabelInputPluginFactory } from '..';
process.chdir(__dirname);
function getLocation(source, charIndex) {
const lines = source.split('\n');
const len = lines.length;
let lineStart = 0;
for (let i = 0; i < len; i += 1) {
const line = lines[i];
// +1 for newline
const lineEnd = lineStart + line.length + 1;
if (lineEnd > charIndex) {
return { line: i + 1, column: charIndex - lineStart };
}
lineStart = lineEnd;
}
throw new Error('Could not determine location of character');
}
function replaceConsoleLogProperty({ types: t }) {
return {
name: 'replace-console-log-property',
visitor: {
MemberExpression(path, state) {
const { opts } = state;
if (path.node.property.name === 'log') {
path.get('property').replaceWith(t.identifier(opts.replace));
}
}
}
};
}
async function generate(input, babelOptions = {}, generateOptions = {}, rollupOptions = {}) {
const bundle = await rollup({
input,
plugins: [babelPlugin({ babelHelpers: 'bundled', ...babelOptions })],
...rollupOptions
});
return getCode(bundle, {
format: 'cjs',
exports: 'auto',
...generateOptions
});
}
test('runs code through babel', async (t) => {
const code = await generate('fixtures/basic/main.js');
t.false(code.includes('const'));
t.is(
code,
`'use strict';
var answer = 42;
console.log("the answer is ".concat(answer));
`
);
});
test('adds helpers', async (t) => {
const code = await generate('fixtures/class/main.js');
t.true(code.includes('function _classCallCheck'));
});
test('adds helpers in loose mode', async (t) => {
const code = await generate('fixtures/class-loose/main.js');
t.true(code.includes('function _inherits'));
});
test('does not babelify excluded code', async (t) => {
const code = await generate('fixtures/exclusions/main.js', { exclude: '**/foo.js' });
// eslint-disable-next-line no-template-curly-in-string
t.false(code.includes('${foo()}'));
t.true(code.includes('=> 42'));
t.is(
code,
`'use strict';
const foo = () => 42;
console.log("the answer is ".concat(foo()));
`
);
});
test('generates sourcemap by default', async (t) => {
const bundle = await rollup({
input: 'fixtures/class/main.js',
plugins: [babelPlugin({ babelHelpers: 'bundled' })]
});
const {
output: [{ code, map }]
} = await bundle.generate({ format: 'cjs', exports: 'auto', sourcemap: true });
const target = 'log';
const smc = await new SourceMapConsumer(map);
const loc = getLocation(code, code.indexOf(target));
const original = smc.originalPositionFor(loc);
t.deepEqual(original, {
source: 'fixtures/class/main.js'.split(nodePath.sep).join('/'),
line: 3,
column: 12,
name: target
});
});
test('works with proposal-decorators (rollup/rollup-plugin-babel#18)', async (t) => {
await t.notThrowsAsync(() =>
rollup({
input: 'fixtures/proposal-decorators/main.js',
plugins: [babelPlugin({ babelHelpers: 'bundled' })]
})
);
});
test('checks config per-file', async (t) => {
const code = await generate('fixtures/checks/main.js', {}, { format: 'esm' });
t.true(code.includes('class Foo'));
t.true(code.includes('var Bar'));
t.false(code.includes('class Bar'));
});
test('allows transform-runtime to be used instead of bundled helpers', async (t) => {
const warnings = [];
const code = await generate(
'fixtures/runtime-helpers/main.js',
{ babelHelpers: 'runtime' },
{},
{
onwarn(warning) {
warnings.push(warning.message);
}
}
);
t.deepEqual(warnings, [
`'@babel/runtime/helpers/classCallCheck' is imported by fixtures${nodePath.sep}runtime-helpers${nodePath.sep}main.js, but could not be resolved – treating it as an external dependency`
]);
t.is(
code,
`'use strict';
var _classCallCheck = require('@babel/runtime/helpers/classCallCheck');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var _classCallCheck__default = /*#__PURE__*/_interopDefaultLegacy(_classCallCheck);
var Foo = function Foo() {
_classCallCheck__default['default'](this, Foo);
};
module.exports = Foo;
`
);
});
test('allows transform-runtime to inject esm version of helpers', async (t) => {
const warnings = [];
const code = await generate(
'fixtures/runtime-helpers-esm/main.js',
{ babelHelpers: 'runtime' },
{
format: 'esm'
},
{
onwarn(warning) {
warnings.push(warning.message);
}
}
);
t.deepEqual(warnings, [
`'@babel/runtime/helpers/esm/classCallCheck' is imported by fixtures${nodePath.sep}runtime-helpers-esm${nodePath.sep}main.js, but could not be resolved – treating it as an external dependency`
]);
t.is(
code,
`import _classCallCheck from '@babel/runtime/helpers/esm/classCallCheck';
var Foo = function Foo() {
_classCallCheck(this, Foo);
};
export default Foo;
`
);
});
test('allows transform-runtime to be used instead of bundled helpers, but throws when CommonJS is used', async (t) => {
await t.throwsAsync(
() => generate('fixtures/runtime-helpers-commonjs/main.js', { babelHelpers: 'runtime' }),
{
message: /Rollup requires that your Babel configuration keeps ES6 module syntax intact/
}
);
});
test('allows using external-helpers plugin in combination with @babel/plugin-external-helpers', async (t) => {
const code = await generate('fixtures/external-helpers/main.js', {
babelHelpers: 'external'
});
t.false(code.includes('function _classCallCheck'));
t.true(code.includes('babelHelpers.classCallCheck'));
t.is(
code,
`'use strict';
var Foo = function Foo() {
babelHelpers.classCallCheck(this, Foo);
};
var Bar = function Bar() {
babelHelpers.classCallCheck(this, Bar);
};
var main = [new Foo(), new Bar()];
module.exports = main;
`
);
});
test('correctly renames helpers (rollup/rollup-plugin-babel#22)', async (t) => {
const code = await generate('fixtures/named-function-helper/main.js');
t.false(code.includes('babelHelpers_get get'), 'helper was incorrectly renamed');
});
test('runs preflight check correctly in absence of class transformer (rollup/rollup-plugin-babel#23)', async (t) => {
await t.notThrowsAsync(() =>
rollup({
input: 'fixtures/no-class-transformer/main.js',
plugins: [babelPlugin({ babelHelpers: 'bundled' })]
})
);
});
test('produces valid code with typeof helper', async (t) => {
const code = await generate('fixtures/typeof/main.js');
t.false(code.includes('var typeof'));
});
test('handles babelrc with ignore option used', async (t) => {
const code = await generate('fixtures/ignored-file/main.js');
t.true(code.includes('class Ignored'));
});
test('transpiles only files with default extensions', async (t) => {
const code = await generate(
'fixtures/extensions-default/main.js',
{},
{},
{
plugins: [babelPlugin({ babelHelpers: 'bundled' }), jsonPlugin()]
}
);
t.false(code.includes('class Es '), 'should transpile .es');
t.false(code.includes('class Es6 '), 'should transpile .es6');
t.false(code.includes('class Js '), 'should transpile .js');
t.false(code.includes('class Jsx '), 'should transpile .jsx');
t.false(code.includes('class Mjs '), 'should transpile .mjs');
t.true(code.includes('class Other '), 'should not transpile .other');
});
test('transpiles only files with whitelisted extensions', async (t) => {
const code = await generate('fixtures/extensions-custom/main.js', {
extensions: ['.js', '.other']
});
t.true(code.includes('class Es '), 'should not transpile .es');
t.true(code.includes('class Es6 '), 'should not transpile .es6');
t.false(code.includes('class Js '), 'should transpile .js');
t.true(code.includes('class Jsx '), 'should not transpile .jsx');
t.true(code.includes('class Mjs '), 'should not transpile .mjs');
t.false(code.includes('class Other '), 'should transpile .other');
});
test('transpiles files when path contains query and hash', async (t) => {
const code = await generate(
'fixtures/with-query-and-hash/main.js',
{},
{},
{
plugins: [
babelPlugin({ babelHelpers: 'bundled' }),
// node-resolve plugin know how to resolve relative request with query
nodeResolvePlugin(),
{
load(id) {
// rollup don't know how to load module with query
// we could teach rollup to discard query while loading module
const [bareId] = id.split(`?`);
return fs.readFileSync(bareId, 'utf-8');
}
}
]
}
);
t.true(code.includes('function WithQuery()'), 'should transpile when path contains query');
t.true(code.includes('function WithHash()'), 'should transpile when path contains hash');
t.true(
code.includes('function WithQueryAndHash()'),
'should transpile when path contains query and hash'
);
});
test('throws when trying to add babel helper unavailable in used @babel/core version', async (t) => {
await t.throwsAsync(
() =>
generate('fixtures/basic/main.js', {
plugins: [
function testPlugin() {
return {
visitor: {
Program(path, state) {
state.file.addHelper('__nonexistentHelper');
}
}
};
}
]
}),
{
message: `${nodePath.resolve(
__dirname,
'fixtures',
'basic',
'main.js'
)}: Unknown helper __nonexistentHelper`
}
);
});
test('works with minified bundled helpers', async (t) => {
const BASE_CHAR_CODE = 'a'.charCodeAt(0);
let counter = 0;
await t.notThrowsAsync(() =>
generate('fixtures/class/main.js', {
plugins: [
function testPlugin({ types }) {
return {
visitor: {
FunctionDeclaration(path) {
// super simple mangling
path
.get('id')
.replaceWith(types.identifier(String.fromCharCode(BASE_CHAR_CODE + counter)));
counter += 1;
}
}
};
}
]
})
);
});
test('supports customizing the loader', async (t) => {
const customBabelPlugin = createBabelInputPluginFactory(() => {
return {
config(cfg) {
return {
...cfg.options,
plugins: [
...(cfg.options.plugins || []),
// Include a custom plugin in the options.
[replaceConsoleLogProperty, { replace: 'foobaz' }]
]
};
},
result(result) {
return {
...result,
code: `${result.code}\n// Generated by some custom loader`
};
}
};
});
const bundle = await rollup({
input: 'fixtures/basic/main.js',
plugins: [customBabelPlugin({ babelHelpers: 'bundled' })]
});
const code = await getCode(bundle);
t.true(code.includes('// Generated by some custom loader'), 'adds the custom comment');
t.true(code.includes('console.foobaz'), 'runs the plugin');
});
test('supports overriding the plugin options in custom loader', async (t) => {
const customBabelPlugin = createBabelInputPluginFactory(() => {
return {
options(options) {
// Ignore the js extension to test overriding the options
return { pluginOptions: { ...options, extensions: ['.x'] } };
},
config(cfg) {
return {
...cfg.options,
plugins: [
...(cfg.options.plugins || []),
// Include a custom plugin in the options.
[replaceConsoleLogProperty, { replace: 'foobaz' }]
]
};
},
result(result) {
return {
...result,
code: `${result.code}\n// Generated by some custom loader`
};
}
};
});
const bundle = await rollup({
input: 'fixtures/basic/main.js',
plugins: [customBabelPlugin({ babelHelpers: 'bundled' })]
});
const code = await getCode(bundle);
t.false(
code.includes('// Generated by some custom loader'),
'does not add the comment to ignored file'
);
t.false(code.includes('console.foobaz'), 'does not run the plugin on ignored file');
});
test('uses babel plugins passed in to the rollup plugin', async (t) => {
const code = await generate('fixtures/basic/main.js', {
plugins: [[replaceConsoleLogProperty, { replace: 'foobaz' }]]
});
t.true(code.includes('console.foobaz'));
});
test('can be used as an input plugin while transforming the output', async (t) => {
const bundle = await rollup({
input: 'fixtures/basic/main.js',
plugins: [
getBabelOutputPlugin({
presets: ['@babel/env']
})
]
});
const code = await getCode(bundle);
t.false(code.includes('const'));
});