@parcel/transformer-babel 2.0.0-nightly.142 → 2.0.0-nightly.1421

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