forked from emberjs/ember-cli-babel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
337 lines (273 loc) · 10.5 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
329
330
331
332
333
334
335
336
337
'use strict';
const {
_shouldCompileModules,
_shouldIncludeHelpers,
_shouldHandleTypeScript,
_getExtensions,
_parentName,
_shouldHighlightCode,
} = require("./lib/babel-options-util");
const VersionChecker = require('ember-cli-version-checker');
const clone = require('clone');
const babel = require('@babel/core');
const getBabelOptions = require('./lib/get-babel-options');
const findApp = require('./lib/find-app');
const emberPlugins = require('./lib/ember-plugins');
const cacheKeyForTree = require('calculate-cache-key-for-tree');
const APP_BABEL_RUNTIME_VERSION = new WeakMap();
const PROJECTS_WITH_VALID_EMBER_CLI = new WeakSet();
let count = 0;
module.exports = {
name: 'ember-cli-babel',
configKey: 'ember-cli-babel',
// Note: This is not used internally for this addon, this is added for users to import this function for getting the ember specific
// babel plugins. Eg: adding ember specific babel plugins in their babel.config.js.
buildEmberPlugins: emberPlugins,
init() {
this._super.init && this._super.init.apply(this, arguments);
if (!PROJECTS_WITH_VALID_EMBER_CLI.has(this.project)) {
let checker = new VersionChecker(this);
let dep = checker.for('ember-cli', 'npm');
if (dep.lt('2.13.0')) {
throw new Error(`ember-cli-babel@7 (used by ${_parentName(this.parent)} at ${this.parent.root}) cannot be used by ember-cli versions older than 2.13, you used ${dep.version}`);
}
PROJECTS_WITH_VALID_EMBER_CLI.add(this.project);
}
},
buildBabelOptions(configOrType, _config) {
let resultType;
if (typeof configOrType !== 'string') {
_config = configOrType;
resultType = 'broccoli';
} else if (configOrType === 'broccoli') {
resultType = 'broccoli';
} else if (configOrType === 'babel') {
resultType = 'babel';
}
let config = _config || this._getAddonOptions();
const customAddonConfig = config['ember-cli-babel'];
const shouldUseBabelConfigFile = customAddonConfig && customAddonConfig.useBabelConfig;
let options;
if (shouldUseBabelConfigFile) {
let babelConfig = babel.loadPartialConfig({
root: this.parent.root,
rootMode: 'root',
envName: process.env.EMBER_ENV || process.env.BABEL_ENV || process.env.NODE_ENV || "development",
});
if (babelConfig.config === undefined) {
// should contain the file that we used for the config,
// if it is undefined then we didn't find any config and
// should error
throw new Error(
"Missing babel config file in the project root. Please double check if the babel config file exists or turn off the `useBabelConfig` option in your ember-cli-build.js file."
);
}
// If the babel config file is found, then pass the path into the options for the transpiler
// parse and leverage the same.
options = { configFile: babelConfig.config };
} else {
options = getBabelOptions(config, this);
}
if (resultType === 'babel') {
return options;
} else {
// legacy codepath
return Object.assign({}, this._buildBroccoliBabelTranspilerOptions(config), options);
}
},
_debugTree() {
if (!this._cachedDebugTree) {
this._cachedDebugTree = require('broccoli-debug').buildDebugCallback(`ember-cli-babel:${_parentName(this.parent)}`);
}
return this._cachedDebugTree.apply(null, arguments);
},
getSupportedExtensions(config = {}) {
return _getExtensions(config, this.parent, this.project);
},
_buildBroccoliBabelTranspilerOptions(config = {}) {
let emberCLIBabelConfig = config["ember-cli-babel"];
let providedAnnotation;
let throwUnlessParallelizable;
let sourceMaps = false;
let shouldCompileModules = _shouldCompileModules(config, this.project);
if (emberCLIBabelConfig) {
providedAnnotation = emberCLIBabelConfig.annotation;
throwUnlessParallelizable = emberCLIBabelConfig.throwUnlessParallelizable;
}
if (config.babel && "sourceMaps" in config.babel) {
sourceMaps = config.babel.sourceMaps;
}
let options = {
annotation: providedAnnotation || `Babel: ${_parentName(this.parent)}`,
sourceMaps,
throwUnlessParallelizable,
filterExtensions: this.getSupportedExtensions(config),
plugins: [],
};
if (shouldCompileModules) {
options.moduleIds = true;
options.getModuleId = require("./lib/relative-module-paths").getRelativeModulePath;
}
options.highlightCode = _shouldHighlightCode(this.parent);
options.babelrc = false;
options.configFile = false;
return options;
},
transpileTree(inputTree, _config) {
let config = _config || this._getAddonOptions();
let description = `000${++count}`.slice(-3);
let postDebugTree = this._debugTree(inputTree, `${description}:input`);
let {
// Separate Babel options from `broccoli-babel-transpiler` options.
babelrc,
configFile,
getModuleId,
highlightCode,
moduleIds,
plugins,
sourceMaps,
...transpilerOptions
} = this._buildBroccoliBabelTranspilerOptions(config);
let options = {
...transpilerOptions,
// `broccoli-babel-transpiler` now expects all Babel options to be
// present under a `babel` key.
babel: {
babelrc,
configFile,
getModuleId,
highlightCode,
moduleIds,
plugins,
sourceMaps,
...this.buildBabelOptions('babel', config),
},
};
let output;
const customAddonConfig = config['ember-cli-babel'];
const shouldUseBabelConfigFile = customAddonConfig && customAddonConfig.useBabelConfig;
if (!shouldUseBabelConfigFile && this._shouldDoNothing(options)) {
output = postDebugTree;
} else {
let BabelTranspiler = require('broccoli-babel-transpiler');
let transpilationInput = postDebugTree;
if (_shouldHandleTypeScript(config, this.parent, this.project)) {
let Funnel = require('broccoli-funnel');
let inputWithoutDeclarations = new Funnel(transpilationInput, { exclude: ['**/*.d.ts'] });
transpilationInput = this._debugTree(inputWithoutDeclarations, `${description}:filtered-input`);
}
output = new BabelTranspiler(transpilationInput, options);
}
return this._debugTree(output, `${description}:output`);
},
setupPreprocessorRegistry(type, registry) {
registry.add('js', {
name: 'ember-cli-babel',
ext: _getExtensions(this._getAddonOptions(), this.parent, this.project),
toTree: (tree) => this.transpileTree(tree)
});
},
_getHelperVersion() {
if (!APP_BABEL_RUNTIME_VERSION.has(this.project)) {
let checker = new VersionChecker(this.project);
APP_BABEL_RUNTIME_VERSION.set(this.project, checker.for('@babel/runtime', 'npm').version);
}
return APP_BABEL_RUNTIME_VERSION.get(this.project);
},
_getHelpersPlugin() {
return [
[
require.resolve('@babel/plugin-transform-runtime'),
{
version: this._getHelperVersion(),
regenerator: false,
useESModules: true
}
]
]
},
treeForAddon() {
// Helpers are a global config, so only the root application should bother
// generating and including the file.
let isRootBabel = this.parent === this.project;
let shouldIncludeHelpers = isRootBabel && _shouldIncludeHelpers(this._getAppOptions(), this);
if (!shouldIncludeHelpers) { return; }
const path = require('path');
const Funnel = require('broccoli-funnel');
const UnwatchedDir = require('broccoli-source').UnwatchedDir;
const babelHelpersPath = path.dirname(require.resolve('@babel/runtime/package.json'));
let babelHelpersTree = new Funnel(new UnwatchedDir(babelHelpersPath), {
srcDir: 'helpers/esm',
destDir: '@babel/runtime/helpers/esm'
});
const transpiledHelpers = this.transpileTree(babelHelpersTree, {
'ember-cli-babel': {
// prevents the helpers from being double transpiled, and including themselves
disablePresetEnv: true
}
});
return new Funnel(transpiledHelpers, {
destDir: this.moduleName(),
});
},
cacheKeyForTree(treeType) {
if (treeType === 'addon') {
let isRootBabel = this.parent === this.project;
let shouldIncludeHelpers = isRootBabel && _shouldIncludeHelpers(this._getAppOptions(), this);
return cacheKeyForTree('addon', this, [shouldIncludeHelpers]);
}
return cacheKeyForTree(treeType, this);
},
isPluginRequired(pluginName) {
let targets = this._getTargets();
// if no targets are setup, assume that all plugins are required
if (!targets) { return true; }
const isPluginRequired = require('@babel/helper-compilation-targets').isRequired;
return isPluginRequired(pluginName, targets);
},
_getAddonOptions() {
let parentOptions = this.parent && this.parent.options;
let appOptions = this.app && this.app.options;
if (parentOptions) {
let customAddonOptions = parentOptions['ember-cli-babel'];
if (customAddonOptions && 'includeExternalHelpers' in customAddonOptions) {
throw new Error('includeExternalHelpers is not supported in addon configurations, it is an app-wide configuration option');
}
}
return parentOptions || appOptions || {};
},
_getAppOptions() {
let app = findApp(this);
return (app && app.options) || {};
},
_getTargets() {
let targets = this.project && this.project.targets;
let parser = require('@babel/helper-compilation-targets').default;
if (typeof targets === 'object' && targets !== null) {
// babel version 7.10.0 introduced a change that mutates the input:
// https://github.com/babel/babel/pull/11500
// copy the object to guard against it, otherwise subsequent calls to
// _getTargets() will only have a mutated copy and lose all config from `config/targets.js`
// in the host application.
// PR to fix this upstream in babel: https://github.com/babel/babel/pull/11648
const copy = clone(targets);
return parser(copy);
} else {
return targets;
}
},
/*
* Used to discover if the addon's current configuration will compile modules
* or not.
*
* @public
* @method shouldCompileModules
*/
shouldCompileModules() {
return _shouldCompileModules(this._getAddonOptions(), this.project);
},
// detect if running babel would do nothing... and do nothing instead
_shouldDoNothing(options) {
return !options.babel.sourceMaps && !options.babel.plugins.length;
}
};