UNPKG

2.33 kBJavaScriptView Raw
1'use strict';
2const path = require('path');
3const PluginError = require('plugin-error');
4const through = require('through2');
5const applySourceMap = require('vinyl-sourcemaps-apply');
6const replaceExt = require('replace-ext');
7const babel = require('@babel/core');
8
9function replaceExtension(fp) {
10 return path.extname(fp) ? replaceExt(fp, '.js') : fp;
11}
12
13module.exports = function (opts) {
14 opts = opts || {};
15
16 return through.obj(function (file, enc, cb) {
17 if (file.isNull()) {
18 cb(null, file);
19 return;
20 }
21
22 if (file.isStream()) {
23 cb(new PluginError('gulp-babel', 'Streaming not supported'));
24 return;
25 }
26
27 if (!supportsCallerOption()) {
28 cb(new PluginError('gulp-babel', '@babel/core@^7.0.0 is required'));
29 return;
30 }
31
32 const fileOpts = Object.assign({}, opts, {
33 filename: file.path,
34 filenameRelative: file.relative,
35 sourceMap: Boolean(file.sourceMap),
36 sourceFileName: file.relative,
37 caller: Object.assign(
38 {name: 'babel-gulp'},
39 opts.caller
40 )
41 });
42
43 babel.transformAsync(file.contents.toString(), fileOpts).then(res => {
44 if (res) {
45 if (file.sourceMap && res.map) {
46 res.map.file = replaceExtension(file.relative);
47 applySourceMap(file, res.map);
48 }
49
50 file.contents = new Buffer(res.code); // eslint-disable-line unicorn/no-new-buffer
51 file.path = replaceExtension(file.path);
52
53 file.babel = res.metadata;
54 }
55
56 this.push(file);
57 }).catch(err => {
58 this.emit('error', new PluginError('gulp-babel', err, {
59 fileName: file.path,
60 showProperties: false
61 }));
62 }).then(
63 () => cb(),
64 () => cb()
65 );
66 });
67};
68
69// Note: We can remove this eventually, I'm just adding it so that people have
70// a little time to migrate to the newer RCs of @babel/core without getting
71// hard-to-diagnose errors about unknown 'caller' options.
72let supportsCallerOptionFlag;
73function supportsCallerOption() {
74 if (supportsCallerOptionFlag === undefined) {
75 try {
76 // Rather than try to match the Babel version, we just see if it throws
77 // when passed a 'caller' flag, and use that to decide if it is supported.
78 babel.loadPartialConfig({
79 caller: undefined,
80 babelrc: false,
81 configFile: false
82 });
83 supportsCallerOptionFlag = true;
84 } catch (err) {
85 supportsCallerOptionFlag = false;
86 }
87 }
88
89 return supportsCallerOptionFlag;
90}