@parcel/transformer-babel 2.0.0-nightly.122 → 2.0.0-nightly.1221

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