@parcel/transformer-babel 2.0.0-beta.2 → 2.0.0-nightly.1004

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
@@ -5,20 +5,20 @@ Object.defineProperty(exports, "__esModule", {
5
5
  });
6
6
  exports.load = load;
7
7
 
8
- function _path() {
9
- const data = _interopRequireDefault(require("path"));
8
+ function _json() {
9
+ const data = _interopRequireDefault(require("json5"));
10
10
 
11
- _path = function () {
11
+ _json = function () {
12
12
  return data;
13
13
  };
14
14
 
15
15
  return data;
16
16
  }
17
17
 
18
- function babelCore() {
19
- const data = _interopRequireWildcard(require("@babel/core"));
18
+ function _path() {
19
+ const data = _interopRequireDefault(require("path"));
20
20
 
21
- babelCore = function () {
21
+ _path = function () {
22
22
  return data;
23
23
  };
24
24
 
@@ -35,66 +35,27 @@ function _utils() {
35
35
  return data;
36
36
  }
37
37
 
38
- function _env() {
39
- const data = _interopRequireDefault(require("./env"));
40
-
41
- _env = function () {
42
- return data;
43
- };
44
-
45
- return data;
46
- }
47
-
48
- function _jsx() {
49
- const data = _interopRequireDefault(require("./jsx"));
50
-
51
- _jsx = function () {
52
- return data;
53
- };
54
-
55
- return data;
56
- }
57
-
58
- function _flow() {
59
- const data = _interopRequireDefault(require("./flow"));
38
+ function _diagnostic() {
39
+ const data = require("@parcel/diagnostic");
60
40
 
61
- _flow = function () {
41
+ _diagnostic = function () {
62
42
  return data;
63
43
  };
64
44
 
65
45
  return data;
66
46
  }
67
47
 
68
- function _typescript() {
69
- const data = _interopRequireDefault(require("./typescript"));
48
+ var _constants = require("./constants");
70
49
 
71
- _typescript = function () {
72
- return data;
73
- };
50
+ var _jsx = _interopRequireDefault(require("./jsx"));
74
51
 
75
- return data;
76
- }
77
-
78
- function _utils2() {
79
- const data = require("./utils");
52
+ var _flow = _interopRequireDefault(require("./flow"));
80
53
 
81
- _utils2 = function () {
82
- return data;
83
- };
84
-
85
- return data;
86
- }
87
-
88
- function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
89
-
90
- 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; }
54
+ var _utils2 = require("./utils");
91
55
 
92
56
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
93
57
 
94
- const TYPESCRIPT_EXTNAME_RE = /^\.tsx?/;
95
-
96
- const BABEL_TRANSFORMER_DIR = _path().default.dirname(__dirname);
97
-
58
+ const TYPESCRIPT_EXTNAME_RE = /\.tsx?$/;
98
59
  const JS_EXTNAME_RE = /^\.(js|cjs|mjs)$/;
99
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'];
100
61
 
@@ -104,23 +65,42 @@ async function load(config, options, logger) {
104
65
  // Don't transpile inside node_modules
105
66
  if (!config.isSource) {
106
67
  return;
107
- }
68
+ } // Invalidate when any babel config file is added.
108
69
 
109
- let babelOptions = {
110
- filename: config.searchPath,
111
- cwd: options.projectRoot,
112
- 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',
113
- showIgnoredFiles: true
114
- };
115
- let partialConfig = await babelCore().loadPartialConfigAsync(babelOptions); // Invalidate when any babel config file is added.
116
70
 
117
71
  for (let fileName of BABEL_CONFIG_FILENAMES) {
118
72
  config.invalidateOnFileCreate({
119
73
  fileName,
120
74
  aboveFilePath: config.searchPath
121
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);
122
82
  }
123
83
 
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
93
+ });
94
+ config.invalidateOnEnvChange('BABEL_ENV');
95
+ config.invalidateOnEnvChange('NODE_ENV');
96
+ let babelOptions = {
97
+ filename: config.searchPath,
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
+
124
104
  let addIncludedFile = file => {
125
105
  if (JS_EXTNAME_RE.test(_path().default.extname(file))) {
126
106
  // We need to invalidate on startup in case the config is non-static,
@@ -128,17 +108,21 @@ async function load(config, options, logger) {
128
108
  logger.warn({
129
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.`
130
110
  });
131
- config.shouldInvalidateOnStartup(); // But also add the config as a dev dependency so we can at least attempt invalidation in watch mode.
111
+ config.invalidateOnStartup(); // But also add the config as a dev dependency so we can at least attempt invalidation in watch mode.
132
112
 
133
113
  config.addDevDependency({
134
- moduleSpecifier: (0, _utils().relativePath)(options.projectRoot, file),
114
+ specifier: (0, _utils().relativePath)(options.projectRoot, file),
135
115
  resolveFrom: _path().default.join(options.projectRoot, 'index'),
136
- // Also invalidate @parcel/transformer-babel when the config or a dependency updates.
116
+ // Also invalidate @babel/core when the config or a dependency updates.
137
117
  // This ensures that the caches in @babel/core are also invalidated.
138
- invalidateParcelPlugin: true
118
+ additionalInvalidations: [{
119
+ specifier: '@babel/core',
120
+ resolveFrom: config.searchPath,
121
+ range: _constants.BABEL_CORE_RANGE
122
+ }]
139
123
  });
140
124
  } else {
141
- config.addIncludedFile(file);
125
+ config.invalidateOnFileChange(file);
142
126
  }
143
127
  };
144
128
 
@@ -146,7 +130,7 @@ async function load(config, options, logger) {
146
130
  logger.warn({
147
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.'
148
132
  });
149
- config.shouldInvalidateOnStartup();
133
+ config.invalidateOnStartup();
150
134
  }; // Old versions of @babel/core return null from loadPartialConfig when the file should explicitly not be run through babel (ignore/exclude)
151
135
 
152
136
 
@@ -176,84 +160,70 @@ async function load(config, options, logger) {
176
160
  }
177
161
 
178
162
  if (partialConfig.fileHandling != null && partialConfig.fileHandling !== 'transpile') {} else if (partialConfig.hasFilesystemConfig()) {
179
- config.setResult({
180
- internal: false,
181
- config: partialConfig.options,
182
- targets: (0, _utils2().enginesToBabelTargets)(config.env)
183
- }); // If the config has plugins loaded with require(), or inline plugins in the config,
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,
184
175
  // we can't cache the result of the compilation because we don't know where they came from.
185
176
 
177
+
186
178
  if (hasRequire(partialConfig.options)) {
187
179
  logger.warn({
188
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.'
189
181
  });
190
- config.setResultHash(JSON.stringify(Date.now()));
191
- config.shouldInvalidateOnStartup();
182
+ config.setCacheKey(JSON.stringify(Date.now()));
183
+ config.invalidateOnStartup();
192
184
  } else {
193
- definePluginDependencies(config, options);
194
- config.setResultHash((0, _utils().md5FromObject)(partialConfig.options));
185
+ await warnOnRedundantPlugins(options.inputFS, partialConfig, logger);
186
+ definePluginDependencies(config, partialConfig.options, options);
187
+ config.setCacheKey((0, _utils().hashObject)(partialConfig.options));
195
188
  }
189
+
190
+ return {
191
+ internal: false,
192
+ config: partialConfig.options,
193
+ targets: (0, _utils2.enginesToBabelTargets)(config.env),
194
+ syntaxPlugins
195
+ };
196
196
  } else {
197
- await buildDefaultBabelConfig(options, config);
197
+ return buildDefaultBabelConfig(options, config);
198
198
  }
199
199
  }
200
200
 
201
201
  async function buildDefaultBabelConfig(options, config) {
202
- let jsxOptions = await (0, _jsx().default)(options, config);
203
- 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.
204
206
 
205
- if (_path().default.extname(config.searchPath).match(TYPESCRIPT_EXTNAME_RE)) {
206
- babelOptions = (0, _typescript().default)(config, jsxOptions === null || jsxOptions === void 0 ? void 0 : jsxOptions.pragma, jsxOptions === null || jsxOptions === void 0 ? void 0 : jsxOptions.pragmaFrag);
207
- } else {
208
- babelOptions = await (0, _flow().default)(config, options);
209
- }
210
207
 
211
- let babelTargets;
212
- let envOptions = await (0, _env().default)(config);
208
+ let babelOptions = await (0, _flow.default)(config, options);
213
209
 
214
- if (envOptions != null) {
215
- babelTargets = envOptions.targets;
216
- babelOptions = mergeOptions(babelOptions, envOptions.config);
217
- }
210
+ if (babelOptions == null) {
211
+ return;
212
+ } // When flow is enabled, we may also need to enable JSX so it parses properly.
218
213
 
219
- babelOptions = mergeOptions(babelOptions, jsxOptions === null || jsxOptions === void 0 ? void 0 : jsxOptions.config);
220
214
 
221
- if (babelOptions != null) {
222
- let _babelOptions = babelOptions; // For Flow
215
+ let syntaxPlugins = [];
223
216
 
224
- _babelOptions.presets = (_babelOptions.presets || []).map(preset => babelCore().createConfigItem(preset, {
225
- type: 'preset',
226
- dirname: BABEL_TRANSFORMER_DIR
227
- }));
228
- _babelOptions.plugins = (_babelOptions.plugins || []).map(plugin => babelCore().createConfigItem(plugin, {
229
- type: 'plugin',
230
- dirname: BABEL_TRANSFORMER_DIR
231
- }));
217
+ if (await (0, _jsx.default)(options, config)) {
218
+ syntaxPlugins.push('jsx');
232
219
  }
233
220
 
234
- config.setResult({
221
+ definePluginDependencies(config, babelOptions, options);
222
+ return {
235
223
  internal: true,
236
224
  config: babelOptions,
237
- targets: babelTargets
238
- });
239
- definePluginDependencies(config, options);
240
- }
241
-
242
- function mergeOptions(result, config) {
243
- if (!config || (!config.presets || config.presets.length === 0) && (!config.plugins || config.plugins.length === 0)) {
244
- return result;
245
- }
246
-
247
- let merged = result;
248
-
249
- if (merged) {
250
- merged.presets = (merged.presets || []).concat(config.presets || []);
251
- merged.plugins = (merged.plugins || []).concat(config.plugins || []);
252
- } else {
253
- result = config;
254
- }
255
-
256
- return result;
225
+ syntaxPlugins
226
+ };
257
227
  }
258
228
 
259
229
  function hasRequire(options) {
@@ -261,25 +231,145 @@ function hasRequire(options) {
261
231
  return configItems.some(item => !item.file);
262
232
  }
263
233
 
264
- function definePluginDependencies(config, options) {
265
- let babelConfig = config.result.config;
266
-
234
+ function definePluginDependencies(config, babelConfig, options) {
267
235
  if (babelConfig == null) {
268
236
  return;
269
237
  }
270
238
 
271
- let configItems = [...babelConfig.presets, ...babelConfig.plugins];
239
+ let configItems = [...(babelConfig.presets || []), ...(babelConfig.plugins || [])];
272
240
 
273
241
  for (let configItem of configItems) {
274
242
  // FIXME: this uses a relative path from the project root rather than resolving
275
243
  // from the config location because configItem.file.request can be a shorthand
276
244
  // rather than a full package name.
277
245
  config.addDevDependency({
278
- moduleSpecifier: (0, _utils().relativePath)(options.projectRoot, configItem.file.resolved),
246
+ specifier: (0, _utils().relativePath)(options.projectRoot, configItem.file.resolved),
279
247
  resolveFrom: _path().default.join(options.projectRoot, 'index'),
280
- // Also invalidate @parcel/transformer-babel when the plugin or a dependency updates.
248
+ // Also invalidate @babel/core when the plugin or a dependency updates.
281
249
  // This ensures that the caches in @babel/core are also invalidated.
282
- invalidateParcelPlugin: true
250
+ additionalInvalidations: [{
251
+ specifier: '@babel/core',
252
+ resolveFrom: config.searchPath,
253
+ range: _constants.BABEL_CORE_RANGE
254
+ }]
255
+ });
256
+ }
257
+ }
258
+
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;
263
+
264
+ if (babelConfig == null) {
265
+ return;
266
+ }
267
+
268
+ let configPath = (_babelConfig$config = babelConfig.config) !== null && _babelConfig$config !== void 0 ? _babelConfig$config : babelConfig.babelrc;
269
+
270
+ if (!configPath) {
271
+ return;
272
+ }
273
+
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
+ });
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'
299
+ });
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'
283
309
  });
284
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
+ 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
+ }];
285
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,6 +5,20 @@ 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
  */
@@ -21,9 +35,22 @@ async function getFlowOptions(config, options) {
21
35
  return null;
22
36
  }
23
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
+ });
24
48
  return {
25
- plugins: [['@babel/plugin-transform-flow-strip-types', {
49
+ plugins: [babelCore.createConfigItem(['@babel/plugin-transform-flow-strip-types', {
26
50
  requireDirective: true
27
- }]]
51
+ }], {
52
+ type: 'plugin',
53
+ dirname: _path().default.dirname(config.searchPath)
54
+ })]
28
55
  };
29
56
  }
package/lib/jsx.js CHANGED
@@ -3,7 +3,7 @@
3
3
  Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
- exports.default = getJSXOptions;
6
+ exports.default = isJSX;
7
7
 
8
8
  function _path() {
9
9
  const data = _interopRequireDefault(require("path"));
@@ -17,63 +17,29 @@ function _path() {
17
17
 
18
18
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
19
19
 
20
- const JSX_EXTENSIONS = {
21
- '.jsx': true,
22
- '.tsx': true
23
- };
24
- const JSX_PRAGMA = {
25
- react: {
26
- pragma: 'React.createElement',
27
- pragmaFrag: 'React.Fragment'
28
- },
29
- preact: {
30
- pragma: 'h',
31
- pragmaFrag: 'Fragment'
32
- },
33
- nervjs: {
34
- pragma: 'Nerv.createElement',
35
- pragmaFrag: undefined
36
- },
37
- hyperapp: {
38
- pragma: 'h',
39
- pragmaFrag: undefined
40
- }
41
- };
20
+ const JSX_EXTENSIONS = new Set(['.jsx', '.tsx']);
21
+ const JSX_LIBRARIES = ['react', 'preact', 'nervejs', 'hyperapp'];
42
22
  /**
43
- * Generates a babel config for JSX. Attempts to detect react or react-like libraries
44
- * and changes the pragma accordingly.
23
+ * Returns whether an asset is likely JSX. Attempts to detect react or react-like libraries
24
+ * along with
45
25
  */
46
26
 
47
- async function getJSXOptions(options, config) {
27
+ async function isJSX(options, config) {
48
28
  if (!config.isSource) {
49
- return null;
29
+ return false;
30
+ }
31
+
32
+ if (JSX_EXTENSIONS.has(_path().default.extname(config.searchPath))) {
33
+ return true;
50
34
  }
51
35
 
52
36
  let pkg = await config.getPackage();
53
- let reactLib;
54
37
 
55
38
  if (pkg !== null && pkg !== void 0 && pkg.alias && pkg.alias['react']) {
56
39
  // e.g.: `{ alias: { "react": "preact/compat" } }`
57
- reactLib = 'react';
40
+ return true;
58
41
  } else {
59
- // Find a dependency that we can map to a JSX pragma
60
- reactLib = Object.keys(JSX_PRAGMA).find(libName => pkg && (pkg.dependencies && pkg.dependencies[libName] || pkg.devDependencies && pkg.devDependencies[libName]));
61
- }
62
-
63
- let pragma = reactLib ? JSX_PRAGMA[reactLib].pragma : undefined;
64
- let pragmaFrag = reactLib ? JSX_PRAGMA[reactLib].pragmaFrag : undefined;
65
-
66
- if (pragma || JSX_EXTENSIONS[_path().default.extname(config.searchPath)]) {
67
- return {
68
- config: {
69
- presets: [['@babel/preset-react', {
70
- pragma,
71
- pragmaFrag,
72
- development: options.mode === 'development'
73
- }]]
74
- },
75
- pragma,
76
- pragmaFrag
77
- };
42
+ // Find a dependency that implies JSX syntax.
43
+ return JSX_LIBRARIES.some(libName => pkg && (pkg.dependencies && pkg.dependencies[libName] || pkg.devDependencies && pkg.devDependencies[libName] || pkg.peerDependencies && pkg.peerDependencies[libName]));
78
44
  }
79
45
  }
@@ -0,0 +1,59 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.remapAstLocations = remapAstLocations;
7
+
8
+ function remapAstLocations(t, ast, map) {
9
+ // remap ast to original mappings
10
+ // This improves sourcemap accuracy and fixes sourcemaps when scope-hoisting
11
+ traverseAll(t, ast.program, node => {
12
+ if (node.loc) {
13
+ var _node$loc;
14
+
15
+ if ((_node$loc = node.loc) !== null && _node$loc !== void 0 && _node$loc.start) {
16
+ let mapping = map.findClosestMapping(node.loc.start.line, node.loc.start.column);
17
+
18
+ if (mapping !== null && mapping !== void 0 && mapping.original) {
19
+ // $FlowFixMe
20
+ node.loc.start.line = mapping.original.line; // $FlowFixMe
21
+
22
+ node.loc.start.column = mapping.original.column; // $FlowFixMe
23
+
24
+ let length = node.loc.end.column - node.loc.start.column; // $FlowFixMe
25
+
26
+ node.loc.end.line = mapping.original.line; // $FlowFixMe
27
+
28
+ node.loc.end.column = mapping.original.column + length; // $FlowFixMe
29
+
30
+ node.loc.filename = mapping.source;
31
+ } else {
32
+ // Maintain null mappings?
33
+ node.loc = null;
34
+ }
35
+ }
36
+ }
37
+ });
38
+ }
39
+
40
+ function traverseAll(t, node, visitor) {
41
+ if (!node) {
42
+ return;
43
+ }
44
+
45
+ visitor(node);
46
+
47
+ for (let key of t.VISITOR_KEYS[node.type] || []) {
48
+ // $FlowFixMe
49
+ let subNode = node[key];
50
+
51
+ if (Array.isArray(subNode)) {
52
+ for (let i = 0; i < subNode.length; i++) {
53
+ traverseAll(t, subNode[i], visitor);
54
+ }
55
+ } else {
56
+ traverseAll(t, subNode, visitor);
57
+ }
58
+ }
59
+ }