1 | 'use strict';
|
2 | const path = require('path');
|
3 | const PluginError = require('plugin-error');
|
4 | const through = require('through2');
|
5 | const applySourceMap = require('vinyl-sourcemaps-apply');
|
6 | const replaceExt = require('replace-ext');
|
7 | const babel = require('@babel/core');
|
8 |
|
9 | function replaceExtension(fp) {
|
10 | return path.extname(fp) ? replaceExt(fp, '.js') : fp;
|
11 | }
|
12 |
|
13 | module.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);
|
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 |
|
70 |
|
71 |
|
72 | let supportsCallerOptionFlag;
|
73 | function supportsCallerOption() {
|
74 | if (supportsCallerOptionFlag === undefined) {
|
75 | try {
|
76 |
|
77 |
|
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 | }
|