@parcel/transformer-babel 2.16.4 → 3.0.0-alpha.2

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 DELETED
@@ -1,311 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.load = load;
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");
36
- var _jsx = _interopRequireDefault(require("./jsx"));
37
- var _flow = _interopRequireDefault(require("./flow"));
38
- var _utils2 = require("./utils");
39
- function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
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'];
43
- async function load(config, options, logger) {
44
- // Don't transpile inside node_modules
45
- if (!config.isSource) {
46
- return;
47
- }
48
-
49
- // Invalidate when any babel config file is added.
50
- for (let fileName of BABEL_CONFIG_FILENAMES) {
51
- config.invalidateOnFileCreate({
52
- fileName,
53
- aboveFilePath: config.searchPath
54
- });
55
- }
56
-
57
- // Do nothing if we cannot resolve any babel config filenames. Checking using our own
58
- // config resolution (which is cached) is much faster than relying on babel.
59
- if (!(await (0, _utils().resolveConfig)(options.inputFS, config.searchPath, BABEL_CONFIG_FILENAMES, options.projectRoot))) {
60
- return buildDefaultBabelConfig(options, config);
61
- }
62
- const babelCore = await options.packageManager.require('@babel/core', config.searchPath, {
63
- range: _constants.BABEL_CORE_RANGE,
64
- saveDev: true,
65
- shouldAutoInstall: options.shouldAutoInstall
66
- });
67
- config.addDevDependency({
68
- specifier: '@babel/core',
69
- resolveFrom: config.searchPath,
70
- range: _constants.BABEL_CORE_RANGE
71
- });
72
- config.invalidateOnEnvChange('BABEL_ENV');
73
- config.invalidateOnEnvChange('NODE_ENV');
74
- let babelOptions = {
75
- filename: config.searchPath,
76
- cwd: options.projectRoot,
77
- envName: options.env.BABEL_ENV ?? options.env.NODE_ENV ?? (options.mode === 'production' || options.mode === 'development' ? options.mode : null) ?? 'development',
78
- showIgnoredFiles: true
79
- };
80
- let partialConfig = await babelCore.loadPartialConfigAsync(babelOptions);
81
- let addIncludedFile = file => {
82
- if (JS_EXTNAME_RE.test(_path().default.extname(file))) {
83
- // We need to invalidate on startup in case the config is non-static,
84
- // e.g. uses unknown environment variables, reads from the filesystem, etc.
85
- logger.warn({
86
- 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.`
87
- });
88
- config.invalidateOnStartup();
89
-
90
- // But also add the config as a dev dependency so we can at least attempt invalidation in watch mode.
91
- config.addDevDependency({
92
- specifier: (0, _utils().relativePath)(options.projectRoot, file),
93
- resolveFrom: _path().default.join(options.projectRoot, 'index'),
94
- // Also invalidate @babel/core when the config or a dependency updates.
95
- // This ensures that the caches in @babel/core are also invalidated.
96
- additionalInvalidations: [{
97
- specifier: '@babel/core',
98
- resolveFrom: config.searchPath,
99
- range: _constants.BABEL_CORE_RANGE
100
- }]
101
- });
102
- } else {
103
- config.invalidateOnFileChange(file);
104
- }
105
- };
106
- let warnOldVersion = () => {
107
- logger.warn({
108
- 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.'
109
- });
110
- config.invalidateOnStartup();
111
- };
112
-
113
- // Old versions of @babel/core return null from loadPartialConfig when the file should explicitly not be run through babel (ignore/exclude)
114
- if (partialConfig == null) {
115
- warnOldVersion();
116
- return;
117
- }
118
- if (partialConfig.files == null) {
119
- // If the files property is missing, we're on an old version of @babel/core.
120
- // We need to invalidate on startup because we can't properly track dependencies.
121
- if (partialConfig.hasFilesystemConfig()) {
122
- warnOldVersion();
123
- if (typeof partialConfig.babelrcPath === 'string') {
124
- addIncludedFile(partialConfig.babelrcPath);
125
- }
126
- if (typeof partialConfig.configPath === 'string') {
127
- addIncludedFile(partialConfig.configPath);
128
- }
129
- }
130
- } else {
131
- for (let file of partialConfig.files) {
132
- addIncludedFile(file);
133
- }
134
- }
135
- if (partialConfig.fileHandling != null && partialConfig.fileHandling !== 'transpile') {} else if (partialConfig.hasFilesystemConfig()) {
136
- // Determine what syntax plugins we need to enable
137
- let syntaxPlugins = [];
138
- if (TYPESCRIPT_EXTNAME_RE.test(config.searchPath)) {
139
- syntaxPlugins.push('typescript');
140
- if (config.searchPath.endsWith('.tsx')) {
141
- syntaxPlugins.push('jsx');
142
- }
143
- } else if (await (0, _jsx.default)(options, config)) {
144
- syntaxPlugins.push('jsx');
145
- }
146
-
147
- // If the config has plugins loaded with require(), or inline plugins in the config,
148
- // we can't cache the result of the compilation because we don't know where they came from.
149
- if (hasRequire(partialConfig.options)) {
150
- logger.warn({
151
- 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.'
152
- });
153
- config.setCacheKey(JSON.stringify(Date.now()));
154
- config.invalidateOnStartup();
155
- } else {
156
- await warnOnRedundantPlugins(options.inputFS, partialConfig, logger);
157
- definePluginDependencies(config, partialConfig.options, options);
158
- config.setCacheKey((0, _utils().hashObject)(partialConfig.options));
159
- }
160
- return {
161
- internal: false,
162
- config: partialConfig.options,
163
- targets: (0, _utils2.enginesToBabelTargets)(config.env),
164
- syntaxPlugins
165
- };
166
- } else {
167
- return buildDefaultBabelConfig(options, config);
168
- }
169
- }
170
- async function buildDefaultBabelConfig(options, config) {
171
- // If this is a .ts or .tsx file, we don't need to enable flow.
172
- if (TYPESCRIPT_EXTNAME_RE.test(config.searchPath)) {
173
- return;
174
- }
175
-
176
- // Detect flow. If not enabled, babel doesn't need to run at all.
177
- let babelOptions = await (0, _flow.default)(config, options);
178
- if (babelOptions == null) {
179
- return;
180
- }
181
-
182
- // When flow is enabled, we may also need to enable JSX so it parses properly.
183
- let syntaxPlugins = [];
184
- if (await (0, _jsx.default)(options, config)) {
185
- syntaxPlugins.push('jsx');
186
- }
187
- definePluginDependencies(config, babelOptions, options);
188
- return {
189
- internal: true,
190
- config: babelOptions,
191
- syntaxPlugins
192
- };
193
- }
194
- function hasRequire(options) {
195
- let configItems = [...options.presets, ...options.plugins];
196
- return configItems.some(item => !item.file);
197
- }
198
- function definePluginDependencies(config, babelConfig, options) {
199
- if (babelConfig == null) {
200
- return;
201
- }
202
- let configItems = [...(babelConfig.presets || []), ...(babelConfig.plugins || [])];
203
- for (let configItem of configItems) {
204
- // FIXME: this uses a relative path from the project root rather than resolving
205
- // from the config location because configItem.file.request can be a shorthand
206
- // rather than a full package name.
207
- config.addDevDependency({
208
- specifier: (0, _utils().relativePath)(options.projectRoot, configItem.file.resolved),
209
- resolveFrom: _path().default.join(options.projectRoot, 'index'),
210
- // Also invalidate @babel/core when the plugin or a dependency updates.
211
- // This ensures that the caches in @babel/core are also invalidated.
212
- additionalInvalidations: [{
213
- specifier: '@babel/core',
214
- resolveFrom: config.searchPath,
215
- range: _constants.BABEL_CORE_RANGE
216
- }]
217
- });
218
- }
219
- }
220
- const redundantPresets = new Set(['@babel/preset-env', '@babel/preset-react', '@babel/preset-typescript', '@parcel/babel-preset-env']);
221
- async function warnOnRedundantPlugins(fs, babelConfig, logger) {
222
- if (babelConfig == null) {
223
- return;
224
- }
225
- let configPath = babelConfig.config ?? babelConfig.babelrc;
226
- if (!configPath) {
227
- return;
228
- }
229
- let presets = babelConfig.options.presets || [];
230
- let plugins = babelConfig.options.plugins || [];
231
- let foundRedundantPresets = new Set();
232
- let filteredPresets = presets.filter(preset => {
233
- if (redundantPresets.has(preset.file.request)) {
234
- foundRedundantPresets.add(preset.file.request);
235
- return false;
236
- }
237
- return true;
238
- });
239
- let filePath = _path().default.relative(process.cwd(), configPath);
240
- let diagnostics = [];
241
- if (filteredPresets.length === 0 && foundRedundantPresets.size > 0 && plugins.length === 0) {
242
- diagnostics.push({
243
- message: (0, _diagnostic().md)`Parcel includes transpilation by default. Babel config __${filePath}__ contains only redundant presets. Deleting it may significantly improve build performance.`,
244
- codeFrames: [{
245
- filePath: configPath,
246
- codeHighlights: await getCodeHighlights(fs, configPath, foundRedundantPresets)
247
- }],
248
- hints: [(0, _diagnostic().md)`Delete __${filePath}__`],
249
- documentationURL: 'https://parceljs.org/languages/javascript/#default-presets'
250
- });
251
- } else if (foundRedundantPresets.size > 0) {
252
- diagnostics.push({
253
- 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.`,
254
- codeFrames: [{
255
- filePath: configPath,
256
- codeHighlights: await getCodeHighlights(fs, configPath, foundRedundantPresets)
257
- }],
258
- hints: [(0, _diagnostic().md)`Remove the above presets from __${filePath}__`],
259
- documentationURL: 'https://parceljs.org/languages/javascript/#default-presets'
260
- });
261
- }
262
- if (foundRedundantPresets.has('@babel/preset-env')) {
263
- diagnostics.push({
264
- message: "@babel/preset-env does not support Parcel's targets, which will likely result in unnecessary transpilation and larger bundle sizes.",
265
- codeFrames: [{
266
- filePath: babelConfig.config ?? babelConfig.babelrc,
267
- codeHighlights: await getCodeHighlights(fs, babelConfig.config ?? babelConfig.babelrc, new Set(['@babel/preset-env']))
268
- }],
269
- hints: [`Either remove __@babel/preset-env__ to use Parcel's builtin transpilation, or replace with __@parcel/babel-preset-env__`],
270
- documentationURL: 'https://parceljs.org/languages/javascript/#custom-plugins'
271
- });
272
- }
273
- if (diagnostics.length > 0) {
274
- logger.warn(diagnostics);
275
- }
276
- }
277
- async function getCodeHighlights(fs, filePath, redundantPresets) {
278
- let ext = _path().default.extname(filePath);
279
- if (ext !== '.js' && ext !== '.cjs' && ext !== '.mjs') {
280
- let contents = await fs.readFile(filePath, 'utf8');
281
- let json = _json().default.parse(contents);
282
- let presets = json.presets || [];
283
- let pointers = [];
284
- for (let i = 0; i < presets.length; i++) {
285
- if (Array.isArray(presets[i]) && redundantPresets.has(presets[i][0])) {
286
- pointers.push({
287
- type: 'value',
288
- key: `/presets/${i}/0`
289
- });
290
- } else if (redundantPresets.has(presets[i])) {
291
- pointers.push({
292
- type: 'value',
293
- key: `/presets/${i}`
294
- });
295
- }
296
- }
297
- if (pointers.length > 0) {
298
- return (0, _diagnostic().generateJSONCodeHighlights)(contents, pointers);
299
- }
300
- }
301
- return [{
302
- start: {
303
- line: 1,
304
- column: 1
305
- },
306
- end: {
307
- line: 1,
308
- column: 1
309
- }
310
- }];
311
- }
package/lib/constants.js DELETED
@@ -1,7 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.BABEL_CORE_RANGE = void 0;
7
- const BABEL_CORE_RANGE = exports.BABEL_CORE_RANGE = '^7.12.0';
package/lib/flow.js DELETED
@@ -1,52 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = getFlowOptions;
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(e) { return e && e.__esModule ? e : { default: e }; }
16
- /**
17
- * Generates a babel config for stripping away Flow types.
18
- */
19
- async function getFlowOptions(config, options) {
20
- if (!config.isSource) {
21
- return null;
22
- }
23
-
24
- // Only add flow plugin if `flow-bin` is listed as a dependency in the root package.json
25
- // @parcel/error-overlay package in integration tests is an exception
26
-
27
- {
28
- let conf = await config.getConfigFrom(options.projectRoot + '/index', ['package.json']);
29
- let pkg = conf === null || conf === void 0 ? void 0 : conf.contents;
30
- if (!pkg || !(pkg.dependencies && pkg.dependencies['flow-bin']) && !(pkg.devDependencies && pkg.devDependencies['flow-bin'])) {
31
- return null;
32
- }
33
- }
34
- const babelCore = await options.packageManager.require('@babel/core', config.searchPath, {
35
- range: _constants.BABEL_CORE_RANGE,
36
- saveDev: true,
37
- shouldAutoInstall: options.shouldAutoInstall
38
- });
39
- await options.packageManager.require('@babel/plugin-transform-flow-strip-types', config.searchPath, {
40
- range: '^7.0.0',
41
- saveDev: true,
42
- shouldAutoInstall: options.shouldAutoInstall
43
- });
44
- return {
45
- plugins: [babelCore.createConfigItem(['@babel/plugin-transform-flow-strip-types', {
46
- requireDirective: true
47
- }], {
48
- type: 'plugin',
49
- dirname: _path().default.dirname(config.searchPath)
50
- })]
51
- };
52
- }
package/lib/jsx.js DELETED
@@ -1,37 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = isJSX;
7
- function _path() {
8
- const data = _interopRequireDefault(require("path"));
9
- _path = function () {
10
- return data;
11
- };
12
- return data;
13
- }
14
- function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
15
- const JSX_EXTENSIONS = new Set(['.jsx', '.tsx']);
16
- const JSX_LIBRARIES = ['react', 'preact', 'nervejs', 'hyperapp'];
17
-
18
- /**
19
- * Returns whether an asset is likely JSX. Attempts to detect react or react-like libraries
20
- * along with
21
- */
22
- async function isJSX(options, config) {
23
- if (!config.isSource) {
24
- return false;
25
- }
26
- if (JSX_EXTENSIONS.has(_path().default.extname(config.searchPath))) {
27
- return true;
28
- }
29
- let pkg = await config.getPackage();
30
- if (pkg !== null && pkg !== void 0 && pkg.alias && pkg.alias['react']) {
31
- // e.g.: `{ alias: { "react": "preact/compat" } }`
32
- return true;
33
- } else {
34
- // Find a dependency that implies JSX syntax.
35
- return JSX_LIBRARIES.some(libName => pkg && (pkg.dependencies && pkg.dependencies[libName] || pkg.devDependencies && pkg.devDependencies[libName] || pkg.peerDependencies && pkg.peerDependencies[libName]));
36
- }
37
- }
@@ -1,55 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.remapAstLocations = remapAstLocations;
7
- function remapAstLocations(t, ast, map) {
8
- // remap ast to original mappings
9
- // This improves sourcemap accuracy and fixes sourcemaps when scope-hoisting
10
- traverseAll(t, ast.program, node => {
11
- if (node.loc) {
12
- var _node$loc;
13
- if ((_node$loc = node.loc) !== null && _node$loc !== void 0 && _node$loc.start) {
14
- let mapping = map.findClosestMapping(node.loc.start.line, node.loc.start.column);
15
- if (mapping !== null && mapping !== void 0 && mapping.original) {
16
- // $FlowFixMe
17
- node.loc.start.line = mapping.original.line;
18
- // $FlowFixMe
19
- node.loc.start.column = mapping.original.column;
20
-
21
- // $FlowFixMe
22
- let length = node.loc.end.column - node.loc.start.column;
23
-
24
- // $FlowFixMe
25
- node.loc.end.line = mapping.original.line;
26
- // $FlowFixMe
27
- node.loc.end.column = mapping.original.column + length;
28
-
29
- // $FlowFixMe
30
- node.loc.filename = mapping.source;
31
- } else {
32
- // Maintain null mappings?
33
- node.loc = null;
34
- }
35
- }
36
- }
37
- });
38
- }
39
- function traverseAll(t, node, visitor) {
40
- if (!node) {
41
- return;
42
- }
43
- visitor(node);
44
- for (let key of t.VISITOR_KEYS[node.type] || []) {
45
- // $FlowFixMe
46
- let subNode = node[key];
47
- if (Array.isArray(subNode)) {
48
- for (let i = 0; i < subNode.length; i++) {
49
- traverseAll(t, subNode[i], visitor);
50
- }
51
- } else {
52
- traverseAll(t, subNode, visitor);
53
- }
54
- }
55
- }
package/lib/types.js DELETED
@@ -1 +0,0 @@
1
- "use strict";
package/lib/utils.js DELETED
@@ -1,75 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.enginesToBabelTargets = enginesToBabelTargets;
7
- function _assert() {
8
- const data = _interopRequireDefault(require("assert"));
9
- _assert = function () {
10
- return data;
11
- };
12
- return data;
13
- }
14
- function _semver() {
15
- const data = _interopRequireDefault(require("semver"));
16
- _semver = function () {
17
- return data;
18
- };
19
- return data;
20
- }
21
- function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
22
- // Copied from @babel/helper-compilation-targets/lib/options.js
23
- const TargetNames = {
24
- node: 'node',
25
- chrome: 'chrome',
26
- opera: 'opera',
27
- edge: 'edge',
28
- firefox: 'firefox',
29
- safari: 'safari',
30
- ie: 'ie',
31
- ios: 'ios',
32
- android: 'android',
33
- electron: 'electron',
34
- samsung: 'samsung',
35
- rhino: 'rhino'
36
- };
37
-
38
- // List of browsers to exclude when the esmodule target is specified.
39
- // Based on https://caniuse.com/#feat=es6-module
40
- 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'];
41
- function enginesToBabelTargets(env) {
42
- // "Targets" is the name @babel/preset-env uses for what Parcel calls engines.
43
- // This should not be confused with Parcel's own targets.
44
- // Unlike Parcel's engines, @babel/preset-env expects to work with minimum
45
- // versions, not semver ranges, of its targets.
46
- let targets = {};
47
- for (let engineName of Object.keys(env.engines)) {
48
- let engineValue = env.engines[engineName];
49
-
50
- // if the engineValue is a string, it might be a semver range. Use the minimum
51
- // possible version instead.
52
- if (engineName === 'browsers') {
53
- targets[engineName] = engineValue;
54
- } else {
55
- var _semver$minVersion;
56
- (0, _assert().default)(typeof engineValue === 'string');
57
- if (!TargetNames.hasOwnProperty(engineName)) continue;
58
- let minVersion = (_semver$minVersion = _semver().default.minVersion(engineValue)) === null || _semver$minVersion === void 0 ? void 0 : _semver$minVersion.toString();
59
- targets[engineName] = minVersion ?? engineValue;
60
- }
61
- }
62
- if (env.outputFormat === 'esmodule' && env.isBrowser()) {
63
- // If there is already a browsers target, add a blacklist to exclude
64
- // instead of using babel's esmodules target. This allows specifying
65
- // a newer set of browsers than the baseline esmodule support list.
66
- // See https://github.com/babel/babel/issues/8809.
67
- if (targets.browsers) {
68
- let browsers = Array.isArray(targets.browsers) ? targets.browsers : [targets.browsers];
69
- targets.browsers = [...browsers, ...ESMODULE_BROWSERS];
70
- } else {
71
- targets.esmodules = true;
72
- }
73
- }
74
- return targets;
75
- }
@@ -1,103 +0,0 @@
1
- // @flow strict-local
2
-
3
- import {babelErrorEnhancer} from './babelErrorUtils';
4
- import {Transformer} from '@parcel/plugin';
5
- import {relativeUrl} from '@parcel/utils';
6
- import SourceMap from '@parcel/source-map';
7
- import semver from 'semver';
8
- import babel7 from './babel7';
9
- import {load} from './config';
10
-
11
- export default (new Transformer({
12
- loadConfig({config, options, logger}) {
13
- return load(config, options, logger);
14
- },
15
-
16
- canReuseAST({ast}) {
17
- return ast.type === 'babel' && semver.satisfies(ast.version, '^7.0.0');
18
- },
19
-
20
- async transform({asset, config, logger, options, tracer}) {
21
- try {
22
- if (config?.config) {
23
- if (
24
- asset.meta.babelPlugins != null &&
25
- Array.isArray(asset.meta.babelPlugins)
26
- ) {
27
- await babel7({
28
- asset,
29
- options,
30
- logger,
31
- babelOptions: config,
32
- additionalPlugins: asset.meta.babelPlugins,
33
- tracer,
34
- });
35
- } else {
36
- await babel7({
37
- asset,
38
- options,
39
- logger,
40
- babelOptions: config,
41
- tracer,
42
- });
43
- }
44
- }
45
-
46
- return [asset];
47
- } catch (e) {
48
- throw await babelErrorEnhancer(e, asset);
49
- }
50
- },
51
-
52
- async generate({asset, ast, options}) {
53
- let originalSourceMap = await asset.getMap();
54
- let sourceFileName: string = relativeUrl(
55
- options.projectRoot,
56
- asset.filePath,
57
- );
58
-
59
- const babelCorePath = await options.packageManager.resolve(
60
- '@babel/core',
61
- asset.filePath,
62
- {
63
- range: '^7.12.0',
64
- saveDev: true,
65
- shouldAutoInstall: options.shouldAutoInstall,
66
- },
67
- );
68
-
69
- const {default: generate} = await options.packageManager.require(
70
- '@babel/generator',
71
- babelCorePath.resolved,
72
- );
73
-
74
- let {code, rawMappings} = generate(ast.program, {
75
- sourceFileName,
76
- sourceMaps: !!asset.env.sourceMap,
77
- comments: true,
78
- importAttributesKeyword: 'with',
79
- });
80
-
81
- let map = new SourceMap(options.projectRoot);
82
- if (rawMappings) {
83
- map.addIndexedMappings(rawMappings);
84
- }
85
-
86
- if (originalSourceMap) {
87
- // The babel AST already contains the correct mappings, but not the source contents.
88
- // We need to copy over the source contents from the original map.
89
- let sourcesContent = originalSourceMap.getSourcesContentMap();
90
- for (let filePath in sourcesContent) {
91
- let content = sourcesContent[filePath];
92
- if (content != null) {
93
- map.setSourceContent(filePath, content);
94
- }
95
- }
96
- }
97
-
98
- return {
99
- content: code,
100
- map,
101
- };
102
- },
103
- }): Transformer);