@parcel/transformer-babel 2.0.0-nightly.92 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/config.js CHANGED
@@ -4,25 +4,61 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.load = load;
7
- exports.preSerialize = preSerialize;
8
- exports.postDeserialize = postDeserialize;
9
7
 
10
- var _nullthrows = _interopRequireDefault(require("nullthrows"));
8
+ function _json() {
9
+ const data = _interopRequireDefault(require("json5"));
11
10
 
12
- var _path = _interopRequireDefault(require("path"));
11
+ _json = function () {
12
+ return data;
13
+ };
14
+
15
+ return data;
16
+ }
17
+
18
+ function _path() {
19
+ const data = _interopRequireDefault(require("path"));
20
+
21
+ _path = function () {
22
+ return data;
23
+ };
24
+
25
+ return data;
26
+ }
27
+
28
+ function internalBabelCore() {
29
+ const data = _interopRequireWildcard(require("@babel/core"));
30
+
31
+ internalBabelCore = function () {
32
+ return data;
33
+ };
34
+
35
+ return data;
36
+ }
37
+
38
+ function _utils() {
39
+ const data = require("@parcel/utils");
40
+
41
+ _utils = function () {
42
+ return data;
43
+ };
44
+
45
+ return data;
46
+ }
13
47
 
14
- var bundledBabelCore = _interopRequireWildcard(require("@babel/core"));
48
+ function _diagnostic() {
49
+ const data = require("@parcel/diagnostic");
15
50
 
16
- var _utils = require("@parcel/utils");
51
+ _diagnostic = function () {
52
+ return data;
53
+ };
17
54
 
18
- var _env = _interopRequireDefault(require("./env"));
55
+ return data;
56
+ }
19
57
 
20
58
  var _jsx = _interopRequireDefault(require("./jsx"));
21
59
 
22
60
  var _flow = _interopRequireDefault(require("./flow"));
23
61
 
24
- var _typescript = _interopRequireDefault(require("./typescript"));
25
-
26
62
  var _utils2 = require("./utils");
27
63
 
28
64
  function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
@@ -31,263 +67,333 @@ function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj;
31
67
 
32
68
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
33
69
 
34
- const TYPESCRIPT_EXTNAME_RE = /^\.tsx?/;
70
+ const TYPESCRIPT_EXTNAME_RE = /\.tsx?$/;
35
71
 
36
- const BABEL_TRANSFORMER_DIR = _path.default.dirname(__dirname);
72
+ const BABEL_TRANSFORMER_DIR = _path().default.dirname(__dirname);
37
73
 
38
- async function load(config, options, logger) {
39
- if (config.result != null) {
40
- return reload(config, options);
41
- } // Don't look for a custom babel config if inside node_modules
74
+ const JS_EXTNAME_RE = /^\.(js|cjs|mjs)$/;
75
+ const BABEL_CONFIG_FILENAMES = ['.babelrc', '.babelrc.js', '.babelrc.json', '.babelrc.cjs', '.babelrc.mjs', '.babelignore', 'babel.config.js', 'babel.config.json', 'babel.config.mjs', 'babel.config.cjs'];
76
+ const BABEL_CORE_RANGE = '^7.12.0';
42
77
 
78
+ async function load(config, options, logger) {
79
+ var _ref, _ref2, _options$env$BABEL_EN;
43
80
 
81
+ // Don't transpile inside node_modules
44
82
  if (!config.isSource) {
45
- return buildDefaultBabelConfig(config);
46
- }
83
+ return;
84
+ } // Invalidate when any babel config file is added.
47
85
 
48
- let babelCore = await loadBabelCore(config, options);
49
- let partialConfig = babelCore.loadPartialConfig({
50
- filename: config.searchPath,
51
- cwd: _path.default.dirname(config.searchPath),
52
- root: options.projectRoot
53
- }); // loadPartialConfig returns null when the file should explicitly not be run through babel (ignore/exclude)
54
86
 
55
- if (partialConfig == null) {} else if (partialConfig.hasFilesystemConfig()) {
56
- config.setResult({
57
- internal: false,
58
- config: partialConfig.options,
59
- targets: (0, _utils2.enginesToBabelTargets)(config.env)
87
+ for (let fileName of BABEL_CONFIG_FILENAMES) {
88
+ config.invalidateOnFileCreate({
89
+ fileName,
90
+ aboveFilePath: config.searchPath
60
91
  });
61
- let {
62
- babelrc: babelrcPath,
63
- config: configPath
64
- } = partialConfig;
65
- let {
66
- canBeRehydrated,
67
- dependsOnRelative,
68
- dependsOnLocal
69
- } = getStats(partialConfig.options);
70
- let configIsJS = typeof babelrcPath === 'string' && _path.default.extname(babelrcPath) === '.js' || typeof configPath === 'string' && _path.default.extname(configPath) === '.js';
71
-
72
- if (configIsJS) {
73
- logger.verbose({
74
- message: 'WARNING: Using a JavaScript Babel config file means losing out on some caching features of Parcel. Try using a .babelrc file instead.'
92
+ } // Do nothing if we cannot resolve any babel config filenames. Checking using our own
93
+ // config resolution (which is cached) is much faster than relying on babel.
94
+
95
+
96
+ if (!(await (0, _utils().resolveConfig)(options.inputFS, config.searchPath, BABEL_CONFIG_FILENAMES, options.projectRoot))) {
97
+ return buildDefaultBabelConfig(options, config);
98
+ }
99
+
100
+ const babelCore = await options.packageManager.require('@babel/core', config.searchPath, {
101
+ range: BABEL_CORE_RANGE,
102
+ saveDev: true,
103
+ shouldAutoInstall: options.shouldAutoInstall
104
+ });
105
+ config.addDevDependency({
106
+ specifier: '@babel/core',
107
+ resolveFrom: config.searchPath,
108
+ range: BABEL_CORE_RANGE
109
+ });
110
+ config.invalidateOnEnvChange('BABEL_ENV');
111
+ config.invalidateOnEnvChange('NODE_ENV');
112
+ let babelOptions = {
113
+ filename: config.searchPath,
114
+ cwd: options.projectRoot,
115
+ envName: (_ref = (_ref2 = (_options$env$BABEL_EN = options.env.BABEL_ENV) !== null && _options$env$BABEL_EN !== void 0 ? _options$env$BABEL_EN : options.env.NODE_ENV) !== null && _ref2 !== void 0 ? _ref2 : options.mode === 'production' || options.mode === 'development' ? options.mode : null) !== null && _ref !== void 0 ? _ref : 'development',
116
+ showIgnoredFiles: true
117
+ };
118
+ let partialConfig = await babelCore.loadPartialConfigAsync(babelOptions);
119
+
120
+ let addIncludedFile = file => {
121
+ if (JS_EXTNAME_RE.test(_path().default.extname(file))) {
122
+ // We need to invalidate on startup in case the config is non-static,
123
+ // e.g. uses unknown environment variables, reads from the filesystem, etc.
124
+ logger.warn({
125
+ message: `It looks like you're using a JavaScript Babel config file. This means the config cannot be watched for changes, and Babel transformations cannot be cached. You'll need to restart Parcel for changes to this config to take effect. Try using a ${_path().default.basename(file, _path().default.extname(file)) + '.json'} file instead.`
126
+ });
127
+ config.invalidateOnStartup(); // But also add the config as a dev dependency so we can at least attempt invalidation in watch mode.
128
+
129
+ config.addDevDependency({
130
+ specifier: (0, _utils().relativePath)(options.projectRoot, file),
131
+ resolveFrom: _path().default.join(options.projectRoot, 'index'),
132
+ // Also invalidate @babel/core when the config or a dependency updates.
133
+ // This ensures that the caches in @babel/core are also invalidated.
134
+ additionalInvalidations: [{
135
+ specifier: '@babel/core',
136
+ resolveFrom: config.searchPath,
137
+ range: BABEL_CORE_RANGE
138
+ }]
75
139
  });
76
- config.shouldInvalidateOnStartup(); // babel.config.js files get required by @babel/core so there's no use in setting resolved path for watch mode invalidation
77
140
  } else {
78
- config.setResolvedPath(typeof babelrcPath === 'string' ? babelrcPath : configPath);
141
+ config.invalidateOnFileChange(file);
79
142
  }
143
+ };
80
144
 
81
- if (babelrcPath && (await isExtended())) {
82
- logger.verbose({
83
- message: 'WARNING: You are using `extends` in your Babel config, which means you are losing out on some of the caching features of Parcel. Maybe try using a reusable preset instead.'
84
- });
85
- config.shouldInvalidateOnStartup();
86
- }
145
+ let warnOldVersion = () => {
146
+ logger.warn({
147
+ message: 'You are using an old version of @babel/core which does not support the necessary features for Parcel to cache and watch babel config files safely. You may need to restart Parcel for config changes to take effect. Please upgrade to @babel/core 7.12.0 or later to resolve this issue.'
148
+ });
149
+ config.invalidateOnStartup();
150
+ }; // Old versions of @babel/core return null from loadPartialConfig when the file should explicitly not be run through babel (ignore/exclude)
87
151
 
88
- if (dependsOnRelative || dependsOnLocal) {
89
- logger.verbose({
90
- message: 'WARNING: It looks like you are using local Babel plugins or presets. You will need to run with the `--no-cache` option in order to pick up changes to these until their containing package versions are bumped.'
91
- });
92
- }
93
152
 
94
- if (canBeRehydrated) {
95
- await definePluginDependencies(config);
96
- config.setResultHash((0, _utils.md5FromObject)(partialConfig.options));
97
- } else {
98
- logger.verbose({
99
- message: 'WARNING: You are using `require` to configure Babel plugins or presets. This means Babel transformations cannot be cached and will run on each build. Please use strings to configure Babel instead.'
100
- });
101
- config.setResultHash(JSON.stringify(Date.now()));
102
- config.shouldInvalidateOnStartup();
103
- }
104
- } else {
105
- await buildDefaultBabelConfig(config);
153
+ if (partialConfig == null) {
154
+ warnOldVersion();
155
+ return;
106
156
  }
107
- }
108
157
 
109
- async function buildDefaultBabelConfig(config) {
110
- let babelOptions;
158
+ if (partialConfig.files == null) {
159
+ // If the files property is missing, we're on an old version of @babel/core.
160
+ // We need to invalidate on startup because we can't properly track dependencies.
161
+ if (partialConfig.hasFilesystemConfig()) {
162
+ warnOldVersion();
111
163
 
112
- if (_path.default.extname(config.searchPath).match(TYPESCRIPT_EXTNAME_RE)) {
113
- babelOptions = (0, _typescript.default)(config);
164
+ if (typeof partialConfig.babelrcPath === 'string') {
165
+ addIncludedFile(partialConfig.babelrcPath);
166
+ }
167
+
168
+ if (typeof partialConfig.configPath === 'string') {
169
+ addIncludedFile(partialConfig.configPath);
170
+ }
171
+ }
114
172
  } else {
115
- babelOptions = (0, _flow.default)(config);
173
+ for (let file of partialConfig.files) {
174
+ addIncludedFile(file);
175
+ }
116
176
  }
117
177
 
118
- let babelTargets;
119
- let envOptions = await (0, _env.default)(config);
178
+ if (partialConfig.fileHandling != null && partialConfig.fileHandling !== 'transpile') {} else if (partialConfig.hasFilesystemConfig()) {
179
+ // Determine what syntax plugins we need to enable
180
+ let syntaxPlugins = [];
120
181
 
121
- if (envOptions != null) {
122
- babelTargets = envOptions.targets;
123
- babelOptions = mergeOptions(babelOptions, {
124
- presets: envOptions.presets
125
- });
126
- }
182
+ if (TYPESCRIPT_EXTNAME_RE.test(config.searchPath)) {
183
+ syntaxPlugins.push('typescript');
127
184
 
128
- babelOptions = mergeOptions(babelOptions, (await (0, _jsx.default)(config)));
129
-
130
- if (babelOptions != null) {
131
- babelOptions.presets = (babelOptions.presets || []).map(preset => bundledBabelCore.createConfigItem(preset, {
132
- type: 'preset',
133
- dirname: BABEL_TRANSFORMER_DIR
134
- }));
135
- babelOptions.plugins = (babelOptions.plugins || []).map(plugin => bundledBabelCore.createConfigItem(plugin, {
136
- type: 'plugin',
137
- dirname: BABEL_TRANSFORMER_DIR
138
- }));
139
- }
185
+ if (config.searchPath.endsWith('.tsx')) {
186
+ syntaxPlugins.push('jsx');
187
+ }
188
+ } else if (await (0, _jsx.default)(options, config)) {
189
+ syntaxPlugins.push('jsx');
190
+ } // If the config has plugins loaded with require(), or inline plugins in the config,
191
+ // we can't cache the result of the compilation because we don't know where they came from.
140
192
 
141
- config.setResult({
142
- internal: true,
143
- config: babelOptions,
144
- targets: babelTargets
145
- });
146
- await definePluginDependencies(config);
147
- }
148
193
 
149
- function mergeOptions(result, config) {
150
- if (!config || (!config.presets || config.presets.length === 0) && (!config.plugins || config.plugins.length === 0)) {
151
- return result;
152
- }
153
-
154
- let merged = result;
194
+ if (hasRequire(partialConfig.options)) {
195
+ logger.warn({
196
+ message: 'It looks like you are using `require` to configure Babel plugins or presets. This means Babel transformations cannot be cached and will run on each build. Please use strings to configure Babel instead.'
197
+ });
198
+ config.setCacheKey(JSON.stringify(Date.now()));
199
+ config.invalidateOnStartup();
200
+ } else {
201
+ await warnOnRedundantPlugins(options.inputFS, partialConfig, logger);
202
+ definePluginDependencies(config, partialConfig.options, options);
203
+ config.setCacheKey((0, _utils().hashObject)(partialConfig.options));
204
+ }
155
205
 
156
- if (merged) {
157
- merged.presets = (merged.presets || []).concat(config.presets || []);
158
- merged.plugins = (merged.plugins || []).concat(config.plugins || []);
206
+ return {
207
+ internal: false,
208
+ config: partialConfig.options,
209
+ targets: (0, _utils2.enginesToBabelTargets)(config.env),
210
+ syntaxPlugins
211
+ };
159
212
  } else {
160
- result = config;
213
+ return buildDefaultBabelConfig(options, config);
161
214
  }
162
-
163
- return result;
164
215
  }
165
216
 
166
- function getStats(options) {
167
- let canBeRehydrated = true;
168
- let dependsOnRelative = false;
169
- let dependsOnLocal = false;
170
- let configItems = [...options.presets, ...options.plugins];
217
+ async function buildDefaultBabelConfig(options, config) {
218
+ // If this is a .ts or .tsx file, we don't need to enable flow.
219
+ if (TYPESCRIPT_EXTNAME_RE.test(config.searchPath)) {
220
+ return;
221
+ } // Detect flow. If not enabled, babel doesn't need to run at all.
171
222
 
172
- for (let configItem of configItems) {
173
- if (!configItem.file) {
174
- canBeRehydrated = false;
175
- } else if (configItem.file.request.startsWith('.')) {
176
- dependsOnRelative = true;
177
- } else if (isLocal()) {
178
- dependsOnLocal = true;
179
- }
223
+
224
+ let babelOptions = await (0, _flow.default)(config, options);
225
+
226
+ if (babelOptions == null) {
227
+ return;
228
+ } // When flow is enabled, we may also need to enable JSX so it parses properly.
229
+
230
+
231
+ let syntaxPlugins = [];
232
+
233
+ if (await (0, _jsx.default)(options, config)) {
234
+ syntaxPlugins.push('jsx');
180
235
  }
181
236
 
237
+ babelOptions.presets = (babelOptions.presets || []).map(preset => internalBabelCore().createConfigItem(preset, {
238
+ type: 'preset',
239
+ dirname: BABEL_TRANSFORMER_DIR
240
+ }));
241
+ babelOptions.plugins = (babelOptions.plugins || []).map(plugin => internalBabelCore().createConfigItem(plugin, {
242
+ type: 'plugin',
243
+ dirname: BABEL_TRANSFORMER_DIR
244
+ }));
245
+ definePluginDependencies(config, babelOptions, options);
182
246
  return {
183
- canBeRehydrated,
184
- dependsOnRelative,
185
- dependsOnLocal
247
+ internal: true,
248
+ config: babelOptions,
249
+ syntaxPlugins
186
250
  };
187
251
  }
188
252
 
189
- function isExtended()
190
- /* babelrcPath */
191
- {
192
- // TODO: read and parse babelrc and check to see if extends property exists
193
- // need access to fs in case of memory filesystem
194
- return false;
253
+ function hasRequire(options) {
254
+ let configItems = [...options.presets, ...options.plugins];
255
+ return configItems.some(item => !item.file);
195
256
  }
196
257
 
197
- function isLocal()
198
- /* configItemPath */
199
- {
200
- // TODO: check if realpath is different, need access to fs in case of memory filesystem
201
- return false;
258
+ function definePluginDependencies(config, babelConfig, options) {
259
+ if (babelConfig == null) {
260
+ return;
261
+ }
262
+
263
+ let configItems = [...(babelConfig.presets || []), ...(babelConfig.plugins || [])];
264
+
265
+ for (let configItem of configItems) {
266
+ // FIXME: this uses a relative path from the project root rather than resolving
267
+ // from the config location because configItem.file.request can be a shorthand
268
+ // rather than a full package name.
269
+ config.addDevDependency({
270
+ specifier: (0, _utils().relativePath)(options.projectRoot, configItem.file.resolved),
271
+ resolveFrom: _path().default.join(options.projectRoot, 'index'),
272
+ // Also invalidate @babel/core when the plugin or a dependency updates.
273
+ // This ensures that the caches in @babel/core are also invalidated.
274
+ additionalInvalidations: [{
275
+ specifier: '@babel/core',
276
+ resolveFrom: config.searchPath,
277
+ range: BABEL_CORE_RANGE
278
+ }]
279
+ });
280
+ }
202
281
  }
203
282
 
204
- function preSerialize(config) {
205
- let babelConfig = config.result.config;
283
+ const redundantPresets = new Set(['@babel/preset-env', '@babel/preset-react', '@babel/preset-typescript', '@parcel/babel-preset-env']);
284
+
285
+ async function warnOnRedundantPlugins(fs, babelConfig, logger) {
286
+ var _babelConfig$config;
206
287
 
207
288
  if (babelConfig == null) {
208
289
  return;
209
- } // ConfigItem.value is a function which the v8 serializer chokes on
210
- // It is being ommited here and will be rehydrated later using the path provided by ConfigItem.file
211
-
212
-
213
- babelConfig.presets = (babelConfig.presets || []).map(({
214
- options,
215
- dirname,
216
- name,
217
- file
218
- }) => ({
219
- options,
220
- dirname,
221
- name,
222
- file
223
- }));
224
- babelConfig.plugins = (babelConfig.plugins || []).map(({
225
- options,
226
- dirname,
227
- name,
228
- file
229
- }) => ({
230
- options,
231
- dirname,
232
- name,
233
- file
234
- }));
235
- }
290
+ }
236
291
 
237
- async function definePluginDependencies(config) {
238
- let babelConfig = config.result.config;
292
+ let configPath = (_babelConfig$config = babelConfig.config) !== null && _babelConfig$config !== void 0 ? _babelConfig$config : babelConfig.babelrc;
239
293
 
240
- if (babelConfig == null) {
294
+ if (!configPath) {
241
295
  return;
242
296
  }
243
297
 
244
- let configItems = [...babelConfig.presets, ...babelConfig.plugins];
245
- await Promise.all(configItems.map(async configItem => {
246
- let pkg = (0, _nullthrows.default)((await config.getConfigFrom(configItem.file.resolved, ['package.json'], {
247
- parse: true
248
- })));
249
- config.addDevDependency(pkg.name, pkg.version);
250
- }));
251
- }
298
+ let presets = babelConfig.options.presets || [];
299
+ let plugins = babelConfig.options.plugins || [];
300
+ let foundRedundantPresets = new Set();
301
+ let filteredPresets = presets.filter(preset => {
302
+ if (redundantPresets.has(preset.file.request)) {
303
+ foundRedundantPresets.add(preset.file.request);
304
+ return false;
305
+ }
306
+
307
+ return true;
308
+ });
309
+
310
+ let filePath = _path().default.relative(process.cwd(), configPath);
252
311
 
253
- async function postDeserialize(config, options) {
254
- let babelCore = config.result.internal ? bundledBabelCore : await options.packageManager.require('@babel/core', config.searchPath);
255
- config.result.config.presets = await Promise.all(config.result.config.presets.map(async configItem => {
256
- let value = await options.packageManager.require(configItem.file.resolved, config.searchPath);
257
- value = value.default ? value.default : value;
258
- return babelCore.createConfigItem([value, configItem.options], {
259
- type: 'preset',
260
- dirname: configItem.dirname
312
+ let diagnostics = [];
313
+
314
+ if (filteredPresets.length === 0 && foundRedundantPresets.size > 0 && plugins.length === 0) {
315
+ diagnostics.push({
316
+ message: (0, _diagnostic().md)`Parcel includes transpilation by default. Babel config __${filePath}__ contains only redundant presets. Deleting it may significantly improve build performance.`,
317
+ codeFrames: [{
318
+ filePath: configPath,
319
+ codeHighlights: await getCodeHighlights(fs, configPath, foundRedundantPresets)
320
+ }],
321
+ hints: [(0, _diagnostic().md)`Delete __${filePath}__`],
322
+ documentationURL: 'https://parceljs.org/languages/javascript/#default-presets'
261
323
  });
262
- }));
263
- config.result.config.plugins = await Promise.all(config.result.config.plugins.map(async configItem => {
264
- let value = await options.packageManager.require(configItem.file.resolved, config.searchPath);
265
- value = value.default ? value.default : value;
266
- return babelCore.createConfigItem([value, configItem.options], {
267
- type: 'plugin',
268
- dirname: configItem.dirname
324
+ } else if (foundRedundantPresets.size > 0) {
325
+ diagnostics.push({
326
+ message: (0, _diagnostic().md)`Parcel includes transpilation by default. Babel config __${filePath}__ includes the following redundant presets: ${[...foundRedundantPresets].map(p => _diagnostic().md.underline(p))}. Removing these may improve build performance.`,
327
+ codeFrames: [{
328
+ filePath: configPath,
329
+ codeHighlights: await getCodeHighlights(fs, configPath, foundRedundantPresets)
330
+ }],
331
+ hints: [(0, _diagnostic().md)`Remove the above presets from __${filePath}__`],
332
+ documentationURL: 'https://parceljs.org/languages/javascript/#default-presets'
269
333
  });
270
- }));
271
- }
334
+ }
272
335
 
273
- async function reload(config, options) {
274
- let {
275
- loadPartialConfig
276
- } = await loadBabelCore(config, options);
277
- let partialConfig = loadPartialConfig({
278
- filename: config.searchPath,
279
- cwd: _path.default.dirname(config.searchPath),
280
- root: options.projectRoot
281
- });
282
- config.setResult({
283
- internal: false,
284
- config: partialConfig.options,
285
- targets: (0, _utils2.enginesToBabelTargets)(config.env)
286
- });
336
+ if (foundRedundantPresets.has('@babel/preset-env')) {
337
+ var _babelConfig$config2, _babelConfig$config3;
338
+
339
+ diagnostics.push({
340
+ message: "@babel/preset-env does not support Parcel's targets, which will likely result in unnecessary transpilation and larger bundle sizes.",
341
+ codeFrames: [{
342
+ filePath: (_babelConfig$config2 = babelConfig.config) !== null && _babelConfig$config2 !== void 0 ? _babelConfig$config2 : babelConfig.babelrc,
343
+ codeHighlights: await getCodeHighlights(fs, (_babelConfig$config3 = babelConfig.config) !== null && _babelConfig$config3 !== void 0 ? _babelConfig$config3 : babelConfig.babelrc, new Set(['@babel/preset-env']))
344
+ }],
345
+ hints: [`Either remove __@babel/preset-env__ to use Parcel's builtin transpilation, or replace with __@parcel/babel-preset-env__`],
346
+ documentationURL: 'https://parceljs.org/languages/javascript/#custom-plugins'
347
+ });
348
+ }
349
+
350
+ if (diagnostics.length > 0) {
351
+ logger.warn(diagnostics);
352
+ }
287
353
  }
288
354
 
289
- function loadBabelCore(config, options) {
290
- var _config$result;
355
+ async function getCodeHighlights(fs, filePath, redundantPresets) {
356
+ let ext = _path().default.extname(filePath);
357
+
358
+ if (ext !== '.js' && ext !== '.cjs' && ext !== '.mjs') {
359
+ let contents = await fs.readFile(filePath, 'utf8');
360
+
361
+ let json = _json().default.parse(contents);
362
+
363
+ let presets = json.presets || [];
364
+ let pointers = [];
365
+
366
+ for (let i = 0; i < presets.length; i++) {
367
+ if (Array.isArray(presets[i]) && redundantPresets.has(presets[i][0])) {
368
+ pointers.push({
369
+ type: 'value',
370
+ key: `/presets/${i}/0`
371
+ });
372
+ } else if (redundantPresets.has(presets[i])) {
373
+ pointers.push({
374
+ type: 'value',
375
+ key: `/presets/${i}`
376
+ });
377
+ }
378
+ }
291
379
 
292
- return !config.isSource || ((_config$result = config.result) === null || _config$result === void 0 ? void 0 : _config$result.internal) ? bundledBabelCore : options.packageManager.require('@babel/core', config.searchPath);
380
+ if (pointers.length > 0) {
381
+ try {
382
+ return (0, _diagnostic().generateJSONCodeHighlights)(contents, pointers);
383
+ } catch {// TODO: support code highlights for json5 sources.
384
+ // Babel supports json5 syntax, but json-source-map does not.
385
+ }
386
+ }
387
+ }
388
+
389
+ return [{
390
+ start: {
391
+ line: 1,
392
+ column: 1
393
+ },
394
+ end: {
395
+ line: 1,
396
+ column: 1
397
+ }
398
+ }];
293
399
  }
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.BABEL_RANGE = void 0;
7
+ const BABEL_RANGE = '^7.0.0';
8
+ exports.BABEL_RANGE = BABEL_RANGE;
package/lib/flow.js CHANGED
@@ -8,9 +8,17 @@ exports.default = getFlowOptions;
8
8
  /**
9
9
  * Generates a babel config for stripping away Flow types.
10
10
  */
11
- function getFlowOptions(config) {
11
+ async function getFlowOptions(config, options) {
12
12
  if (!config.isSource) {
13
13
  return null;
14
+ } // Only add flow plugin if `flow-bin` is listed as a dependency in the root package.json
15
+
16
+
17
+ let conf = await config.getConfigFrom(options.projectRoot + '/index', ['package.json']);
18
+ let pkg = conf === null || conf === void 0 ? void 0 : conf.contents;
19
+
20
+ if (!pkg || !(pkg.dependencies && pkg.dependencies['flow-bin']) && !(pkg.devDependencies && pkg.devDependencies['flow-bin'])) {
21
+ return null;
14
22
  }
15
23
 
16
24
  return {