@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/jsx.js CHANGED
@@ -3,65 +3,43 @@
3
3
  Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
- exports.default = getJSXOptions;
6
+ exports.default = isJSX;
7
7
 
8
- var _path = _interopRequireDefault(require("path"));
8
+ function _path() {
9
+ const data = _interopRequireDefault(require("path"));
10
+
11
+ _path = function () {
12
+ return data;
13
+ };
14
+
15
+ return data;
16
+ }
9
17
 
10
18
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
11
19
 
12
- const JSX_EXTENSIONS = {
13
- '.jsx': true,
14
- '.tsx': true
15
- };
16
- const JSX_PRAGMA = {
17
- react: {
18
- pragma: 'React.createElement',
19
- pragmaFrag: 'React.Fragment'
20
- },
21
- preact: {
22
- pragma: 'h',
23
- pragmaFrag: 'Fragment'
24
- },
25
- nervjs: {
26
- pragma: 'Nerv.createElement',
27
- pragmaFrag: undefined
28
- },
29
- hyperapp: {
30
- pragma: 'h',
31
- pragmaFrag: undefined
32
- }
33
- };
20
+ const JSX_EXTENSIONS = new Set(['.jsx', '.tsx']);
21
+ const JSX_LIBRARIES = ['react', 'preact', 'nervejs', 'hyperapp'];
34
22
  /**
35
- * Generates a babel config for JSX. Attempts to detect react or react-like libraries
36
- * and changes the pragma accordingly.
23
+ * Returns whether an asset is likely JSX. Attempts to detect react or react-like libraries
24
+ * along with
37
25
  */
38
26
 
39
- async function getJSXOptions(options, config) {
27
+ async function isJSX(options, config) {
40
28
  if (!config.isSource) {
41
- return null;
29
+ return false;
30
+ }
31
+
32
+ if (JSX_EXTENSIONS.has(_path().default.extname(config.searchPath))) {
33
+ return true;
42
34
  }
43
35
 
44
36
  let pkg = await config.getPackage();
45
- let reactLib;
46
37
 
47
- if ((pkg === null || pkg === void 0 ? void 0 : pkg.alias) && pkg.alias['react']) {
38
+ if (pkg !== null && pkg !== void 0 && pkg.alias && pkg.alias['react']) {
48
39
  // e.g.: `{ alias: { "react": "preact/compat" } }`
49
- reactLib = 'react';
40
+ return true;
50
41
  } else {
51
- // Find a dependency that we can map to a JSX pragma
52
- reactLib = Object.keys(JSX_PRAGMA).find(libName => pkg && (pkg.dependencies && pkg.dependencies[libName] || pkg.devDependencies && pkg.devDependencies[libName]));
53
- }
54
-
55
- let pragma = reactLib ? JSX_PRAGMA[reactLib].pragma : undefined;
56
- let pragmaFrag = reactLib ? JSX_PRAGMA[reactLib].pragmaFrag : undefined;
57
-
58
- if (pragma || JSX_EXTENSIONS[_path.default.extname(config.searchPath)]) {
59
- return {
60
- presets: [['@babel/preset-react', {
61
- pragma,
62
- pragmaFrag,
63
- development: options.mode === 'development'
64
- }]]
65
- };
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]));
66
44
  }
67
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
+ }
package/lib/utils.js CHANGED
@@ -4,18 +4,46 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.enginesToBabelTargets = enginesToBabelTargets;
7
- exports.getMinSemver = getMinSemver;
8
7
 
9
- var _assert = _interopRequireDefault(require("assert"));
8
+ function _assert() {
9
+ const data = _interopRequireDefault(require("assert"));
10
10
 
11
- var _semver = _interopRequireDefault(require("semver"));
11
+ _assert = function () {
12
+ return data;
13
+ };
12
14
 
13
- var _options = require("@babel/helper-compilation-targets/lib/options");
15
+ return data;
16
+ }
17
+
18
+ function _semver() {
19
+ const data = _interopRequireDefault(require("semver"));
20
+
21
+ _semver = function () {
22
+ return data;
23
+ };
24
+
25
+ return data;
26
+ }
14
27
 
15
28
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
16
29
 
17
- // List of browsers to exclude when the esmodule target is specified.
30
+ // Copied from @babel/helper-compilation-targets/lib/options.js
31
+ const TargetNames = {
32
+ node: 'node',
33
+ chrome: 'chrome',
34
+ opera: 'opera',
35
+ edge: 'edge',
36
+ firefox: 'firefox',
37
+ safari: 'safari',
38
+ ie: 'ie',
39
+ ios: 'ios',
40
+ android: 'android',
41
+ electron: 'electron',
42
+ samsung: 'samsung',
43
+ rhino: 'rhino'
44
+ }; // List of browsers to exclude when the esmodule target is specified.
18
45
  // Based on https://caniuse.com/#feat=es6-module
46
+
19
47
  const ESMODULE_BROWSERS = ['not ie <= 11', 'not edge < 16', 'not firefox < 60', 'not chrome < 61', 'not safari < 11', 'not opera < 48', 'not ios_saf < 11', 'not op_mini all', 'not android < 76', 'not blackberry > 0', 'not op_mob > 0', 'not and_chr < 76', 'not and_ff < 68', 'not ie_mob > 0', 'not and_uc > 0', 'not samsung < 8.2', 'not and_qq > 0', 'not baidu > 0', 'not kaios > 0'];
20
48
 
21
49
  function enginesToBabelTargets(env) {
@@ -32,9 +60,11 @@ function enginesToBabelTargets(env) {
32
60
  if (engineName === 'browsers') {
33
61
  targets[engineName] = engineValue;
34
62
  } else {
35
- (0, _assert.default)(typeof engineValue === 'string');
36
- if (!_options.TargetNames.hasOwnProperty(engineName)) continue;
37
- let minVersion = getMinSemver(engineValue);
63
+ var _semver$minVersion;
64
+
65
+ (0, _assert().default)(typeof engineValue === 'string');
66
+ if (!TargetNames.hasOwnProperty(engineName)) continue;
67
+ let minVersion = (_semver$minVersion = _semver().default.minVersion(engineValue)) === null || _semver$minVersion === void 0 ? void 0 : _semver$minVersion.toString();
38
68
  targets[engineName] = minVersion !== null && minVersion !== void 0 ? minVersion : engineValue;
39
69
  }
40
70
  }
@@ -53,16 +83,4 @@ function enginesToBabelTargets(env) {
53
83
  }
54
84
 
55
85
  return targets;
56
- } // TODO: Replace with `minVersion` (https://github.com/npm/node-semver#ranges-1)
57
- // once semver has been upgraded across Parcel.
58
-
59
-
60
- function getMinSemver(version) {
61
- try {
62
- let range = new _semver.default.Range(version);
63
- let sorted = range.set.sort((a, b) => a[0].semver.compare(b[0].semver));
64
- return sorted[0][0].semver.version;
65
- } catch (err) {
66
- return null;
67
- }
68
86
  }
package/package.json CHANGED
@@ -1,10 +1,14 @@
1
1
  {
2
2
  "name": "@parcel/transformer-babel",
3
- "version": "2.0.0-beta.1",
3
+ "version": "2.0.0-nightly.1002+5530a6ef",
4
4
  "license": "MIT",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
8
+ "funding": {
9
+ "type": "opencollective",
10
+ "url": "https://opencollective.com/parcel"
11
+ },
8
12
  "repository": {
9
13
  "type": "git",
10
14
  "url": "https://github.com/parcel-bundler/parcel.git"
@@ -12,32 +16,24 @@
12
16
  "main": "lib/BabelTransformer.js",
13
17
  "source": "src/BabelTransformer.js",
14
18
  "engines": {
15
- "node": ">= 10.0.0",
16
- "parcel": "^2.0.0-alpha.1.1"
19
+ "node": ">= 12.0.0",
20
+ "parcel": "2.0.0-nightly.1000+5530a6ef"
17
21
  },
18
22
  "dependencies": {
19
- "@babel/core": "^7.0.0",
20
- "@babel/generator": "^7.0.0",
21
- "@babel/helper-compilation-targets": "^7.8.4",
22
- "@babel/plugin-transform-flow-strip-types": "^7.0.0",
23
- "@babel/plugin-transform-typescript": "^7.4.5",
24
- "@babel/preset-env": "^7.0.0",
25
- "@babel/preset-react": "^7.0.0",
26
- "@babel/traverse": "^7.0.0",
27
- "@parcel/babel-ast-utils": "2.0.0-beta.1",
28
- "@parcel/babel-preset-env": "2.0.0-beta.1",
29
- "@parcel/plugin": "2.0.0-beta.1",
30
- "@parcel/utils": "2.0.0-beta.1",
23
+ "@parcel/diagnostic": "2.0.0-nightly.1002+5530a6ef",
24
+ "@parcel/plugin": "2.0.0-nightly.1002+5530a6ef",
25
+ "@parcel/source-map": "^2.0.0",
26
+ "@parcel/utils": "2.0.0-nightly.1002+5530a6ef",
31
27
  "browserslist": "^4.6.6",
32
- "core-js": "^3.2.1",
28
+ "json5": "^2.2.0",
33
29
  "nullthrows": "^1.1.1",
34
30
  "semver": "^5.7.0"
35
31
  },
36
32
  "devDependencies": {
37
- "@parcel/types": "2.0.0-beta.1"
38
- },
39
- "peerDependencies": {
40
- "@parcel/core": "^2.0.0-alpha.3.1"
33
+ "@babel/core": "^7.12.0",
34
+ "@babel/preset-env": "^7.0.0",
35
+ "@babel/types": "^7.12.0",
36
+ "@parcel/types": "2.0.0-nightly.1002+5530a6ef"
41
37
  },
42
- "gitHead": "74335525be92e23bac4ed1bf30595443cfb238e3"
38
+ "gitHead": "5530a6eff8b619873353baeb0457ae4ec591e9fa"
43
39
  }
@@ -1,22 +1,16 @@
1
1
  // @flow strict-local
2
2
 
3
- import {generate, babelErrorEnhancer} from '@parcel/babel-ast-utils';
3
+ import {babelErrorEnhancer} from './babelErrorUtils';
4
4
  import {Transformer} from '@parcel/plugin';
5
+ import {relativeUrl} from '@parcel/utils';
6
+ import SourceMap from '@parcel/source-map';
5
7
  import semver from 'semver';
6
8
  import babel7 from './babel7';
7
- import {load, preSerialize, postDeserialize} from './config';
9
+ import {load} from './config';
8
10
 
9
- export default new Transformer({
10
- async loadConfig({config, options, logger}) {
11
- await load(config, options, logger);
12
- },
13
-
14
- preSerializeConfig({config}) {
15
- return preSerialize(config);
16
- },
17
-
18
- postDeserializeConfig({config, options}) {
19
- return postDeserialize(config, options);
11
+ export default (new Transformer({
12
+ loadConfig({config, options, logger}) {
13
+ return load(config, options, logger);
20
14
  },
21
15
 
22
16
  canReuseAST({ast}) {
@@ -24,16 +18,20 @@ export default new Transformer({
24
18
  },
25
19
 
26
20
  async transform({asset, config, options}) {
27
- // TODO: come up with a better name
28
21
  try {
29
22
  if (config?.config) {
30
23
  if (
31
24
  asset.meta.babelPlugins != null &&
32
25
  Array.isArray(asset.meta.babelPlugins)
33
26
  ) {
34
- await babel7(asset, options, config, asset.meta.babelPlugins);
27
+ await babel7({
28
+ asset,
29
+ options,
30
+ babelOptions: config,
31
+ additionalPlugins: asset.meta.babelPlugins,
32
+ });
35
33
  } else {
36
- await babel7(asset, options, config);
34
+ await babel7({asset, options, babelOptions: config});
37
35
  }
38
36
  }
39
37
 
@@ -43,7 +41,54 @@ export default new Transformer({
43
41
  }
44
42
  },
45
43
 
46
- generate({asset, ast, options}) {
47
- return generate({asset, ast, options});
44
+ async generate({asset, ast, options}) {
45
+ let originalSourceMap = await asset.getMap();
46
+ let sourceFileName: string = relativeUrl(
47
+ options.projectRoot,
48
+ asset.filePath,
49
+ );
50
+
51
+ const babelCorePath = await options.packageManager.resolve(
52
+ '@babel/core',
53
+ asset.filePath,
54
+ {
55
+ range: '^7.12.0',
56
+ saveDev: true,
57
+ shouldAutoInstall: options.shouldAutoInstall,
58
+ },
59
+ );
60
+
61
+ const {default: generate} = await options.packageManager.require(
62
+ '@babel/generator',
63
+ babelCorePath.resolved,
64
+ );
65
+
66
+ let {code, rawMappings} = generate(ast.program, {
67
+ sourceFileName,
68
+ sourceMaps: !!asset.env.sourceMap,
69
+ comments: true,
70
+ });
71
+
72
+ let map = new SourceMap(options.projectRoot);
73
+ if (rawMappings) {
74
+ map.addIndexedMappings(rawMappings);
75
+ }
76
+
77
+ if (originalSourceMap) {
78
+ // The babel AST already contains the correct mappings, but not the source contents.
79
+ // We need to copy over the source contents from the original map.
80
+ let sourcesContent = originalSourceMap.getSourcesContentMap();
81
+ for (let filePath in sourcesContent) {
82
+ let content = sourcesContent[filePath];
83
+ if (content != null) {
84
+ map.setSourceContent(filePath, content);
85
+ }
86
+ }
87
+ }
88
+
89
+ return {
90
+ content: code,
91
+ map,
92
+ };
48
93
  },
49
- });
94
+ }): Transformer);
package/src/babel7.js CHANGED
@@ -1,31 +1,37 @@
1
1
  // @flow
2
2
 
3
3
  import type {MutableAsset, AST, PluginOptions} from '@parcel/types';
4
+ import typeof * as BabelCore from '@babel/core';
4
5
 
5
6
  import invariant from 'assert';
6
- import * as bundledBabelCore from '@babel/core';
7
7
  import {relativeUrl} from '@parcel/utils';
8
+ import {remapAstLocations} from './remapAstLocations';
8
9
 
9
- import {BABEL_RANGE} from './constants';
10
10
  import packageJson from '../package.json';
11
11
 
12
12
  const transformerVersion: mixed = packageJson.version;
13
13
  invariant(typeof transformerVersion === 'string');
14
14
 
15
- export default async function babel7(
15
+ type Babel7TransformOptions = {|
16
16
  asset: MutableAsset,
17
17
  options: PluginOptions,
18
18
  babelOptions: any,
19
- additionalPlugins: Array<any> = [],
19
+ additionalPlugins?: Array<any>,
20
+ |};
21
+
22
+ export default async function babel7(
23
+ opts: Babel7TransformOptions,
20
24
  ): Promise<?AST> {
21
- // If this is an internally generated config, use our internal @babel/core,
22
- // otherwise require a local version from the package we're compiling.
23
- let babel = babelOptions.internal
24
- ? bundledBabelCore
25
- : await options.packageManager.require('@babel/core', asset.filePath, {
26
- range: BABEL_RANGE,
27
- autoinstall: options.autoinstall,
28
- });
25
+ let {asset, options, babelOptions, additionalPlugins = []} = opts;
26
+ const babelCore: BabelCore = await options.packageManager.require(
27
+ '@babel/core',
28
+ asset.filePath,
29
+ {
30
+ range: '^7.12.0',
31
+ saveDev: true,
32
+ shouldAutoInstall: options.shouldAutoInstall,
33
+ },
34
+ );
29
35
 
30
36
  let config = {
31
37
  ...babelOptions.config,
@@ -41,7 +47,16 @@ export default async function babel7(
41
47
  allowReturnOutsideFunction: true,
42
48
  strictMode: false,
43
49
  sourceType: 'module',
44
- plugins: ['dynamicImport'],
50
+ plugins: [
51
+ ...(babelOptions.config.parserOpts?.plugins ?? []),
52
+ ...(babelOptions.syntaxPlugins ?? []),
53
+ // Applied by preset-env
54
+ 'classProperties',
55
+ 'classPrivateProperties',
56
+ 'classPrivateMethods',
57
+ 'exportDefaultFrom',
58
+ // 'topLevelAwait'
59
+ ],
45
60
  },
46
61
  caller: {
47
62
  name: 'parcel',
@@ -54,13 +69,19 @@ export default async function babel7(
54
69
  let ast = await asset.getAST();
55
70
  let res;
56
71
  if (ast) {
57
- res = await babel.transformFromAstAsync(
72
+ res = await babelCore.transformFromAstAsync(
58
73
  ast.program,
59
74
  asset.isASTDirty() ? undefined : await asset.getCode(),
60
75
  config,
61
76
  );
62
77
  } else {
63
- res = await babel.transformAsync(await asset.getCode(), config);
78
+ res = await babelCore.transformAsync(await asset.getCode(), config);
79
+ if (res.ast) {
80
+ let map = await asset.getMap();
81
+ if (map) {
82
+ remapAstLocations(babelCore.types, res.ast, map);
83
+ }
84
+ }
64
85
  }
65
86
 
66
87
  if (res.ast) {
@@ -0,0 +1,30 @@
1
+ // @flow
2
+ import type {BaseAsset} from '@parcel/types';
3
+
4
+ export type BabelError = Error & {
5
+ loc?: {
6
+ line: number,
7
+ column: number,
8
+ ...
9
+ },
10
+ source?: string,
11
+ filePath?: string,
12
+ ...
13
+ };
14
+
15
+ export async function babelErrorEnhancer(
16
+ error: BabelError,
17
+ asset: BaseAsset,
18
+ ): Promise<BabelError> {
19
+ if (error.loc) {
20
+ let start = error.message.startsWith(asset.filePath)
21
+ ? asset.filePath.length + 1
22
+ : 0;
23
+ error.message = error.message.slice(start).split('\n')[0].trim();
24
+ }
25
+
26
+ error.source = await asset.getCode();
27
+ error.filePath = asset.filePath;
28
+
29
+ return error;
30
+ }