@parcel/transformer-babel 2.0.0-beta.1 → 2.0.0-nightly.1002

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,291 +4,372 @@ 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
- var _ref, _ref2, _ref3, _ref4, _options$env$BABEL_EN;
63
+ var _ref, _ref2, _options$env$BABEL_EN;
42
64
 
43
- // Don't look for a custom babel config if inside node_modules
65
+ // Don't transpile inside node_modules
44
66
  if (!config.isSource) {
45
- return buildDefaultBabelConfig(options, config);
46
- } // If we are in a monorepo, also find .babelrc configs in the sub packages.
67
+ return;
68
+ } // Invalidate when any babel config file is added.
47
69
 
48
70
 
49
- let babelrcRoots = [options.projectRoot];
50
- let packageJSONPath = await (0, _utils.resolveConfig)(options.inputFS, config.searchPath, ['package.json']);
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.
51
78
 
52
- if (packageJSONPath) {
53
- let packageRoot = _path.default.dirname(packageJSONPath);
54
79
 
55
- if (packageRoot && packageRoot !== options.projectRoot) {
56
- babelrcRoots.push(packageRoot);
57
- }
80
+ if (!(await (0, _utils().resolveConfig)(options.inputFS, config.searchPath, BABEL_CONFIG_FILENAMES, options.projectRoot))) {
81
+ return buildDefaultBabelConfig(options, config);
58
82
  }
59
83
 
60
- let babelCore = await options.packageManager.require('@babel/core', config.searchPath, {
61
- range: _constants.BABEL_RANGE,
62
- autoinstall: options.autoinstall
84
+ const babelCore = await options.packageManager.require('@babel/core', config.searchPath, {
85
+ range: _constants.BABEL_CORE_RANGE,
86
+ saveDev: true,
87
+ shouldAutoInstall: options.shouldAutoInstall
63
88
  });
64
- let partialConfig = babelCore.loadPartialConfig({
89
+ config.addDevDependency({
90
+ specifier: '@babel/core',
91
+ resolveFrom: config.searchPath,
92
+ range: _constants.BABEL_CORE_RANGE
93
+ });
94
+ config.invalidateOnEnvChange('BABEL_ENV');
95
+ config.invalidateOnEnvChange('NODE_ENV');
96
+ let babelOptions = {
65
97
  filename: config.searchPath,
66
- cwd: _path.default.dirname(config.searchPath),
67
- root: options.projectRoot,
68
- babelrcRoots,
69
- envName: (_ref = (_ref2 = (_ref3 = (_ref4 = (_options$env$BABEL_EN = options.env.BABEL_ENV) !== null && _options$env$BABEL_EN !== void 0 ? _options$env$BABEL_EN : process.env.BABEL_ENV) !== null && _ref4 !== void 0 ? _ref4 : options.env.NODE_ENV) !== null && _ref3 !== void 0 ? _ref3 : process.env.NODE_ENV) !== null && _ref2 !== void 0 ? _ref2 : options.mode === 'production' || options.mode === 'development' ? options.mode : null) !== null && _ref !== void 0 ? _ref : 'development'
70
- }); // loadPartialConfig returns null when the file should explicitly not be run through babel (ignore/exclude)
71
-
72
- if (partialConfig == null) {} else if (partialConfig.hasFilesystemConfig()) {
73
- config.setResult({
74
- internal: false,
75
- config: partialConfig.options,
76
- targets: (0, _utils2.enginesToBabelTargets)(config.env)
77
- });
78
- let {
79
- babelrc: babelrcPath,
80
- config: configPath
81
- } = partialConfig;
82
- let {
83
- canBeRehydrated,
84
- dependsOnRelative,
85
- dependsOnLocal
86
- } = getStats(partialConfig.options);
87
- let configIsJS = typeof babelrcPath === 'string' && _path.default.extname(babelrcPath) === '.js' || typeof configPath === 'string' && _path.default.extname(configPath) === '.js';
88
-
89
- if (configIsJS) {
90
- logger.verbose({
91
- 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
+ }]
92
123
  });
93
- config.shouldInvalidateOnStartup(); // babel.config.js files get required by @babel/core so there's no use in setting resolved path for watch mode invalidation
94
124
  } else {
95
- config.addIncludedFile(typeof babelrcPath === 'string' ? babelrcPath : configPath);
125
+ config.invalidateOnFileChange(file);
96
126
  }
127
+ };
97
128
 
98
- if (babelrcPath && (await isExtended())) {
99
- logger.verbose({
100
- 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.'
101
- });
102
- config.shouldInvalidateOnStartup();
103
- }
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)
104
135
 
105
- if (dependsOnRelative || dependsOnLocal) {
106
- logger.verbose({
107
- 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.'
108
- });
136
+
137
+ if (partialConfig == null) {
138
+ warnOldVersion();
139
+ return;
140
+ }
141
+
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();
147
+
148
+ if (typeof partialConfig.babelrcPath === 'string') {
149
+ addIncludedFile(partialConfig.babelrcPath);
150
+ }
151
+
152
+ if (typeof partialConfig.configPath === 'string') {
153
+ addIncludedFile(partialConfig.configPath);
154
+ }
155
+ }
156
+ } else {
157
+ for (let file of partialConfig.files) {
158
+ addIncludedFile(file);
109
159
  }
160
+ }
110
161
 
111
- if (canBeRehydrated) {
112
- await definePluginDependencies(config);
113
- config.setResultHash((0, _utils.md5FromObject)(partialConfig.options));
114
- } else {
115
- logger.verbose({
116
- 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.'
162
+ if (partialConfig.fileHandling != null && partialConfig.fileHandling !== 'transpile') {} else if (partialConfig.hasFilesystemConfig()) {
163
+ // Determine what syntax plugins we need to enable
164
+ let syntaxPlugins = [];
165
+
166
+ if (TYPESCRIPT_EXTNAME_RE.test(config.searchPath)) {
167
+ syntaxPlugins.push('typescript');
168
+
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.
176
+
177
+
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.'
117
181
  });
118
- config.setResultHash(JSON.stringify(Date.now()));
119
- config.shouldInvalidateOnStartup();
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));
120
188
  }
189
+
190
+ return {
191
+ internal: false,
192
+ config: partialConfig.options,
193
+ targets: (0, _utils2.enginesToBabelTargets)(config.env),
194
+ syntaxPlugins
195
+ };
121
196
  } else {
122
- await buildDefaultBabelConfig(options, config);
197
+ return buildDefaultBabelConfig(options, config);
123
198
  }
124
199
  }
125
200
 
126
201
  async function buildDefaultBabelConfig(options, config) {
127
- let babelOptions;
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.
128
206
 
129
- if (_path.default.extname(config.searchPath).match(TYPESCRIPT_EXTNAME_RE)) {
130
- babelOptions = (0, _typescript.default)(config);
131
- } else {
132
- babelOptions = (0, _flow.default)(config);
133
- }
134
207
 
135
- let babelTargets;
136
- let envOptions = await (0, _env.default)(config);
208
+ let babelOptions = await (0, _flow.default)(config, options);
137
209
 
138
- if (envOptions != null) {
139
- babelTargets = envOptions.targets;
140
- babelOptions = mergeOptions(babelOptions, {
141
- presets: envOptions.presets
142
- });
143
- }
210
+ if (babelOptions == null) {
211
+ return;
212
+ } // When flow is enabled, we may also need to enable JSX so it parses properly.
144
213
 
145
- babelOptions = mergeOptions(babelOptions, (await (0, _jsx.default)(options, config)));
146
-
147
- if (babelOptions != null) {
148
- babelOptions.presets = (babelOptions.presets || []).map(preset => bundledBabelCore.createConfigItem(preset, {
149
- type: 'preset',
150
- dirname: BABEL_TRANSFORMER_DIR
151
- }));
152
- babelOptions.plugins = (babelOptions.plugins || []).map(plugin => bundledBabelCore.createConfigItem(plugin, {
153
- type: 'plugin',
154
- dirname: BABEL_TRANSFORMER_DIR
155
- }));
214
+
215
+ let syntaxPlugins = [];
216
+
217
+ if (await (0, _jsx.default)(options, config)) {
218
+ syntaxPlugins.push('jsx');
156
219
  }
157
220
 
158
- config.setResult({
221
+ definePluginDependencies(config, babelOptions, options);
222
+ return {
159
223
  internal: true,
160
224
  config: babelOptions,
161
- targets: babelTargets
162
- });
163
- await definePluginDependencies(config);
225
+ syntaxPlugins
226
+ };
164
227
  }
165
228
 
166
- function mergeOptions(result, config) {
167
- if (!config || (!config.presets || config.presets.length === 0) && (!config.plugins || config.plugins.length === 0)) {
168
- return result;
169
- }
170
-
171
- let merged = result;
229
+ function hasRequire(options) {
230
+ let configItems = [...options.presets, ...options.plugins];
231
+ return configItems.some(item => !item.file);
232
+ }
172
233
 
173
- if (merged) {
174
- merged.presets = (merged.presets || []).concat(config.presets || []);
175
- merged.plugins = (merged.plugins || []).concat(config.plugins || []);
176
- } else {
177
- result = config;
234
+ function definePluginDependencies(config, babelConfig, options) {
235
+ if (babelConfig == null) {
236
+ return;
178
237
  }
179
238
 
180
- return result;
181
- }
182
-
183
- function getStats(options) {
184
- let canBeRehydrated = true;
185
- let dependsOnRelative = false;
186
- let dependsOnLocal = false;
187
- let configItems = [...options.presets, ...options.plugins];
239
+ let configItems = [...(babelConfig.presets || []), ...(babelConfig.plugins || [])];
188
240
 
189
241
  for (let configItem of configItems) {
190
- if (!configItem.file) {
191
- canBeRehydrated = false;
192
- } else if (configItem.file.request.startsWith('.')) {
193
- dependsOnRelative = true;
194
- } else if (isLocal()) {
195
- dependsOnLocal = true;
196
- }
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
+ });
197
256
  }
198
-
199
- return {
200
- canBeRehydrated,
201
- dependsOnRelative,
202
- dependsOnLocal
203
- };
204
- }
205
-
206
- function isExtended()
207
- /* babelrcPath */
208
- {
209
- // TODO: read and parse babelrc and check to see if extends property exists
210
- // need access to fs in case of memory filesystem
211
- return false;
212
257
  }
213
258
 
214
- function isLocal()
215
- /* configItemPath */
216
- {
217
- // TODO: check if realpath is different, need access to fs in case of memory filesystem
218
- return false;
219
- }
259
+ const redundantPresets = new Set(['@babel/preset-env', '@babel/preset-react', '@babel/preset-typescript', '@parcel/babel-preset-env']);
220
260
 
221
- function preSerialize(config) {
222
- let babelConfig = config.result.config;
261
+ async function warnOnRedundantPlugins(fs, babelConfig, logger) {
262
+ var _babelConfig$config;
223
263
 
224
264
  if (babelConfig == null) {
225
265
  return;
226
- } // ConfigItem.value is a function which the v8 serializer chokes on
227
- // It is being ommited here and will be rehydrated later using the path provided by ConfigItem.file
228
-
229
-
230
- babelConfig.presets = (babelConfig.presets || []).map(({
231
- options,
232
- dirname,
233
- name,
234
- file
235
- }) => ({
236
- options,
237
- dirname,
238
- name,
239
- file
240
- }));
241
- babelConfig.plugins = (babelConfig.plugins || []).map(({
242
- options,
243
- dirname,
244
- name,
245
- file
246
- }) => ({
247
- options,
248
- dirname,
249
- name,
250
- file
251
- }));
252
- }
266
+ }
253
267
 
254
- async function definePluginDependencies(config) {
255
- let babelConfig = config.result.config;
268
+ let configPath = (_babelConfig$config = babelConfig.config) !== null && _babelConfig$config !== void 0 ? _babelConfig$config : babelConfig.babelrc;
256
269
 
257
- if (babelConfig == null) {
270
+ if (!configPath) {
258
271
  return;
259
272
  }
260
273
 
261
- let configItems = [...babelConfig.presets, ...babelConfig.plugins];
262
- await Promise.all(configItems.map(async configItem => {
263
- let pkg = (0, _nullthrows.default)((await config.getConfigFrom(configItem.file.resolved, ['package.json'], {
264
- parse: true
265
- }))).contents;
266
- config.addDevDependency(pkg.name, pkg.version);
267
- }));
268
- }
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
+ }
269
282
 
270
- async function postDeserialize(config, options) {
271
- let babelCore = config.result.internal ? bundledBabelCore : await options.packageManager.require('@babel/core', config.searchPath, {
272
- autoinstall: options.autoinstall
283
+ return true;
273
284
  });
274
- config.result.config.presets = await Promise.all(config.result.config.presets.map(async configItem => {
275
- let value = await options.packageManager.require(configItem.file.resolved, config.searchPath, {
276
- autoinstall: options.autoinstall
277
- });
278
- value = value.default ? value.default : value;
279
- return babelCore.createConfigItem([value, configItem.options], {
280
- type: 'preset',
281
- dirname: configItem.dirname
285
+
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'
282
299
  });
283
- }));
284
- config.result.config.plugins = await Promise.all(config.result.config.plugins.map(async configItem => {
285
- let value = await options.packageManager.require(configItem.file.resolved, config.searchPath, {
286
- autoinstall: options.autoinstall
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'
287
309
  });
288
- value = value.default ? value.default : value;
289
- return babelCore.createConfigItem([value, configItem.options], {
290
- type: 'plugin',
291
- dirname: configItem.dirname
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'
292
323
  });
293
- }));
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
+ try {
358
+ return (0, _diagnostic().generateJSONCodeHighlights)(contents, pointers);
359
+ } catch {// TODO: support code highlights for json5 sources.
360
+ // Babel supports json5 syntax, but json-source-map does not.
361
+ }
362
+ }
363
+ }
364
+
365
+ return [{
366
+ start: {
367
+ line: 1,
368
+ column: 1
369
+ },
370
+ end: {
371
+ line: 1,
372
+ column: 1
373
+ }
374
+ }];
294
375
  }
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
  }