Compare commits

...

234 Commits

Author SHA1 Message Date
Henry Zhu
a6df92f245 v7.0.0-beta.44 2018-04-02 18:19:30 -04:00
Logan Smyth
f4b81ab101 Merge pull request #7655 from babel/babel-env-make
Remove setting BABEL_ENV to test by default in makefile
2018-04-02 13:57:47 -07:00
Brian Ng
360b632881 Remove setting BABEL_ENV to test by default in makefile 2018-04-02 15:18:50 -05:00
Henry Zhu
bdfeeb38c6 v7.0.0-beta.43 2018-04-02 12:47:55 -04:00
Henry Zhu
47ada5ab3a revert prev pr to temp fix osx (#7652) 2018-04-02 12:40:03 -04:00
John-David Dalton
59ba3959dc Add options.allowAwaitOutsideFunction. (#7637) 2018-03-29 10:41:14 -04:00
unconfident
0200e6256a Allow StringLiteral to be used as ObjectTypeProperty.key (#7639) 2018-03-28 09:20:46 -05:00
Henry Zhu
9a26c2b07a Merge pull request #7471 from yakotika/master
added support Node's --require and -r flags in babel-node
2018-03-27 14:44:35 -04:00
Henry Zhu
901571d72f Merge pull request #7579 from devenbansod/migrate-to-jest-expect-2
Migrate a few packages' tests to use Jest Expect (see below)
2018-03-27 14:43:44 -04:00
Deven Bansod
b09c729675 Use expect's instanceOf and toHaveProperty methods 2018-03-27 22:34:25 +05:30
Sven SAULEAU
a36525be45 Merge pull request #7615 from babel/fix-clean-makefile
clean makefile a bit
2018-03-27 08:36:16 +02:00
Logan Smyth
a10c91790f Merge pull request #7588 from loganfsmyth/register-cycle-fixes
Have @babel/core lazy-load all dependencies and make @babel/register not explode because of that
2018-03-25 15:24:00 -07:00
Justin Ridgewell
ab7d1231ad Fix flow errors with Logical Assignment Operators (#7629)
* Fix flow errors with logical assignment

* Fix column numbers
2018-03-25 22:47:48 +01:00
Logan Smyth
a5df709bc3 Lazy-load @babel/core's dependencies to decrease up-front load times. 2018-03-25 14:22:32 -07:00
Logan Smyth
1dbed5f458 Have @babel/register explicitly skip re-entrant plugins/presets. 2018-03-25 14:22:32 -07:00
Logan Smyth
40e38646e4 Include stdout in error messages to aid debugging. 2018-03-25 12:50:35 -07:00
Logan Smyth
9e4dd861ee Ensure that sourceMapSupport is installed in all branches. 2018-03-25 12:50:35 -07:00
Justin Ridgewell
a7bddc02ba Add ??= to Logical Assignment Operators (#7623)
`??=` is being merged into the Logical Assignment Operator proposal, and the overall proposal will wait until nullish coalescing is finalized.
2018-03-25 18:58:51 +01:00
Justin Ridgewell
023f8bd1cb Move Logical Assignment Ops to Stage 1 (#7625) 2018-03-25 17:49:21 +01:00
Deven Bansod
c9b99af5a6 Remove assert.* from commented out assertions 2018-03-24 16:22:20 +05:30
Deven Bansod
c8d82d6483 Migrate all remaining fixtures to jest expect 2018-03-24 16:22:20 +05:30
Deven Bansod
db42a5d70f Migrate babel-preset-es2015 and -next-target tests to use jest expect 2018-03-24 16:22:19 +05:30
Deven Bansod
0856f89882 Migrate -transform-block-scoping and -transform-classes to jest expect 2018-03-24 16:22:18 +05:30
Deven Bansod
921702ef8c Migrate babel-plugin-proposal-do-expressions tests to jest-expect 2018-03-24 16:22:18 +05:30
Deven Bansod
8b57a3e3b9 Migrate a few packages' tests to use Jest Expect (see below)
* Migrate the following packages' tests:
    * babel-helper-annotate-as-pure
    * babel-helper-module-imports
    * babel-helper-transform-fixture-test-runner
    * babel-highlight
    * babel-node
    * babel-plugin-transform-modules-commonjs
    * babel-preset-env-standalone
    * babel-preset-env
    * babel-preset-es2015
    * babel-preset-react
    * babel-standalone
    * babel-template
    * babel-traverse
    * babel-types
2018-03-24 16:22:10 +05:30
Logan Smyth
21309cc8d4 Make these tests re-throw the same error to keep the trace. 2018-03-23 21:26:50 -07:00
Andy
19708e0154 TypeScript: support mapped type modifiers syntax (#7383) 2018-03-23 14:34:15 -04:00
Mateusz Burzyński
f98dff9189 Allow placeholders in JSXElements when parsing templates (#7583) 2018-03-23 09:27:51 +01:00
Brian Ng
840ba187a7 Prevent duplicate regex flags (#7617) 2018-03-22 10:25:26 -05:00
Sven SAULEAU
de00d939f0 fix: clean makefile 2018-03-22 10:29:25 +01:00
Brian Ng
e80488f1d5 Update to beta.42 (#7609) 2018-03-21 10:39:46 -05:00
Michał Pierzchała
81c1b49f6a Disable flow on transformClass, fix preset-env errors (#7605) 2018-03-20 18:42:11 -05:00
Justin Ridgewell
55bf55398a Logical Assignment: ensure computed key isn't recomputed (#7604)
* Logical Assignment: ensure computed key isn't recomputed

* More tests
2018-03-20 23:06:09 +00:00
Daniel Tschinder
f0d681a238 Remove obsolete max-len eslint rule and reformat some stuff to fit (#7602) 2018-03-20 08:51:47 -05:00
Logan Smyth
6d6fe844fd Centralize Babel's own compilation config to make it easier to follow. (#7599) 2018-03-19 21:49:17 -07:00
Logan Smyth
edb0a70e14 Run prettier to format all JSON. 2018-03-19 18:26:55 -07:00
Brian Ng
669f6b97b2 Tweak es2015-related plugin order in preset-env (#7586) 2018-03-19 14:19:42 -05:00
Michał Pierzchała
e2c5f25e97 Refactored quirky inheritance in babel-plugin-transform-classes (#7444)
* chore(plugin-transform-classes): refactor inheritance

* path some flow types

* remove unused export

* get rid of class

* temporarily rename to vanilla for diff readability

* more setState with minor adjustments

* rename 'private' methods

* explicit null check

* adjust import ordering

* Rename createConstructor -> maybeCreateConstructor

* Rename vanilla.js -> transformClass.js
2018-03-19 16:37:59 +01:00
Amin Marashi
8eee435cd6 Add RegExp support to include/exclude preset-env options (#7242)
* Add support for RegExp includes/excludes

* Keep the plugin order

* Detect invalid modules in regexp

* Add more tests for regexp

* Cover builtins, and unnormalized in the RegExp tests

* Remove babel-plugin- in all positions

* Change babel-plugin- prefix to string

* Add a test for the same module in include/exclude

* Handle partial matches explicitly

* Remove extra valid regexp check

* Optimise validation of plugins

* Optimise selecting the plugins

* Fix undefined include/exclude option

* Update documentation to reflect the new include matching

* Fix typo

* Apply reviews

Use regexp.test instead of string.match (slower)

Define flatten helper

Do not normalize babel-plugin anywhere in the string
2018-03-18 15:54:43 +01:00
Henry Zhu
d260bfaec4 v7.0.0-beta.42 2018-03-15 16:50:03 -04:00
Logan Smyth
c662c2ada2 Use strict namespace behavior for mjs files. (#7545) 2018-03-15 13:27:01 -07:00
Ben Wiley
b6e54800b4 Remove outdated spec deviation note [skip ci] (#7571)
`JSXText` was added to the JSX spec [here](https://github.com/facebook/jsx/pull/80).
2018-03-15 16:20:14 -04:00
Henry Zhu
ae210a46d1 Merge pull request #7562 from babel/pr/7534
Use helper-module-import inside preset-env
2018-03-15 16:19:03 -04:00
Logan Smyth
017d0e7078 Ensure that the backward-compat logic for plugin-utils copies over the version API properly. (#7580) 2018-03-15 11:45:53 -07:00
Josh Justice
b8d1d221f8 Rename actual/expected test files to input/output (#7578)
These files appear to have been missed in the update of test file naming from actual/expected.js to input/output.js. As a result, they were silently not being run. I've confirmed that they were not running, updated the names, then confirmed that they are running now.
2018-03-15 19:02:41 +01:00
Brian Ng
fed530f6bf Use helper-module-import inside entry plugin too 2018-03-15 09:21:20 -05:00
Gaël Gillard
29d44193cd Use helper-module-imports instead of custom import (#7457) 2018-03-15 09:21:19 -05:00
Melvin Groenhoff
82994ce087 Fix "Module build failed: Error: Cannot find module '@babel/types'" (#7575)
* @babel/template and @babel/types are dependencies instead of devDependencies (fixes #7573).

* Use @babel/types and @babel/template via @babel/core
2018-03-15 14:45:26 +01:00
Mateusz Burzyński
586d3b5929 Wrap wrapNativeSuper helpers in redefining functions for better tree-shakeability (#7188) 2018-03-14 23:48:33 +01:00
Mateusz Burzyński
d682e32529 Favour extends helper over objectWithoutProperties when whole object gets copied anyway (#7390) 2018-03-14 22:59:02 +01:00
Simon Kjellberg
07ab02f6b2 Fix incorrect value of _cache in _wrapNativeSuper (#7570)
The boolean expressions returns false in environments where Map is missing.
This change explicitly sets _cache to undefined in such cases, to ensure the cache methods will be ignored.
2018-03-14 16:37:51 -04:00
Nicolò Ribaudo
91a114f74a [transform-classes] Fix typo in _wrapNativeSuper helper 2018-03-14 19:23:10 +01:00
Nicolò Ribaudo
6d9887fc0f [typeof-symbol] Guard against undefined built-in globals 2018-03-14 19:23:10 +01:00
Henry Zhu
d2a3a8151e update to beta.41 (#7568) 2018-03-14 12:40:59 -05:00
Henry Zhu
270ea17fed v7.0.0-beta.41 2018-03-14 12:25:26 -04:00
Daniel Tschinder
da2aea31f5 Fix —require 2018-03-14 13:26:07 +01:00
Daniel Tschinder
1d69cd41ca Fix import of type ConfigItem (#7561)
It is also exported as type
2018-03-13 13:31:32 -05:00
Daniel Tschinder
a7ec312cfe Run node 9 on circleci and remove from travis (#7560) 2018-03-13 09:53:37 -04:00
Sven SAULEAU
6ff91cfdae docs: [skip ci] fix proposal link text 2018-03-13 13:21:34 +01:00
Yael Hermon
dfb3795a97 update preset-env after build-data (#7543) 2018-03-12 20:49:52 -05:00
Logan Smyth
353d3199c2 Re-add TEST_ONLY and use Jest's -t for TEST_GREP. (#7556) 2018-03-12 15:12:39 -07:00
Haroen Viaene
bdd70c37e0 docs(babel-standalone): remove bower mention (#6588)
* docs(babel-standalone): remove bower mention

Since the package won't be downloadable as `@babel/standalone` it's best to just remove it, since it's pretty much deprecated as is. I left the other mention of babel-standalone-bower since I guess that's just the name and still useful in other cases

cc @daniel15 

reported in https://github.com/babel/babel/pull/6495#pullrequestreview-70980926

* Update README.md
2018-03-12 19:10:24 +01:00
Daniel Tschinder
9d2d499760 Replace lodash/map with array equivalent (#7550)
* Replace lodash/map with array equivalent

* Fix review comments
2018-03-12 11:03:03 +01:00
Yael Hermon
29807837bb preset-env - add Symbol.asyncIterator to shippedProposals builtIns (#7548)
* preset-env - add Symbol.asyncIterator to shippedProposals builtins

* fix typo
2018-03-11 16:29:22 -05:00
ngohoangthang
c14a6a7735 Fix "ran" to "run" for monorepo.md (#7547) [skip ci] 2018-03-11 13:12:34 +01:00
Daniel Tschinder
3a7881379a jest: ToEqual -> toBe 2018-03-10 11:48:09 +01:00
Deven Bansod
f3f0197890 Migrate babel-core tests to use jest-expect (#7513)
* Used codemods at: https://gist.github.com/devenbansod/03c5cff857661e076cbec72fcb2e7eb3 along with some manual intervention and review
2018-03-10 11:40:28 +01:00
Logan Smyth
8e030e28b3 Merge pull request #7538 from loganfsmyth/unambiguous-import-meta
Make 'sourceType:unambiguous' use 'module' when import.meta is used.
2018-03-09 15:00:13 -08:00
Logan Smyth
3c8e9acd4a Make the unambiguous grammar select module when import.meta is used. 2018-03-09 14:44:06 -08:00
Logan Smyth
958551fd89 Refactor unambiguous to track state during parsing. 2018-03-09 14:35:55 -08:00
Logan Smyth
b5e6536f26 Remove the sourceMapTarget option from core and implement it in babel-cli. (#7500) 2018-03-09 14:14:25 -08:00
Will Monk
0389035e15 Add exact Param To ObjectTypeAnnotations (#7535) 2018-03-09 19:22:01 +01:00
Brian Ng
4f4dd3d4a6 Assign another temp var when parsing assignment patterns in destructuring (#7333) 2018-03-09 09:39:25 +01:00
Logan Smyth
4da3f3bc64 Update helpers from #7491. (#7532) 2018-03-08 17:06:43 -08:00
Logan Smyth
7901e7d1b9 Fix flowtype errors introduced in #7503. (#7531) 2018-03-08 16:02:28 -08:00
Logan Smyth
4b6c7ac0f6 Run build-no-bundle in the watcher to get right files. (#7530) 2018-03-08 13:48:32 -08:00
Daniel Tschinder
24a07fc790 Use jest workers on travis-ci and circleCI (#7510) 2018-03-08 22:15:54 +01:00
Logan Smyth
1c9b0ff49e Merge pull request #7491 from loganfsmyth/require-array-rest-spread-iterable
Explicitly throw if the array rest/spread items are not iterable.
2018-03-08 12:39:53 -08:00
Logan Smyth
828e9a8538 Skip minification of large bundles during CI builds. (#7528) 2018-03-08 12:36:47 -08:00
Brian Ng
f97d4313c9 Update test262 test script and a few keyword escape fixes (#7503)
* Update test262 and whitelist

* Use test262-stream

* Check escapes in contextual keywords

* Check escapes when parsing new.target

* Check escapes for getters/setters

* Check escapes for static class methods

* Check escapes on async arrow and functions
2018-03-08 09:10:00 -06:00
Brian Ng
2a0071028d Add Number.parseFloat/parseInt mappins for preset-env 'usage' (#7421) 2018-03-08 09:08:43 -06:00
Sven SAULEAU
2c0d492674 Merge pull request #7515 from abouthiroppy/feature/modify-readme-of-babel-plugin-transform-block-scoped-functions
Update README.md and add test
2018-03-08 12:06:58 +01:00
Logan Smyth
e42cbb40a4 Merge pull request #7472 from loganfsmyth/expose-partial-config
Expose the partial Babel config for callers to load and mutate.
2018-03-07 18:23:27 -08:00
Logan Smyth
74ab2798e2 Tweaks around PR comments. 2018-03-07 18:02:38 -08:00
Logan Smyth
fef5c7e523 Expose the partial Babel config for people to load and mutate. 2018-03-07 16:33:25 -08:00
Logan Smyth
53825f8152 Show a more useful diff when comparing fixture files. (#7520) 2018-03-07 12:27:10 -08:00
Rory O’Kane
40819f112c Fix link to proposal in do expressions plugin README (#7519)
The old link, http://wiki.ecmascript.org/doku.php?id=strawman:do_expressions, fails to load for me.

[skip ci]
2018-03-07 15:01:39 -05:00
Yuta Hiroto
2d36549541 Update README.md and add test 2018-03-07 23:49:56 +09:00
Brian Ng
7e423de911 Restore passing SIGINT signals to spawned child processes (#7511) 2018-03-07 14:10:11 +01:00
Abu Shamsutdinov
8317f8ab14 added support Node's --require and -r flags in babel-node 2018-03-07 12:38:57 +03:00
Daniel Tschinder
65dcc4eabe Fix makefile indentation 2018-03-06 11:57:26 +01:00
Daniel Tschinder
c8992e4155 Enforce Prettier defaults + also format .babelrc and .json (#7499)
* .prettierrc: full configuration for Prettier

This way, contributors using different-from-default settings will still
use the correct prettier settings

* Makefile: also lint .babelrc.js

* Makefile: also prettify .json files

* Exclude package.json files and correct build dir

* Add more default options to prettierrc and load it in cli

This avoids prettier looking up the config for each file

* Format json

* Update prettier and eslint and reformat codebase

* Remove obsolete file

* Add comment
2018-03-06 11:40:36 +01:00
Raja Sekar
50b9fbb570 empty src dir error fix - fixes #7375 2018-03-05 17:46:38 -08:00
Daniel Tschinder
5d615dd198 Disallow setters to have RestElement (#7498) 2018-03-05 18:03:59 -06:00
Daniel Tschinder
eb2a0b0fcd Raise minimum version for debug to only allow secure version. (#7495) 2018-03-05 20:12:56 +01:00
Logan Smyth
eaa31b6ec3 Explicitly throw if the rest/spread items are not iterable. 2018-03-05 09:32:40 -08:00
Logan Smyth
4d76d5dddc Refactor Babel's helpers into smaller functions. 2018-03-05 09:32:39 -08:00
Nicolò Ribaudo
a86d311986 Reuse the assertThisInitialized helper in possibleConstructorReturn (#7493) 2018-03-05 08:11:16 -08:00
Daniel Tschinder
a340a2614f Fix reseting modules in jest and config (#7494)
* Fix reseting modules in jest and config

we have lib folders inside the source folders which should not be ignored.

* Add codemods lib folder

* Support mjs

* improve ignore pattern
2018-03-05 16:04:29 +01:00
Daniel Tschinder
f9857ca6ba Docs: Use namespace packages in all links (#7496)
preset-env and babylon were still linking to spearate repos
2018-03-05 08:49:27 -06:00
Daniel Tschinder
f43bf7fcd5 Enable babel-register tests again (#7487) 2018-03-05 10:47:00 +01:00
Gvozd
653318b7e4 Always transform for-await in async functions. (#7446)
for-await was transformed in @babel/helper-remap-async-to-generator, which was
called by @babel/plugin-transform-async-to-generator and
@babel/plugin-proposal-async-generator-functions. This prevented for-await
statements in async functions to be transpiled if the
transform-async-to-generator plugin was't enabled.
2018-03-05 09:30:25 +01:00
K Sashi Kumar
d187c26748 Spec Violation: Fix var initializer in for-in loop (#7392) 2018-03-04 16:18:32 -08:00
Kevin Ji
fc64ab5725 eslint: Rename to .json, mark as root config - fixes #7433 2018-03-04 16:00:41 -08:00
Nicolò Ribaudo
5cd8b5b7f0 Add eslint plugin to disallow t.clone and t.cloneDeep (#7191)
* Add eslint plugin to disallow `t.clone` and `t.cloneDeep`

* Make it better and add flow

* Other cases

* Superpowers

* Fix
2018-03-04 15:47:11 -08:00
Nicolò Ribaudo
a328b6ad1a Arrow functions and methods' params are binding identifiers (#6770) 2018-03-04 15:19:48 -08:00
Logan Smyth
15a80f0df8 Merge pull request #7490 from loganfsmyth/sourcetype-helpful-errors
Give helpful errors if the wrong sourceType is detected
2018-03-04 15:03:49 -08:00
Logan Smyth
a4795408b4 Allow plugins to assert that a specific babel version has loaded the plugin. (#7450) 2018-03-04 14:36:54 -08:00
Logan Smyth
5f6e3122a0 Give users helpful feedback if they are detected as using the wrong sourceType. 2018-03-04 14:12:37 -08:00
Logan Smyth
7f8f4e86dc Merge pull request #7484 from loganfsmyth/test-input-mjs
Require tests to use input.mjs for modules, and output.js/.mjs based on active transforms
2018-03-04 14:06:07 -08:00
Logan Smyth
5c3092d86f Expand .raise() to allow more options. 2018-03-04 13:38:12 -08:00
Logan Smyth
7cc00cce0d Require output fixture extension to match sourceType output. 2018-03-04 13:31:33 -08:00
Logan Smyth
beb99dfda1 Rename test fixtures using module syntax to .mjs files. 2018-03-04 13:31:32 -08:00
Logan Smyth
5f9539e9cc Rework the testrunner to pass the input filename only. 2018-03-04 13:28:25 -08:00
Logan Smyth
aa669ef902 Fix an issue with new update-expression tests. 2018-03-04 13:25:31 -08:00
Marvin Hagemeister
c92e8be612 Generating correct assignments for live bindings updated with UpdateExpressions (#7489)
Fixes #7488
2018-03-04 20:46:33 +01:00
K Sashi Kumar
ab1e295c74 [Doc] Remove build-babylon from contributing (#7474) [skip ci] 2018-03-04 19:55:25 +01:00
K Sashi Kumar
ae0df86340 Remove broken check in checkFunctionNameAndParams (#7473) 2018-03-04 16:34:16 +01:00
Deven Bansod
41bf66bca2 Migrate babel-code-frame tests to use expect (#7485)
* Replace `assert.equal` calls with appropriate `expect` calls
* Work-in-progress: Currently targeting only `babel-code-frame` tests
2018-03-04 11:39:12 +01:00
Logan Smyth
212058148c Require users to pass a filename, or specify --no-babelrc when using CLI with stdin. (#7461) 2018-03-03 12:29:11 -08:00
Daniel Tschinder
785131d8e6 Also run coverage with node: current (#7479) 2018-03-03 18:45:34 +01:00
Mauro Bringolf
81532103da Contributing docs: Add caveat about direct subdirectories and exec tests (#7482) [skip Ci]
* Add caveat about direct subdirectories and exec tests

* Fix _only_ typo
2018-03-03 18:01:29 +01:00
Michał Pierzchała
cc6e739f15 Add a brief summary to CLI's build output (#7439)
* feat(babel-cli): add a brief summary to build output

* address feedback

* further adjustments

* Use quiet output as default, add --verbose

* fix tests

* remove verbose alias
2018-03-03 13:29:26 +01:00
Daniel Tschinder
3e95830646 Migrate to jest (#7455) 2018-03-03 10:58:19 +01:00
Orta
53208d6998 Another iteration on the TS plugin readme (#7469) 2018-03-02 22:39:18 -06:00
Orta
fdfbd9a6f7 Update README for Babel TypeScript Plugin (#7443) 2018-03-01 08:46:54 -06:00
Daniel Tschinder
007f8d19b3 Remove unused dependencies (#7454)
Replace util.promisify with node internal version
2018-02-28 10:59:28 -05:00
Daniel Tschinder
586ba35950 Update to circleci v2 (#7451) 2018-02-28 10:58:47 -05:00
Daniel Tschinder
1a454f666c Install peerDependencies and remove unused async dependency (#7453) 2018-02-28 10:58:33 -05:00
Logan Smyth
a07f96ce3f Merge pull request #7449 from loganfsmyth/env-enhancement
Centralize the plugin/preset and config APIs into one place
2018-02-28 01:03:35 -08:00
Logan Smyth
2c3eb3096f Expand the '.env()' API call with more flexibility. 2018-02-27 18:48:24 -08:00
Logan Smyth
148e6dfc26 Centralize the plugin/configuration API object. 2018-02-27 18:48:24 -08:00
Logan Smyth
ddd40bf5c7 Rely entirely on sourceType for module vs script differentiation. (#7417) 2018-02-27 18:11:13 -08:00
Logan Smyth
bf8b25289b Merge pull request #7436 from loganfsmyth/less-upfront-work
Default to `ast:false` and do less work when loading core
2018-02-27 18:03:53 -08:00
Logan Smyth
b19b7fd2cf Fix PR comments. 2018-02-27 17:46:17 -08:00
Guy Bedford
f004972625 Ensure babel-preset-env targets input object is not mutated (#7438) 2018-02-27 08:46:24 -06:00
Yuta Hiroto
5459c75d64 Fix CONTRIBUTING.md (#7441) 2018-02-27 08:45:28 -06:00
Logan Smyth
8e3e6e0a88 Require AST output to be opt-in, rather than opt-out. 2018-02-26 18:44:59 -08:00
Logan Smyth
d4a8c7672c Avoid using lodash during config loading, for require() performance. 2018-02-26 18:44:58 -08:00
Logan Smyth
600106b9cb Lazy-initialize external helper template. 2018-02-26 18:44:57 -08:00
Logan Smyth
dffcef785a Lazy-initialize helper templates. 2018-02-26 18:18:57 -08:00
Logan Smyth
cb4f4f4d5f Ensure that typechecking artifacts are built up front for watch. 2018-02-25 21:38:11 -08:00
Logan Smyth
7ff4a73916 Upgrade flow to 0.66 and fix a few minor errors. (#7431) 2018-02-25 19:22:23 -08:00
Brian Ng
8823e4247e Fix up flow errors (#7227)
* charcodes@0.1.0

* Add hasFlowComment to tokenizer/state

* Fix babel-types flow errors

* Add isIterator to tokenizer/state

* Remove unnecessary argument from flow/readToken

* Add annotation to tokenizer/isIterator

* Fix reference to generated index.js.flow

* Add workaround in babel-template expression formatter

* Fix tsEatThenParseType return type

* Fix inconsistency with ParseSubscript state

* Add workaround for flow handling error with tagged template in optional chain

* Add flow workaround in expectPlugin inside tokenizer
2018-02-25 18:12:33 -08:00
Andy
6f3be3a543 typescript: Support definite assignment assertion (#7159) 2018-02-24 16:26:07 -06:00
Andy
6f6c8dabba TypeScript: Support conditional types syntax (#7404)
Microsoft/TypeScript#21316 and Microsoft/TypeScript#21496
2018-02-24 14:56:14 +01:00
Alasdair McLeay
960fa66c9e Reinstate --inspect-brk, lost when making babel-node standalone (#7423) [skip ci] 2018-02-23 15:18:13 -05:00
Logan Smyth
df50cddd63 Replace instead of merging babel-register options, and resolve cwd up front (#7416)
Replace instead of merging babel-register options, and resolve cwd up front
2018-02-23 08:51:42 -08:00
Brian Ng
455c04e60a Bump compat-table and regen preset-env data (#7401) 2018-02-23 08:46:14 -06:00
Brian Ng
182fe7b04e Add missing promise polyfill deps for preset-env's useBuiltIns: usage (#7400) 2018-02-23 08:45:22 -06:00
Brian Ng
959865b48d Update babel to beta.40 (#7413) 2018-02-23 08:44:45 -06:00
Logan Smyth
62c1046249 Avoid re-traversing inserted references to the namespace binding. (#7418) 2018-02-22 23:54:29 -08:00
Henry Zhu
70627ac92c we can use emojis 😊[skip ci] 2018-02-22 22:01:02 -05:00
Logan Smyth
a99e9614a6 Resolve the babel-register working directory up front. 2018-02-22 18:48:36 -08:00
Logan Smyth
cfb830b5bd Overwrite instead of merging babel-register options. 2018-02-22 18:43:47 -08:00
Mike S
84de90e572 Better error message for invalid plugin/preset (#7238)
- Error for invalid plugin/preset now includes file path
2018-02-22 18:30:01 -08:00
Mateusz Burzyński
d283324f8a Mark hoisted react constant elements as #__PURE__ (#7372) 2018-02-21 18:58:56 +01:00
Brian Ng
d75a6b8468 Remove istanbul hacks (#7403) 2018-02-21 09:56:30 -06:00
Deepak Pai
dad05ed503 Solves Tagged template literal size optimization (#7379)
* Tagged template literal size optimization
solves #7352

* Incorporates review changes
2018-02-20 15:39:22 -05:00
Justin Ridgewell
7e90d56024 Proposal: Logical Assignment Operators (#7385)
* Proposal: Logical Assignment Operators

https://github.com/jridgewell/proposal-logical-assignment

I'm bringing it [back](https://github.com/babel/babel/pull/516). 😉

* Use expectPlugin

* Add to stage 0 preset

* Add logicalAssignment missing plugin log stuff
2018-02-18 13:56:29 -05:00
Nicolò Ribaudo
3d49766f6b Don't extract rest elements from nested expressions (#7364)
* Don't extract rest elements from nested expressions

* Node 4
2018-02-17 16:22:38 +01:00
Brian Ng
4d17a96d50 Minor object-rest-spread README tweaks [skip ci] 2018-02-16 20:56:21 -06:00
James Reggio
6cbc585cf4 Fix over-zealous traversal by object-rest-spread (#7388)
Prior to this change, we'd conduct an open-ended traversal on the 'id'
of any VariableDeclarator to find a RestElement. The 'id' of
a VariableDeclarator can contain an AssignmentPattern (to supply
a default value), and if the right-hand side of the AssignmentPattern
contained a RestElement, we'd transform it.

The problem here is that the right-hand side of an AssignmentPattern can
be *any* Expression. If the right-hand side is a function body, we'd
traverse the entire function body, and if a RestElement occurred
anywhere in that function body, we'd transform it and emit the
transformations wherever we began the traversal (at least one scope
outside its usage).

The fix is to stop the inner traversal if we encounter an
AssignmentPattern. The outer traversal will still visit the
AssignmentPattern, so RestElements within the right-hand side of an
AssignmentPattern will be properly transformed at that time.
2018-02-16 21:19:09 -05:00
Andrea Puddu
ee6dfd1580 Fix object spread according to spec (#7034) 2018-02-16 20:06:17 -05:00
Logan Smyth
e732ee0c5b Preserve import binding locations during module rewriting (#7378)
* Only wrap import references that need it.

* Preserve the import binding location for sourcemaps.

* Add tests.
2018-02-14 10:17:27 -08:00
Justin Falcone
128fc6864e Link generator readme to Babylon AST spec [skip ci] (#7380) 2018-02-14 11:40:39 -05:00
Raja Sekar
6aed8e944f updated node debugger usage command in test (#7376) [skip ci] 2018-02-13 11:17:19 -05:00
Mateusz Burzyński
4d164bd8e6 Added babel-helper-split-export-declaration (#7313) 2018-02-13 16:44:05 +01:00
Henry Zhu
ea3f2d9299 v7.0.0-beta.40 2018-02-12 11:41:13 -05:00
Vojtěch Štěpančík
88a0f52230 Fix CLI compilation callback calling (#7366) 2018-02-12 08:10:35 -05:00
Yeonghoon Park
4a2e1dbbc3 Fix stage-3 name in README.md (#7363)
[skip-ci] Fix a typo in preset-env doc: `@babel/preset-stage-3` package name.
2018-02-11 14:04:31 +02:00
Clar Roʒe
2979dd99ac Update browserslist for babel-preset-env. (#7365) 2018-02-11 09:57:50 +02:00
Suchipi Izumi
534ee4734c Extract @babel/highlight package from @babel/code-frame
This creates a new package called @babel/highlight which syntax highlights
JavaScript code for terminal output. This functionality was already
present in @babel/code-frame, but exposing it as a separate package lets
other projects leverage it. @babel/code-frame has been refactored
slightly so that it uses @babel/highlight to do its syntax highlighting.
2018-02-09 09:31:37 +01:00
Steven Hargrove
a01007a3d3 Allow falsey, yet valid options for codeFrameColumns() (#7341)
Allow for overriding default linesAbove/linesBelow values.
2018-02-08 16:52:12 -05:00
Logan Smyth
493996e02a Merge pull request #7345 from loganfsmyth/small-bug-fixes
Small tweaks to prep for coming .babelrc lookup work
2018-02-08 13:30:49 -08:00
Justin Ridgewell
c03a34e509 Typo in nullish-coalescing-operator README.md 2018-02-08 14:34:41 -05:00
Naveen jain
92580e750d Fixes issues regarding super in optionalChain (#7356) 2018-02-08 14:31:47 -05:00
Logan Smyth
213805f21e Avoid duplicating types in index-browser. 2018-02-08 09:19:16 -08:00
Logan Smyth
28d13cb09b Fix small bug in the new .parse function. 2018-02-08 00:22:50 -08:00
Logan Smyth
9a8ba76e1f Merge .babelrc and .babelignore searching into a single pass. 2018-02-08 00:22:49 -08:00
Logan Smyth
d88173b9f8 Ensure that tests don't leave mutated global state in the environment. 2018-02-08 00:22:49 -08:00
Logan Smyth
85174b6ce1 Remove unneeded param from buildRootConfig. 2018-02-07 23:23:19 -08:00
Logan Smyth
ec2e0b664a Properly allow undefined ignore patterns for test/include/exclude. 2018-02-07 23:23:19 -08:00
Naveen jain
a3ad518ce1 [BugFix] : OptionalChaining Bug fixes (#7288)
* Added optionalExpression types to babylon and babel-types

* OptionalChain transforms bug fix

* Added OptionalExpressions to babel-generator. Fixed OptionalChain Bugs

* Removed 'optionalChain' from newExpression and added test cases

* Added test cases for optionalChain

* Update index.js
2018-02-07 19:42:14 -05:00
Nicolò Ribaudo
dd0337cc85 Fix failing test (#7344) 2018-02-06 17:42:55 -06:00
Nicolò Ribaudo
4887d81929 Remove bindings of removed paths from scope 2018-02-06 23:59:12 +01:00
Ben Newman
22555cd15d Failing test involving object rest/spread and clearScope().
This failing test case demonstrates a regression between 7.0.0-beta.38 and
7.0.0-beta.39 in the @babel/plugin-proposal-object-rest-spread package.

I distilled this test case from a larger configuration of plugins in my
application, one of which calls api.traverse.cache.clearScope(). Although
calling clearScope() is an uncommon thing for a plugin to do, it was a
reliable way to reproduce the problem. If I can find other reliable
reproductions, I'll push some additional failing tests to this PR.
Regardless of how common it is, clearing the scope cache should be a safe
operation that only slows down the transform (because scopes have to be
recreated and re-crawled). Crashing due to a spurious duplicate
declaration seems like a bug worth fixing.

My hunch is that [these two lines](eb38ea2b10/packages/babel-plugin-proposal-object-rest-spread/src/index.js (L75-L76))
(which were changed in `7.0.0-beta.39`) are not actually removing the
original rest element as a binding from the enclosing `Scope`, in certain
circumstances, so the new variable declaration ends up colliding with the
old (removed) binding.

Possibly related: #7304 (reported by @julien-f)
2018-02-06 23:59:12 +01:00
Daniel Tschinder
593c1a0861 Add core-js as valid polyfill source (#7315) 2018-02-04 17:53:54 -06:00
Kai Cataldo
7234442fde Add location information to parsing errors (#7314) 2018-02-04 13:00:03 -06:00
Justin Ridgewell
5ea1bfe780 Do not optimize away async/gen arrow functions (#7319)
* Do not optimize away async/gen arrow functions

* Node version 8
2018-02-03 17:08:12 -05:00
Tauyekel Kunzhol
2254ed45d2 [Bug fix] Reaching maximum calls stack when copying large number of non-js files in babel-cli (#7320)
Maximum call stack occurs when you try to copy large number of non-js files using `babel-cli@7.0.0-beta.38` or `babel-cli@7.0.0-beta.39`
2018-02-02 20:56:57 -08:00
Logan Smyth
278cd5e572 Preserve identifier location information when mapping this and arguments. (#7312) 2018-02-01 18:54:15 -08:00
Mathias Bynens
96c0415c86 Remove outdated sentence from README (#7311)
Unicode property escapes are now part of ECMAScript proper.

[skip ci]
2018-02-01 14:27:13 -08:00
K Sashi Kumar
ed98d2491e [Typescript] - Fix SyntaxError in async arrow functions with rest params (#7297)
* Fix: [Typescript] - SyntaxError in async arrow functions with rest params

* Fix optional params and add test code in flow
2018-01-31 21:05:24 +01:00
Henry Zhu
eb38ea2b10 Update babel to beta.39 (#7302) 2018-01-30 22:59:00 -05:00
Nicolò Ribaudo
f19d559ff3 Compile Babylon with Gulp (#7240) 2018-01-30 23:13:40 +01:00
Henry Zhu
73e64c6cb0 v7.0.0-beta.39 2018-01-30 15:27:19 -05:00
Brian Ng
3deb246c7d Add some es5 features to babel-preset-env (#6526) 2018-01-30 13:53:38 -06:00
Henry Zhu
1ebc229fa5 Revert "make babel injectable in babel-register" (#7298)
Revert "make babel injectable in babel-register"
2018-01-30 14:16:02 -05:00
Nicolò Ribaudo
cc4913699b Update packages/babylon/README.md [skip ci]
https://github.com/babel/babel/pull/7292#discussion_r164765384
2018-01-30 20:08:15 +01:00
Henry Zhu
82b6ee734b Revert "make babel injectable in babel-register" 2018-01-30 12:39:38 -05:00
Kai Cataldo
22c8f6376c babel-core: Add parse method (#7291) 2018-01-30 12:38:58 -05:00
Raja Sekar
023550c87b Docs: updated link relative to babel/babylon (#7292) [skip ci] 2018-01-30 12:05:43 -05:00
Henry Zhu
8e0d247e8c Fix: fixup package name [skip ci] 2018-01-30 12:04:52 -05:00
Naveen jain
65ae4ff15b Fix: export default decorated class parsed as class expression (#7189) 2018-01-30 12:00:29 -05:00
Owen Buckley
2185256589 update substitution placeholder message in @babel/template (#7255) 2018-01-30 11:54:31 -05:00
Mateusz Burzyński
3316a554bf Support cjs shorthand for modules option in preset-es2015 & preset-env (#7283) 2018-01-30 11:46:21 -05:00
Nicolò Ribaudo
252ea5a966 Fix reused nodes - part 2 (#7149) 2018-01-29 22:59:06 +01:00
Mateusz Burzyński
912bcc186d Fix reused nodes - part 1 (#7149) 2018-01-29 22:59:06 +01:00
Nicolò Ribaudo
63ae923987 Add t.cloneNode and deprecate t.clone and t.cloneDeep (#7149) 2018-01-29 22:59:06 +01:00
Nicolò Ribaudo
dde9274986 Disallow duplicated nodes in tests output (#7149) 2018-01-29 22:59:06 +01:00
Mauro Bringolf
ba111c13b5 Add notice on constant checks to documentation (#7279) [skip ci] 2018-01-29 09:23:01 -05:00
Sven SAULEAU
967414d926 Merge pull request #7273 from Janpot/babel-register-inject
make babel injectable in babel-register
2018-01-26 17:50:53 +01:00
Mauro Bringolf
92fc26d399 Remove check-constants plugin (#6987)
* Rebased onto new version

* Moved constants check into a separate method
2018-01-26 10:43:09 -05:00
Brian Ng
fa5eb4f605 Make comment props more consistent (#7246) 2018-01-26 10:39:52 -05:00
Jan Potoms
d6a782b09c use @babel/core 2018-01-26 16:36:29 +01:00
Jan Potoms
567d25cfa5 Document the feature 2018-01-26 08:38:16 +01:00
Jan Potoms
1da831baa4 improve spec 2018-01-25 10:26:21 +01:00
Jan Potoms
b0d8c62d1c Fix issue where babel was retained 2018-01-25 10:18:02 +01:00
Jan Potoms
0e570eceb2 make babel injectable in babel-register 2018-01-25 08:16:34 +01:00
Justin Ridgewell
ca18ea5e79 Re-add optional chaining delete (#7257)
* Re-add optional chaining delete

* Move exec tests next to output tests

* Forgot to commit these
2018-01-24 11:26:02 -08:00
Alexander Pepper
63d9998aa4 babel-preset-env: Fixed links in readme and improved "Built-ins" example (#7271) 2018-01-24 10:02:03 -06:00
Raja Sekar
88e550c733 removed plugin transform eval (#7262) 2018-01-23 17:31:45 -05:00
Andy
b96fdf8780 typescript: Fix enum emit when values are strings (#7160) 2018-01-23 15:42:32 -06:00
Justin Ridgewell
180eda3211 Remove old optional chain features (#6345) 2018-01-22 14:03:43 -08:00
Kristofer Baxter
b3969d35fa Add preset-env target esmodules (#7212) 2018-01-22 15:44:10 -06:00
Andy
dccfed3601 TypeScript: Support parsing 'unique' type operator (#7239) 2018-01-22 16:09:22 -05:00
Jamie Kyle
5759c33b4c Add opts.message option to code frames (#7243)
* Add opts.message option to code frames

* Fix for missing loc.start in code-frame

* Add docs
2018-01-21 14:19:20 +11:00
Brian Ng
193bccc93c Ensure isPureAnnotated returns a boolean 2018-01-20 13:42:49 -06:00
Brian Ng
5ce54799ff Tweak and add tests to babel-helper-annotate-as-pure (#7245) 2018-01-20 13:29:38 -05:00
Brian Ng
064c17e03f Bump prettier and related deps (#7244) 2018-01-20 17:00:21 +01:00
Matt Ziemer
f9804e6beb Add 'loose' option link for babel-preset-env (#7241)
- Added a external link to a good explanation of “loose” transformations.
http://2ality.com/2015/12/babel6-loose-mode.html
2018-01-20 14:34:52 +02:00
Henry Zhu
47ce7e71c9 Update to beta.38 (#7231) 2018-01-17 18:03:11 -05:00
Luca
5ac8ba19a4 Fix typo [skip ci] (#7229) 2018-01-17 13:43:59 -05:00
2347 changed files with 26372 additions and 14313 deletions

View File

@@ -1,63 +1,80 @@
"use strict";
// Blame Logan for this.
// This works around https://github.com/istanbuljs/istanbuljs/issues/92 until
// we have a version of Istanbul that actually works with 7.x.
function istanbulHacks() {
return {
inherits: require("babel-plugin-istanbul").default,
visitor: {
Program: {
exit: function(path) {
if (!this.__dv__) return
module.exports = function(api) {
const env = api.env();
const node = path.node.body[0];
if (
node.type !== "VariableDeclaration" ||
node.declarations[0].id.type !== "Identifier" ||
!node.declarations[0].id.name.match(/cov_/) ||
node._blockHoist !== 3
) {
throw new Error("Something has gone wrong in Logan's hacks.");
}
const includeCoverage = process.env.BABEL_COVERAGE === "true";
// Gross hacks to put the code coverage block above all compiled
// import statement output.
node._blockHoist = 5;
},
const envOpts = {
loose: true,
modules: false,
exclude: ["transform-typeof-symbol"],
};
let convertESM = true;
switch (env) {
// Configs used during bundling builds.
case "babylon":
case "standalone":
convertESM = false;
break;
case "production":
// Config during builds before publish.
break;
case "development":
envOpts.debug = true;
envOpts.targets = {
node: "current",
};
break;
case "test":
envOpts.targets = {
node: "current",
};
break;
}
const config = {
comments: false,
presets: [["@babel/env", envOpts]],
plugins: [
// TODO: Use @babel/preset-flow when
// https://github.com/babel/babel/issues/7233 is fixed
"@babel/plugin-transform-flow-strip-types",
["@babel/proposal-class-properties", { loose: true }],
"@babel/proposal-export-namespace-from",
"@babel/proposal-numeric-separator",
["@babel/proposal-object-rest-spread", { useBuiltIns: true }],
// Explicitly use the lazy version of CommonJS modules.
convertESM ? ["@babel/transform-modules-commonjs", { lazy: true }] : null,
].filter(Boolean),
overrides: [
{
test: "packages/babylon",
plugins: [
"babel-plugin-transform-charcodes",
["@babel/transform-for-of", { assumeArray: true }],
],
},
},
{
test: "./packages/babel-register",
plugins: [
// Override the root options to disable lazy imports for babel-register
// because otherwise the require hook will try to lazy-import things
// leading to dependency cycles.
convertESM ? "@babel/transform-modules-commonjs" : null,
].filter(Boolean),
},
],
};
}
let envOpts = {
loose: true,
// we need to do this as long as we do not test everything from source
if (includeCoverage) {
config.auxiliaryCommentBefore = "istanbul ignore next";
config.plugins.push("babel-plugin-istanbul");
}
return config;
};
const config = {
comments: false,
presets: [
["@babel/env", envOpts],
"@babel/flow"
],
plugins: [
["@babel/proposal-class-properties", { loose: true }],
"@babel/proposal-export-namespace-from",
"@babel/proposal-numeric-separator",
["@babel/proposal-object-rest-spread", { useBuiltIns: true }],
]
};
if (process.env.BABEL_ENV === "cov") {
config.auxiliaryCommentBefore = "istanbul ignore next";
config.plugins.push(istanbulHacks);
}
if (process.env.BABEL_ENV === "development") {
envOpts.targets = {
node: "current"
};
envOpts.debug = true;
}
module.exports = config;

61
.circleci/config.yml Normal file
View File

@@ -0,0 +1,61 @@
version: 2
aliases:
- &restore-node-modules-cache
keys:
- v1-yarn-deps-{{ checksum "yarn.lock" }}
- &restore-yarn-cache
keys:
- v1-yarn-cache
- &save-node-modules-cache
paths:
- node_modules
key: v1-yarn-deps-{{ checksum "yarn.lock" }}
- &save-yarn-cache
paths:
- ~/.yarn-cache
key: v1-yarn-cache
- &yarn-install
run: |
sudo npm i -g yarn@^1.5.1
yarn --version
- &artifact_babel
path: ~/babel/packages/babel-standalone/babel.js
- &artifact_babel_min
path: ~/babel/packages/babel-standalone/babel.min.js
- &artifact_env
path: ~/babel/packages/babel-preset-env-standalone/babel-preset-env.js
- &artifact_env_min
path: ~/babel/packages/babel-preset-env-standalone/babel-preset-env.min.js
jobs:
build:
working_directory: ~/babel
docker:
- image: circleci/node:9
steps:
- checkout
- restore-cache: *restore-yarn-cache
- restore-cache: *restore-node-modules-cache
- *yarn-install
- run: make test-ci-coverage
# Builds babel-standalone with the regular Babel config
- run: make build
# test-ci-coverage doesn't test babel-standalone, as trying to gather coverage
# data for a JS file that's several megabytes large is bound to fail. Here,
# we just run the babel-standalone test separately.
- run: ./node_modules/.bin/jest packages/babel-standalone/test/
- run: ./node_modules/.bin/jest packages/babel-preset-env-standalone/test/
- store_artifacts: *artifact_babel
- store_artifacts: *artifact_babel_min
- store_artifacts: *artifact_env
- store_artifacts: *artifact_env_min
- save_cache: *save-node-modules-cache
- save_cache: *save-yarn-cache

View File

@@ -1,4 +1,6 @@
/lib
/build
package.json
packages/babel-runtime
!packages/babel-runtime/scripts
!packages/babel-runtime/core-js.js
@@ -18,5 +20,4 @@ packages/babel-preset-env-standalone/babel-preset-env.js
packages/babel-preset-env-standalone/babel-preset-env.min.js
packages/babel-standalone/babel.js
packages/babel-standalone/babel.min.js
packages/babylon/build
packages/babylon/test/expressions

View File

@@ -1,8 +1,7 @@
{
"root": true,
"extends": "babel",
"plugins": [
"prettier"
],
"plugins": ["prettier"],
"rules": {
"curly": ["error", "multi-line"],
"prettier/prettier": "error",
@@ -13,22 +12,21 @@
},
"overrides": [
{
"files": [
"packages/*/src/**/*.js",
"codemods/*/src/**/*.js"
],
"files": ["packages/*/src/**/*.js", "codemods/*/src/**/*.js"],
"rules": {
"no-undefined-identifier": "error"
"no-undefined-identifier": "error",
"no-deprecated-clone": "error"
}
},
{
"files": [
"packages/*/test/**/*.js",
"codemods/*/test/**/*.js",
"packages/babel-helper-transform-fixture-test-runner/src/helpers.js",
"test/**/*.js"
],
"env": {
"mocha": true
"jest": true
}
}
]

View File

@@ -13,8 +13,8 @@ codemods/*/src
[libs]
lib/file.js
lib/parser.js
lib/packages/babel-types/lib/index.js.flow
lib/third-party-libs.js.flow
packages/babel-types/lib/index.js.flow
[options]
include_warnings=true

4
.gitignore vendored
View File

@@ -16,15 +16,19 @@ package-lock.json
!/packages/babel-runtime/core-js/map.js
/packages/babel-runtime/helpers/*.js
!/packages/babel-runtime/helpers/toArray.js
!/packages/babel-runtime/helpers/iterableToArray.js
!/packages/babel-runtime/helpers/temporalRef.js
/packages/babel-runtime/helpers/builtin/*.js
!/packages/babel-runtime/helpers/builtin/toArray.js
!/packages/babel-runtime/helpers/builtin/iterableToArray.js
!/packages/babel-runtime/helpers/builtin/temporalRef.js
/packages/babel-runtime/helpers/builtin/es6/*.js
!/packages/babel-runtime/helpers/builtin/es6/toArray.js
!/packages/babel-runtime/helpers/builtin/es6/iterableToArray.js
!/packages/babel-runtime/helpers/builtin/es6/temporalRef.js
/packages/babel-runtime/helpers/es6/*.js
!/packages/babel-runtime/helpers/es6/toArray.js
!/packages/babel-runtime/helpers/es6/iterableToArray.js
!/packages/babel-runtime/helpers/es6/temporalRef.js
/packages/babel-register/test/.babel
/packages/babel-cli/test/tmp

1
.prettierignore Normal file
View File

@@ -0,0 +1 @@
package.json

View File

@@ -1,5 +1,14 @@
{
"arrowParens": "avoid",
"trailingComma": "es5",
"useTabs": false,
"semi": true,
"singleQuote": false,
"bracketSpacing": true,
"jsxBracketSameLine": false,
"tabWidth": 2,
"parser": "babylon",
"printWidth": 80,
"overrides": [{
"files": [
"**/codemods/*/src/**/*.js",

View File

@@ -7,6 +7,7 @@ cache:
directories:
- node_modules
node_js:
# We test the latest version on circleci
- '8'
- '6'
- '4'
@@ -19,6 +20,8 @@ env:
before_install:
- curl -o- -L https://yarnpkg.com/install.sh | bash
install: yarn --ignore-engines
before_script:
- 'if [ "$JOB" = "babylon-flow-tests" ]; then make bootstrap-flow; fi'
- 'if [ "$JOB" = "babylon-test262-tests" ]; then make bootstrap-test262; fi'

View File

@@ -116,7 +116,7 @@ $ TEST_ONLY=babel-cli make test
```sh
# Run tests for the @babel/plugin-transform-classes package.
$ TEST_ONLY=es2015-class make test
$ TEST_ONLY=babel-plugin-transform-classes make test
```
Use the `TEST_GREP` variable to run a subset of tests by name:
@@ -175,7 +175,7 @@ For example, in [`@babel/plugin-transform-exponentiation-operator/test`](https:/
- In each subfolder, you can organize your directory structure by categories of tests. (Example: these folders can be named after the feature you are testing or can reference the issue number they fix)
- Generally, there are two kinds of tests for plugins
- The first is a simple test of the input and output produced by running Babel on some code. We do this by creating an [`input.js`](https://github.com/babel/babel/blob/master/packages/babel-plugin-transform-exponentiation-operator/test/fixtures/exponentian-operator/binary/input.js) file and an [`output.js`](https://github.com/babel/babel/blob/master/packages/babel-plugin-transform-exponentiation-operator/test/fixtures/exponentian-operator/binary/output.js) file.
  - The first is a simple test of the input and output produced by running Babel on some code. We do this by creating an [`input.js`](https://github.com/babel/babel/blob/master/packages/babel-plugin-transform-exponentiation-operator/test/fixtures/exponentian-operator/binary/input.js) file and an [`output.js`](https://github.com/babel/babel/blob/master/packages/babel-plugin-transform-exponentiation-operator/test/fixtures/exponentian-operator/binary/output.js) file. This kind of test only works in sub-subdirectories of `/fixtures`, i.e. `/fixtures/exponentian-operator/binary/input.js` and **not** `/fixtures/exponentian-operator/input.js`.
- If you need to expect an error, you can ignore creating the `output.js` file and pass a new `throws` key to the `options.json` that contains the error string that is created.
- The second and preferred type is a test that actually evaluates the produced code and asserts that certain properties are true or false. We do this by creating an [`exec.js`](https://github.com/babel/babel/blob/master/packages/babel-plugin-transform-exponentiation-operator/test/fixtures/exponentian-operator/comprehensive/exec.js) file.
@@ -234,7 +234,7 @@ descriptive name, and add the following:
After writing tests for babylon, just build it by running:
```sh
$ make build-babylon
$ make build
```
Then, to run the tests, use:

View File

@@ -12,6 +12,11 @@ const gulp = require("gulp");
const path = require("path");
const webpack = require("webpack");
const merge = require("merge-stream");
const rollup = require("rollup-stream");
const source = require("vinyl-source-stream");
const buffer = require("vinyl-buffer");
const rollupBabel = require("rollup-plugin-babel");
const rollupNodeResolve = require("rollup-plugin-node-resolve");
const registerStandalonePackageTask = require("./scripts/gulp-tasks")
.registerStandalonePackageTask;
@@ -27,53 +32,101 @@ function getGlobFromSource(source) {
return `./${source}/*/src/**/*.js`;
}
gulp.task("default", ["build"]);
function getIndexFromPackage(name) {
return `${name}/src/index.js`;
}
gulp.task("build", function() {
function compilationLogger(rollup) {
return through.obj(function(file, enc, callback) {
gutil.log(
`Compiling '${chalk.cyan(file.relative)}'${
rollup ? " with rollup " : ""
}...`
);
callback(null, file);
});
}
function errorsLogger() {
return plumber({
errorHandler(err) {
gutil.log(err.stack);
},
});
}
function rename(fn) {
return through.obj(function(file, enc, callback) {
file.path = fn(file);
callback(null, file);
});
}
function buildBabel(exclude) {
return merge(
sources.map(source => {
const base = path.join(__dirname, source);
const f = filter(["**", "!**/packages/babylon/**"]);
return gulp
.src(getGlobFromSource(source), { base: base })
.pipe(f)
.pipe(
plumber({
errorHandler: function(err) {
gutil.log(err.stack);
},
})
)
.pipe(
newer({
dest: base,
map: swapSrcWithLib,
})
)
.pipe(
through.obj(function(file, enc, callback) {
gutil.log("Compiling", "'" + chalk.cyan(file.relative) + "'...");
callback(null, file);
})
)
let stream = gulp.src(getGlobFromSource(source), { base: base });
if (exclude) {
const filters = exclude.map(p => `!**/${p}/**`);
filters.unshift("**");
stream = stream.pipe(filter(filters));
}
return stream
.pipe(errorsLogger())
.pipe(newer({ dest: base, map: swapSrcWithLib }))
.pipe(compilationLogger())
.pipe(babel())
.pipe(
through.obj(function(file, enc, callback) {
// Passing 'file.relative' because newer() above uses a relative
// path and this keeps it consistent.
file.path = path.resolve(file.base, swapSrcWithLib(file.relative));
callback(null, file);
})
// Passing 'file.relative' because newer() above uses a relative
// path and this keeps it consistent.
rename(file => path.resolve(file.base, swapSrcWithLib(file.relative)))
)
.pipe(gulp.dest(base));
})
);
}
function buildRollup(packages) {
return merge(
packages.map(pkg => {
return rollup({
input: getIndexFromPackage(pkg),
format: "cjs",
plugins: [
rollupBabel({
envName: "babylon",
babelrc: false,
extends: "./.babelrc.js",
}),
rollupNodeResolve(),
],
})
.pipe(source("index.js"))
.pipe(buffer())
.pipe(errorsLogger())
.pipe(compilationLogger(/* rollup */ true))
.pipe(gulp.dest(path.join(pkg, "lib")));
})
);
}
gulp.task("default", ["build"]);
gulp.task("build", function() {
const bundles = ["packages/babylon"];
return merge([buildBabel(/* exclude */ bundles), buildRollup(bundles)]);
});
gulp.task("watch", ["build"], function() {
gulp.task("build-no-bundle", () => buildBabel());
gulp.task("watch", ["build-no-bundle"], function() {
watch(sources.map(getGlobFromSource), { debounceDelay: 200 }, function() {
gulp.start("build");
gulp.start("build-no-bundle");
});
});

View File

@@ -1,8 +1,6 @@
MAKEFLAGS = -j1
FLOW_COMMIT = 622bbc4f07acb77eb1109830c70815f827401d90
TEST262_COMMIT = 1282e842febf418ca27df13fa4b32f7e5021b470
export NODE_ENV = test
TEST262_COMMIT = 52f70e2f637731aae92a9c9a2d831310c3ab2e1e
# Fix color output until TravisCI fixes https://github.com/travis-ci/travis-ci/issues/7967
export FORCE_COLOR = true
@@ -11,10 +9,7 @@ SOURCES = packages codemods
.PHONY: build build-dist watch lint fix clean test-clean test-only test test-ci publish bootstrap
build: clean
make clean-lib
# Build babylon before building all other projects
make build-babylon
build: clean clean-lib
./node_modules/.bin/gulp build
node ./packages/babel-types/scripts/generateTypeHelpers.js
# call build again as the generated files might need to be compiled again.
@@ -24,15 +19,11 @@ build: clean
node scripts/generators/typescript.js > ./packages/babel-types/lib/index.d.ts
# generate docs
node scripts/generators/docs.js > ./packages/babel-types/README.md
ifneq ("$(BABEL_ENV)", "cov")
ifneq ("$(BABEL_COVERAGE)", "true")
make build-standalone
make build-preset-env-standalone
endif
build-babylon:
cd packages/babylon; \
./node_modules/.bin/rollup -c
build-standalone:
./node_modules/.bin/gulp build-babel-standalone
@@ -45,22 +36,25 @@ build-dist: build
cd packages/babel-runtime; \
node scripts/build-dist.js
watch: clean
make clean-lib
BABEL_ENV=development ./node_modules/.bin/gulp watch
watch: clean clean-lib
watch-babylon:
cd packages/babylon; \
./node_modules/.bin/rollup -c -w
# Ensure that build artifacts for types are created during local
# development too.
BABEL_ENV=development ./node_modules/.bin/gulp build-no-bundle
node ./packages/babel-types/scripts/generateTypeHelpers.js
node scripts/generators/flow.js > ./packages/babel-types/lib/index.js.flow
BABEL_ENV=development ./node_modules/.bin/gulp watch
flow:
./node_modules/.bin/flow check --strip-root
lint:
./node_modules/.bin/eslint scripts $(SOURCES) *.js --format=codeframe --rulesdir="./scripts/eslint_rules"
./node_modules/.bin/eslint scripts $(SOURCES) '*.js' '**/.*.js' --format=codeframe --rulesdir="./scripts/eslint_rules"
fix:
./node_modules/.bin/eslint scripts $(SOURCES) *.js --format=codeframe --fix --rulesdir="./scripts/eslint_rules"
# The config is hardcoded because otherwise prettier searches for it and also picks up some broken package.json files from tests
./node_modules/.bin/prettier --config .prettierrc --write --ignore-path .eslintignore '**/*.json'
./node_modules/.bin/eslint scripts $(SOURCES) '*.js' '**/.*.js' --format=codeframe --fix --rulesdir="./scripts/eslint_rules"
clean: test-clean
rm -rf packages/babel-polyfill/browser*
@@ -73,19 +67,17 @@ test-clean:
$(call clean-source-test, $(source)))
test-only:
./scripts/test.sh
BABEL_ENV=test ./scripts/test.sh
make test-clean
test: lint test-only
test-ci:
make bootstrap
make test-only
test-ci: bootstrap test-only
test-ci-coverage: SHELL:=/bin/bash
test-ci-coverage:
BABEL_ENV=cov make bootstrap
./scripts/test-cov.sh
BABEL_COVERAGE=true BABEL_ENV=test make bootstrap
BABEL_ENV=test TEST_TYPE=cov ./scripts/test-cov.sh
bash <(curl -s https://codecov.io/bash) -f coverage/coverage-final.json
bootstrap-flow:
@@ -97,9 +89,7 @@ bootstrap-flow:
test-flow:
node scripts/tests/flow/run_babylon_flow_tests.js
test-flow-ci:
make bootstrap
make test-flow
test-flow-ci: bootstrap test-flow
test-flow-update-whitelist:
node scripts/tests/flow/run_babylon_flow_tests.js --update-whitelist
@@ -113,9 +103,7 @@ bootstrap-test262:
test-test262:
node scripts/tests/test262/run_babylon_test262.js
test-test262-ci:
make bootstrap
make test-test262
test-test262-ci: bootstrap test-test262
test-test262-update-whitelist:
node scripts/tests/test262/run_babylon_test262.js --update-whitelist
@@ -132,10 +120,9 @@ publish:
./node_modules/.bin/lerna publish --force-publish=* --exact --skip-temp-tag
make clean
bootstrap:
make clean-all
yarn
./node_modules/.bin/lerna bootstrap
bootstrap: clean-all
yarn --ignore-engines
./node_modules/.bin/lerna bootstrap -- --ignore-engines
make build
cd packages/babel-runtime; \
node scripts/build-dist.js

View File

@@ -1,30 +0,0 @@
general:
artifacts:
- "packages/babel-standalone/babel.js"
- "packages/babel-standalone/babel.min.js"
- "packages/babel-preset-env-standalone/babel-preset-env.js"
- "packages/babel-preset-env-standalone/babel-preset-env.min.js"
machine:
node:
version:
8
dependencies:
pre:
- curl -o- -L https://yarnpkg.com/install.sh | bash
cache_directories:
- ~/.yarn-cache
override:
- yarn
test:
override:
- make test-ci-coverage
# Builds babel-standalone with the regular Babel config
- make build
# test-ci-coverage doesn't test babel-standalone, as trying to gather coverage
# data for a JS file that's several megabytes large is bound to fail. Here,
# we just run the babel-standalone test separately.
- ./node_modules/mocha/bin/_mocha packages/babel-standalone/test/ --opts test/mocha.opts
- ./node_modules/mocha/bin/_mocha packages/babel-preset-env-standalone/test/ --opts test/mocha.opts

View File

@@ -1,6 +1,6 @@
{
"name": "@babel/plugin-codemod-optional-catch-binding",
"version": "7.0.0-beta.38",
"version": "7.0.0-beta.44",
"description": "Remove unused catch bindings",
"repository": "https://github.com/babel/babel/tree/master/packages/babel-plugin-transform-remove-unused-catch-binding",
"license": "MIT",
@@ -9,13 +9,13 @@
"@babel/plugin"
],
"dependencies": {
"@babel/plugin-syntax-optional-catch-binding": "7.0.0-beta.38"
"@babel/plugin-syntax-optional-catch-binding": "7.0.0-beta.44"
},
"peerDependencies": {
"@babel/core": "7.0.0-beta.38"
"@babel/core": "7.0.0-beta.44"
},
"devDependencies": {
"@babel/core": "7.0.0-beta.38",
"@babel/helper-plugin-test-runner": "7.0.0-beta.38"
"@babel/core": "7.0.0-beta.44",
"@babel/helper-plugin-test-runner": "7.0.0-beta.44"
}
}

View File

@@ -15,7 +15,7 @@ This is quite taboo but let's look at the pros and cons:
* Easy to coordinate changes across modules.
* Single place to report issues.
* Easier to setup a development environment.
* Tests across modules are ran together which finds bugs that touch multiple modules easier.
* Tests across modules are run together which finds bugs that touch multiple modules easier.
**Cons:**

View File

@@ -1,16 +1,16 @@
{
"lerna": "2.0.0-rc.4",
"version": "7.0.0-beta.38",
"version": "7.0.0-beta.44",
"changelog": {
"repo": "babel/babel",
"labels": {
"PR: Spec Compliancy": ":eyeglasses: Spec Compliancy",
"PR: Breaking Change": ":boom: Breaking Change",
"PR: New Feature": ":rocket: New Feature",
"PR: Bug Fix": ":bug: Bug Fix",
"PR: Polish": ":nail_care: Polish",
"PR: Docs": ":memo: Documentation",
"PR: Internal": ":house: Internal"
"PR: Spec Compliancy :eyeglasses:": ":eyeglasses: Spec Compliancy",
"PR: Breaking Change :boom:": ":boom: Breaking Change",
"PR: New Feature :rocket:": ":rocket: New Feature",
"PR: Bug Fix :bug:": ":bug: Bug Fix",
"PR: Polish :nail_care:": ":nail_care: Polish",
"PR: Docs :memo:": ":memo: Documentation",
"PR: Internal :house:": ":house: Internal"
}
},
"cacheDir": ".changelog",

View File

@@ -3,9 +3,9 @@
*/
declare module "micromatch" {
declare function exports(Array<string>, Array<string>, ?{
nocase: boolean,
}): Array<string>;
declare module.exports: {
(Array<string>, Array<string>, ?{ nocase: boolean }): Array<string>,
};
}
declare module "resolve" {

View File

@@ -10,31 +10,35 @@
"test": "make test"
},
"devDependencies": {
"@babel/cli": "7.0.0-beta.37",
"@babel/core": "7.0.0-beta.37",
"@babel/preset-env": "7.0.0-beta.37",
"@babel/preset-flow": "7.0.0-beta.37",
"@babel/preset-stage-0": "7.0.0-beta.37",
"@babel/register": "7.0.0-beta.37",
"async": "^1.5.0",
"@babel/cli": "7.0.0-beta.42",
"@babel/core": "7.0.0-beta.42",
"@babel/plugin-transform-modules-commonjs": "7.0.0-beta.42",
"@babel/preset-env": "7.0.0-beta.42",
"@babel/preset-flow": "7.0.0-beta.42",
"@babel/preset-stage-0": "7.0.0-beta.42",
"@babel/register": "7.0.0-beta.42",
"babel-core": "^7.0.0-0",
"babel-eslint": "^8.0.1",
"babel-jest": "^22.4.1",
"babel-loader": "8.0.0-beta.0",
"babel-plugin-istanbul": "^4.1.4",
"babylon": "7.0.0-beta.37",
"babel-plugin-transform-charcodes": "^0.1.0",
"babylon": "7.0.0-beta.42",
"browserify": "^13.1.1",
"bundle-collapser": "^1.2.1",
"chai": "^4.1.0",
"chalk": "^2.0.0",
"chalk": "^2.3.2",
"charcodes": "^0.1.0",
"derequire": "^2.0.2",
"eslint": "^4.5.0",
"enhanced-resolve": "^3.0.0",
"eslint": "^4.18.2",
"eslint-config-babel": "^7.0.2",
"eslint-plugin-flowtype": "^2.20.0",
"eslint-plugin-prettier": "^2.2.0",
"flow-bin": "^0.59.0",
"eslint-plugin-prettier": "^2.5.0",
"flow-bin": "^0.66.0",
"graceful-fs": "^4.1.11",
"gulp": "^3.9.0",
"gulp-babel": "^8.0.0-beta.0",
"gulp-filter": "^5.0.1",
"gulp-babel": "^8.0.0-beta.2",
"gulp-filter": "^5.1.0",
"gulp-newer": "^1.0.0",
"gulp-plumber": "^1.0.1",
"gulp-rename": "^1.2.2",
@@ -42,21 +46,24 @@
"gulp-util": "^3.0.7",
"gulp-watch": "^4.3.5",
"husky": "^0.14.3",
"jest": "^22.4.2",
"lerna": "2.0.0",
"lerna-changelog": "^0.5.0",
"lint-staged": "^4.2.3",
"lint-staged": "^6.0.1",
"lodash": "^4.2.0",
"merge-stream": "^1.0.1",
"mocha": "^3.0.0",
"nyc": "^11.0.3",
"output-file-sync": "^2.0.0",
"prettier": "1.9.1",
"prettier": "1.11.1",
"pump": "^1.0.2",
"rimraf": "^2.4.3",
"semver": "^5.0.0",
"rollup-plugin-babel": "^4.0.0-beta.0",
"rollup-plugin-node-resolve": "^3.0.2",
"rollup-stream": "^1.24.1",
"test262-stream": "^1.1.0",
"through2": "^2.0.0",
"uglify-js": "^2.4.16",
"util.promisify": "^1.0.0",
"vinyl-buffer": "^1.0.1",
"vinyl-source-stream": "^2.0.0",
"webpack": "^3.4.1",
"webpack-dependency-suite": "^2.4.4",
"webpack-stream": "^4.0.0"
@@ -66,20 +73,45 @@
"npm": ">= 2.x <= 5.x",
"yarn": ">=0.27.5 || >=1.0.0-20170811"
},
"nyc": {
"all": true,
"exclude": [
"scripts/*.js",
"packages/*/test/**",
"packages/babel-standalone/**",
"codemods/*/test/**"
],
"sourceMap": false,
"instrument": false
},
"lint-staged": {
"*.js": [
"eslint --format=codeframe --rulesdir='./scripts/eslint_rules'"
]
},
"jest": {
"collectCoverageFrom": [
"packages/*/src/**/*.mjs",
"packages/*/src/**/*.js",
"codemods/*/src/**/*.mjs",
"codemods/*/src/**/*.js"
],
"testRegex": "./(packages|codemods)/[^/]+/test/.+\\.m?js$",
"testPathIgnorePatterns": [
"/node_modules/",
"/test/fixtures/",
"/test/debug-fixtures/",
"/babylon/test/expressions/",
"/test/tmp/",
"/test/__data__/",
"/test/helpers/",
"<rootDir>/test/warning\\.js",
"<rootDir>/build/",
"_browser\\.js"
],
"testEnvironment": "node",
"setupTestFrameworkScriptFile": "<rootDir>/test/testSetupFile.js",
"transformIgnorePatterns": [
"/node_modules/",
"<rootDir>/packages/babel-standalone/babel(\\.min)?\\.js",
"<rootDir>/packages/babel-preset-env-standalone/babel-preset-env(\\.min)?\\.js",
"/test/(fixtures|tmp|__data__)/",
"<rootDir>/(packages|codemods)/[^/]+/lib/"
],
"modulePathIgnorePatterns": [
"/test/fixtures/",
"/test/tmp/",
"/test/__data__/",
"<rootDir>/build/"
]
}
}

View File

@@ -13,15 +13,15 @@ A monorepo, muhahahahahaha. See the [monorepo design doc](/doc/design/monorepo.m
| Package | Version | Dependencies |
|--------|-------|------------|
| [`@babel/core`](/packages/babel-core) | [![npm](https://img.shields.io/npm/v/babel-core.svg?maxAge=2592000)](https://www.npmjs.com/package/babel-core) | [![Dependency Status](https://david-dm.org/babel/babel.svg?path=packages/babel-core)](https://david-dm.org/babel/babel?path=packages/babel-core) |
| [`babylon`](https://github.com/babel/babel/tree/master/packages/babylon) | [![npm](https://img.shields.io/npm/v/babylon.svg?maxAge=2592000)](https://www.npmjs.com/package/babylon) | [![Dependency Status](https://david-dm.org/babel/babylon.svg)](https://david-dm.org/babel/babylon) |
| [`@babel/traverse`](/packages/babel-traverse) | [![npm](https://img.shields.io/npm/v/babel-traverse.svg?maxAge=2592000)](https://www.npmjs.com/package/babel-traverse) | [![Dependency Status](https://david-dm.org/babel/babel.svg?path=packages/babel-traverse)](https://david-dm.org/babel/babel?path=packages/babel-traverse) |
| [`@babel/generator`](/packages/babel-generator) | [![npm](https://img.shields.io/npm/v/babel-generator.svg?maxAge=2592000)](https://www.npmjs.com/package/babel-generator) | [![Dependency Status](https://david-dm.org/babel/babel.svg?path=packages/babel-generator)](https://david-dm.org/babel/babel?path=packages/babel-generator) |
| [`@babel/core`](/packages/babel-core) | [![npm](https://img.shields.io/npm/v/@babel/core.svg?maxAge=2592000)](https://www.npmjs.com/package/@babel/core) | [![Dependency Status](https://david-dm.org/babel/babel.svg?path=packages/babel-core)](https://david-dm.org/babel/babel?path=packages/babel-core) |
| [`babylon`](/packages/babylon) | [![npm](https://img.shields.io/npm/v/babylon.svg?maxAge=2592000)](https://www.npmjs.com/package/babylon) | [![Dependency Status](https://david-dm.org/babel/babel.svg?path=packages/babylon)](https://david-dm.org/babel/babel?path=packages/babylon) |
| [`@babel/traverse`](/packages/babel-traverse) | [![npm](https://img.shields.io/npm/v/@babel/traverse.svg?maxAge=2592000)](https://www.npmjs.com/package/@babel/traverse) | [![Dependency Status](https://david-dm.org/babel/babel.svg?path=packages/babel-traverse)](https://david-dm.org/babel/babel?path=packages/babel-traverse) |
| [`@babel/generator`](/packages/babel-generator) | [![npm](https://img.shields.io/npm/v/@babel/generator.svg?maxAge=2592000)](https://www.npmjs.com/package/@babel/generator) | [![Dependency Status](https://david-dm.org/babel/babel.svg?path=packages/babel-generator)](https://david-dm.org/babel/babel?path=packages/babel-generator) |
[`@babel/core`](/packages/babel-core) is the Babel compiler itself; it exposes the `babel.transform` method, where `transformedCode = transform(src).code`.
The compiler can be broken down into 3 parts:
- The parser: [`babylon`](https://github.com/babel/babel/tree/master/packages/babylon)
- The parser: [`babylon`](/packages/babylon)
- The transformer[s]: All the plugins/presets
- These all use [`@babel/traverse`](/packages/babel-traverse) to traverse through the AST
- The generator: [`@babel/generator`](/packages/babel-generator)
@@ -36,18 +36,18 @@ Check out the [`babel-handbook`](https://github.com/thejameskyle/babel-handbook/
| Package | Version | Dependencies |
|--------|-------|------------|
| [`@babel/cli`](/packages/babel-cli) | [![npm](https://img.shields.io/npm/v/babel-cli.svg?maxAge=2592000)](https://www.npmjs.com/package/babel-cli) | [![Dependency Status](https://david-dm.org/babel/babel.svg?path=packages/babel-cli)](https://david-dm.org/babel/babel?path=packages/babel-cli) |
| [`@babel/types`](/packages/babel-types) | [![npm](https://img.shields.io/npm/v/babel-types.svg?maxAge=2592000)](https://www.npmjs.com/package/babel-types) | [![Dependency Status](https://david-dm.org/babel/babel.svg?path=packages/babel-types)](https://david-dm.org/babel/babel?path=packages/babel-types) |
| [`@babel/polyfill`](/packages/babel-polyfill) | [![npm](https://img.shields.io/npm/v/babel-polyfill.svg?maxAge=2592000)](https://www.npmjs.com/package/babel-polyfill) | [![Dependency Status](https://david-dm.org/babel/babel.svg?path=packages/babel-polyfill)](https://david-dm.org/babel/babel?path=packages/babel-polyfill) |
| [`@babel/runtime`](/packages/babel-runtime) | [![npm](https://img.shields.io/npm/v/babel-runtime.svg?maxAge=2592000)](https://www.npmjs.com/package/babel-runtime) | [![Dependency Status](https://david-dm.org/babel/babel.svg?path=packages/babel-runtime)](https://david-dm.org/babel/babel?path=packages/babel-runtime) |
| [`@babel/register`](/packages/babel-register) | [![npm](https://img.shields.io/npm/v/babel-register.svg?maxAge=2592000)](https://www.npmjs.com/package/babel-register) | [![Dependency Status](https://david-dm.org/babel/babel.svg?path=packages/babel-register)](https://david-dm.org/babel/babel?path=packages/babel-register) |
| [`@babel/template`](/packages/babel-template) | [![npm](https://img.shields.io/npm/v/babel-template.svg?maxAge=2592000)](https://www.npmjs.com/package/babel-template) | [![Dependency Status](https://david-dm.org/babel/babel.svg?path=packages/babel-template)](https://david-dm.org/babel/babel?path=packages/babel-template) |
| [`@babel/helpers`](/packages/babel-helpers) | [![npm](https://img.shields.io/npm/v/babel-helpers.svg?maxAge=2592000)](https://www.npmjs.com/package/babel-helpers) | [![Dependency Status](https://david-dm.org/babel/babel.svg?path=packages/babel-helpers)](https://david-dm.org/babel/babel?path=packages/babel-helpers) |
| [`@babel/code-frame`](/packages/babel-code-frame) | [![npm](https://img.shields.io/npm/v/babel-code-frame.svg?maxAge=2592000)](https://www.npmjs.com/package/babel-code-frame) | [![Dependency Status](https://david-dm.org/babel/babel.svg?path=packages/babel-code-frame)](https://david-dm.org/babel/babel?path=packages/babel-code-frame) |
| [`@babel/cli`](/packages/babel-cli) | [![npm](https://img.shields.io/npm/v/@babel/cli.svg?maxAge=2592000)](https://www.npmjs.com/package/@babel/cli) | [![Dependency Status](https://david-dm.org/babel/babel.svg?path=packages/babel-cli)](https://david-dm.org/babel/babel?path=packages/babel-cli) |
| [`@babel/types`](/packages/babel-types) | [![npm](https://img.shields.io/npm/v/@babel/types.svg?maxAge=2592000)](https://www.npmjs.com/package/@babel/types) | [![Dependency Status](https://david-dm.org/babel/babel.svg?path=packages/babel-types)](https://david-dm.org/babel/babel?path=packages/babel-types) |
| [`@babel/polyfill`](/packages/babel-polyfill) | [![npm](https://img.shields.io/npm/v/@babel/polyfill.svg?maxAge=2592000)](https://www.npmjs.com/package/@babel/polyfill) | [![Dependency Status](https://david-dm.org/babel/babel.svg?path=packages/babel-polyfill)](https://david-dm.org/babel/babel?path=packages/babel-polyfill) |
| [`@babel/runtime`](/packages/babel-runtime) | [![npm](https://img.shields.io/npm/v/@babel/runtime.svg?maxAge=2592000)](https://www.npmjs.com/package/@babel/runtime) | [![Dependency Status](https://david-dm.org/babel/babel.svg?path=packages/babel-runtime)](https://david-dm.org/babel/babel?path=packages/babel-runtime) |
| [`@babel/register`](/packages/babel-register) | [![npm](https://img.shields.io/npm/v/@babel/register.svg?maxAge=2592000)](https://www.npmjs.com/package/@babel/register) | [![Dependency Status](https://david-dm.org/babel/babel.svg?path=packages/babel-register)](https://david-dm.org/babel/babel?path=packages/babel-register) |
| [`@babel/template`](/packages/babel-template) | [![npm](https://img.shields.io/npm/v/@babel/template.svg?maxAge=2592000)](https://www.npmjs.com/package/@babel/template) | [![Dependency Status](https://david-dm.org/babel/babel.svg?path=packages/babel-template)](https://david-dm.org/babel/babel?path=packages/babel-template) |
| [`@babel/helpers`](/packages/babel-helpers) | [![npm](https://img.shields.io/npm/v/@babel/helpers.svg?maxAge=2592000)](https://www.npmjs.com/package/@babel/helpers) | [![Dependency Status](https://david-dm.org/babel/babel.svg?path=packages/babel-helpers)](https://david-dm.org/babel/babel?path=packages/babel-helpers) |
| [`@babel/code-frame`](/packages/babel-code-frame) | [![npm](https://img.shields.io/npm/v/@babel/code-frame.svg?maxAge=2592000)](https://www.npmjs.com/package/@babel/code-frame) | [![Dependency Status](https://david-dm.org/babel/babel.svg?path=packages/babel-code-frame)](https://david-dm.org/babel/babel?path=packages/babel-code-frame) |
- [`@babel/cli`](/packages/babel-cli) is the CLI tool that runs `@babel/core` and helps with outputting to a directory, a file, stdout and more (also includes `@babel/node` cli). Check out the [docs](https://babeljs.io/docs/usage/cli/).
- [`@babel/types`](/packages/babel-types) is used to validate, build and change AST nodes.
- [`@babel/polyfill`](/packages/babel-polyfill) is [literally a wrapper](https://github.com/babel/babel/blob/master/packages/babel-polyfill/src/index.js) around [`core-js`](https://github.com/zloirock/core-js) and [regenerator-runtime](https://github.com/facebook/regenerator/tree/master/packages/regenerator-runtime). Check out the [docs](https://babeljs.io/docs/usage/polyfill/).
- [`@babel/polyfill`](/packages/babel-polyfill) is [literally a wrapper](/packages/babel-polyfill/src/index.js) around [`core-js`](https://github.com/zloirock/core-js) and [regenerator-runtime](https://github.com/facebook/regenerator/tree/master/packages/regenerator-runtime). Check out the [docs](https://babeljs.io/docs/usage/polyfill/).
- [`@babel/runtime`](/packages/babel-runtime) is similar to the polyfill except that it doesn't modify the global scope and is to be used with [`@babel/plugin-transform-runtime`](/packages/babel-plugin-transform-runtime) (usually in library/plugin code). Check out the [docs](https://babeljs.io/docs/plugins/transform-runtime/).
- [`@babel/register`](/packages/babel-register) is a way to automatically compile files with Babel on the fly by binding to Node.js `require`. Check out the [docs](http://babeljs.io/docs/usage/require/).
- [`@babel/template`](/packages/babel-template) is a helper function that allows constructing AST nodes from a string presentation of the code; this eliminates the tedium of using `@babel/types` for building AST nodes.
@@ -62,7 +62,7 @@ The transformer[s] used in Babel are the independent pieces of code that transfo
| Package | Version | Dependencies | Description |
|--------|-------|------------|---|
| [`@babel/preset-env`](https://github.com/babel/babel-preset-env) | [![npm](https://img.shields.io/npm/v/babel-preset-env.svg?maxAge=2592000)](https://www.npmjs.com/package/babel-preset-env) | [![Dependency Status](https://david-dm.org/babel/babel-preset-env.svg)](https://david-dm.org/babel/babel-preset-env) | automatically determines plugins and polyfills you need based on your supported environments |
| [`@babel/preset-env`](/packages/babel-preset-env) | [![npm](https://img.shields.io/npm/v/@babel/preset-env.svg?maxAge=2592000)](https://www.npmjs.com/package/@babel/preset-env) | [![Dependency Status](https://david-dm.org/babel/babel/status.svg?path=packages/babel-preset-env)](https://david-dm.org/babel/babel?path=packages/babel-preset-env) | automatically determines plugins and polyfills you need based on your supported environments |
> You can find community maintained presets on [npm](https://www.npmjs.com/search?q=babel-preset)

View File

@@ -1,6 +1,6 @@
{
"name": "@babel/cli",
"version": "7.0.0-beta.38",
"version": "7.0.0-beta.44",
"description": "Babel command line.",
"author": "Sebastian McKenzie <sebmck@gmail.com>",
"homepage": "https://babeljs.io/",
@@ -29,11 +29,11 @@
"chokidar": "^1.6.1"
},
"peerDependencies": {
"@babel/core": "7.0.0-beta.38"
"@babel/core": "7.0.0-beta.44"
},
"devDependencies": {
"@babel/core": "7.0.0-beta.38",
"@babel/helper-fixtures": "7.0.0-beta.38"
"@babel/core": "7.0.0-beta.44",
"@babel/helper-fixtures": "7.0.0-beta.44"
},
"bin": {
"babel": "./bin/babel.js",

View File

@@ -6,6 +6,8 @@ import fs from "fs";
import * as util from "./util";
let compiledFiles = 0;
export default function(commander, filenames, opts) {
function write(src, relative, base, callback) {
if (typeof base === "function") {
@@ -13,7 +15,7 @@ export default function(commander, filenames, opts) {
base = undefined;
}
if (!util.isCompilableExtension(relative, commander.extensions)) {
return callback();
return process.nextTick(callback);
}
// remove extension and then append back on .js
@@ -26,7 +28,6 @@ export default function(commander, filenames, opts) {
defaults(
{
sourceFileName: slash(path.relative(dest + "/..", src)),
sourceMapTarget: path.basename(relative),
},
opts,
),
@@ -42,12 +43,15 @@ export default function(commander, filenames, opts) {
) {
const mapLoc = dest + ".map";
res.code = util.addSourceMappingUrl(res.code, mapLoc);
res.map.file = path.basename(relative);
outputFileSync(mapLoc, JSON.stringify(res.map));
}
outputFileSync(dest, res.code);
util.chmod(src, dest);
compiledFiles += 1;
util.log(src + " -> " + dest);
return callback(null, true);
},
@@ -59,6 +63,13 @@ export default function(commander, filenames, opts) {
return path.join(commander.outDir, filename);
}
function outputDestFolder(outDir) {
const outDirPath = path.resolve(outDir);
if (!fs.existsSync(outDirPath)) {
fs.mkdirSync(outDirPath);
}
}
function handleFile(src, filename, base, callback) {
if (typeof base === "function") {
callback = base;
@@ -78,6 +89,11 @@ export default function(commander, filenames, opts) {
}
function sequentialHandleFile(files, dirname, index, callback) {
if (files.length === 0) {
outputDestFolder(commander.outDir);
return;
}
if (typeof index === "function") {
callback = index;
index = 0;
@@ -125,10 +141,17 @@ export default function(commander, filenames, opts) {
const filename = filenames[index];
handle(filename, function(err) {
if (err) throw err;
if (err) throw new Error(err);
index++;
if (index !== filenames.length) {
sequentialHandle(filenames, index);
} else {
util.log(
`🎉 Successfully compiled ${compiledFiles} ${
compiledFiles > 1 ? "files" : "file"
} with Babel.`,
true,
);
}
});
}

View File

@@ -16,7 +16,10 @@ export default function(commander, filenames, opts) {
const buildResult = function() {
const map = new sourceMap.SourceMapGenerator({
file: path.basename(commander.outFile || "") || "stdout",
file:
commander.sourceMapTarget ||
path.basename(commander.outFile || "") ||
"stdout",
sourceRoot: opts.sourceRoot,
});

View File

@@ -32,7 +32,6 @@ function collect(value, previousValue): Array<string> {
return previousValue ? previousValue.concat(values) : values;
}
/* eslint-disable max-len */
// Standard Babel input configs.
commander.option(
"-f, --filename [filename]",
@@ -163,12 +162,11 @@ commander.option(
"--include-dotfiles",
"Include dotfiles when compiling and copying non-compilable files",
);
commander.option("-q, --quiet", "Don't log anything");
commander.option("--verbose", "Log everything");
commander.option(
"--delete-dir-on-start",
"Delete the out directory before compilation",
);
/* eslint-enable max-len */
commander.version(pkg.version + " (@babel/core " + version + ")");
commander.usage("[options] <files ...>");
@@ -221,6 +219,17 @@ if (commander.deleteDirOnStart && !commander.outDir) {
errors.push("--delete-dir-on-start requires --out-dir");
}
if (
!commander.outDir &&
filenames.length === 0 &&
typeof commander.filename !== "string" &&
commander.babelrc !== false
) {
errors.push(
"stdin compilation requires either -f/--filename [filename] or --no-babelrc",
);
}
if (errors.length) {
console.error(errors.join(". "));
process.exit(2);
@@ -243,11 +252,12 @@ delete opts.outFile;
delete opts.outDir;
delete opts.copyFiles;
delete opts.includeDotfiles;
delete opts.quiet;
delete opts.verbose;
delete opts.configFile;
delete opts.deleteDirOnStart;
delete opts.keepFileExtension;
delete opts.relative;
delete opts.sourceMapTarget;
// Commander will default the "--no-" arguments to true, but we want to leave them undefined so that
// @babel/core can handle the default-assignment logic on its own.

View File

@@ -46,8 +46,8 @@ export function addSourceMappingUrl(code, loc) {
return code + "\n//# sourceMappingURL=" + path.basename(loc);
}
export function log(msg) {
if (!commander.quiet) console.log(msg);
export function log(msg, force) {
if (force === true || commander.verbose) console.log(msg);
}
export function transform(filename, code, opts, callback) {
@@ -63,7 +63,7 @@ export function compile(filename, opts, callback) {
if (err) {
if (commander.watch) {
console.error(err);
return callback(null, { ignored: true });
return callback(null, null);
} else {
return callback(err);
}

View File

@@ -1,3 +1,3 @@
{
"args": ["--config-file", "../.othername_babelrc"]
}
"args": ["--config-file", "../.othername_babelrc", "-f", "file.js"]
}

View File

@@ -4,6 +4,7 @@
"--out-dir", "lib",
"--copy-files",
"--include-dotfiles",
"--ignore", "src/foo"
"--ignore", "src/foo",
"--verbose"
]
}

View File

@@ -1 +1,2 @@
src/index.js -> lib/index.js
🎉 Successfully compiled 1 file with Babel.

View File

@@ -4,6 +4,7 @@
"--out-dir", "lib",
"--copy-files",
"--include-dotfiles",
"--only", "src/foo"
"--only", "src/foo",
"--verbose"
]
}

View File

@@ -1,2 +1,3 @@
src/foo/.foo.js -> lib/foo/.foo.js
src/foo/bar.js -> lib/foo/bar.js
🎉 Successfully compiled 2 files with Babel.

View File

@@ -1,3 +1,3 @@
{
"args": ["src", "--out-dir", "lib", "--copy-files", "--include-dotfiles"]
"args": ["src", "--out-dir", "lib", "--copy-files", "--include-dotfiles", "--verbose"]
}

View File

@@ -1,3 +1,4 @@
src/.foo.js -> lib/.foo.js
src/bar/index.js -> lib/bar/index.js
src/foo/foo.js -> lib/foo/foo.js
🎉 Successfully compiled 3 files with Babel.

View File

@@ -3,6 +3,7 @@
"src",
"--out-dir", "lib",
"--copy-files",
"--ignore", "src/foo/*"
"--ignore", "src/foo/*",
"--verbose"
]
}

View File

@@ -1 +1,2 @@
src/index.js -> lib/index.js
🎉 Successfully compiled 1 file with Babel.

View File

@@ -3,6 +3,7 @@
"src",
"--out-dir", "lib",
"--copy-files",
"--only", "src/foo/*"
"--only", "src/foo/*",
"--verbose"
]
}

View File

@@ -1 +1,2 @@
src/foo/bar.js -> lib/foo/bar.js
🎉 Successfully compiled 1 file with Babel.

View File

@@ -1,3 +1,3 @@
{
"args": ["src", "--out-dir", "lib", "--copy-files"]
"args": ["src", "--out-dir", "lib", "--copy-files", "--verbose"]
}

View File

@@ -1,2 +1,3 @@
src/bar/index.js -> lib/bar/index.js
src/foo/foo.js -> lib/foo/foo.js
🎉 Successfully compiled 2 files with Babel.

View File

@@ -1,3 +1,3 @@
{
"args": ["src", "--out-dir", "lib", "--ignore", "src/bar"]
"args": ["src", "--out-dir", "lib", "--ignore", "src/bar", "--verbose"]
}

View File

@@ -1 +1,2 @@
src/foobar/foo.js -> lib/foobar/foo.js
🎉 Successfully compiled 1 file with Babel.

View File

@@ -1,3 +1,3 @@
{
"args": ["src", "--out-dir", "lib", "--ignore", "**/*.foo.js"]
"args": ["src", "--out-dir", "lib", "--ignore", "**/*.foo.js", "--verbose"]
}

View File

@@ -2,3 +2,4 @@ src/a.js -> lib/a.js
src/b.js -> lib/b.js
src/baz/c.js -> lib/baz/c.js
src/foo.js -> lib/foo.js
🎉 Successfully compiled 4 files with Babel.

View File

@@ -1,3 +1,3 @@
{
"args": ["src", "--out-dir", "lib", "--ignore", "src/foo/*"]
"args": ["src", "--out-dir", "lib", "--ignore", "src/foo/*", "--verbose"]
}

View File

@@ -1 +1,2 @@
src/bar/index.js -> lib/bar/index.js
🎉 Successfully compiled 1 file with Babel.

View File

@@ -1,3 +1,3 @@
{
"args": ["src", "--out-dir", "lib", "--only", "**/*.foo.js"]
"args": ["src", "--out-dir", "lib", "--only", "**/*.foo.js", "--verbose"]
}

View File

@@ -1,2 +1,3 @@
src/a.foo.js -> lib/a.foo.js
src/baz/b.foo.js -> lib/baz/b.foo.js
🎉 Successfully compiled 2 files with Babel.

View File

@@ -1,3 +1,3 @@
{
"args": ["src", "--out-dir", "lib", "--only", "src/bar/*"]
"args": ["src", "--out-dir", "lib", "--only", "src/bar/*", "--verbose"]
}

View File

@@ -1 +1,2 @@
src/bar/index.js -> lib/bar/index.js
🎉 Successfully compiled 1 file with Babel.

View File

@@ -1,3 +1,3 @@
{
"args": ["src", "--out-dir", "lib", "--copy-files"]
"args": ["src", "--out-dir", "lib", "--copy-files", "--verbose"]
}

View File

@@ -1 +1,2 @@
src/foo.js -> lib/foo.js
🎉 Successfully compiled 1 file with Babel.

View File

@@ -1,3 +1,3 @@
{
"args": ["src", "--out-dir", "lib", "--keep-file-extension"]
"args": ["src", "--out-dir", "lib", "--keep-file-extension", "--verbose"]
}

View File

@@ -1,2 +1,3 @@
src/bar.mjs -> lib/bar.mjs
src/foo.js -> lib/foo.js
🎉 Successfully compiled 2 files with Babel.

View File

@@ -1,3 +1,3 @@
{
"args": ["**/src", "--out-dir", "../lib", "--relative"]
"args": ["**/src", "--out-dir", "../lib", "--relative", "--verbose"]
}

View File

@@ -2,3 +2,4 @@ package1/src/bar/bar1.js -> package1/lib/bar/bar1.js
package1/src/foo1.js -> package1/lib/foo1.js
package2/src/bar/bar2.js -> package2/lib/bar/bar2.js
package2/src/foo2.js -> package2/lib/foo2.js
🎉 Successfully compiled 4 files with Babel.

View File

@@ -1,3 +1,3 @@
{
"args": ["src", "--source-maps", "inline", "--out-dir", "lib"]
"args": ["src", "--source-maps", "inline", "--out-dir", "lib", "--verbose"]
}

View File

@@ -7,4 +7,4 @@ function _classCallCheck(instance, Constructor) { if (!_instanceof(instance, Con
var Test = function Test() {
_classCallCheck(this, Test);
};
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9iYXIvYmFyLmpzIl0sIm5hbWVzIjpbIlRlc3QiXSwibWFwcGluZ3MiOiI7Ozs7OztJQUFNQSxJIiwiZmlsZSI6ImJhci5qcyIsInNvdXJjZXNDb250ZW50IjpbImNsYXNzIFRlc3Qge1xuXG59Il19
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9iYXIvYmFyLmpzIl0sIm5hbWVzIjpbIlRlc3QiXSwibWFwcGluZ3MiOiI7Ozs7OztJQUFNQSxJIiwic291cmNlc0NvbnRlbnQiOlsiY2xhc3MgVGVzdCB7XG5cbn0iXX0=

View File

@@ -3,4 +3,4 @@
arr.map(function (x) {
return x * MULTIPLIER;
});
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uL3NyYy9mb28uanMiXSwibmFtZXMiOlsiYXJyIiwibWFwIiwieCIsIk1VTFRJUExJRVIiXSwibWFwcGluZ3MiOiI7O0FBQUFBLElBQUlDLEdBQUosQ0FBUTtBQUFBLFNBQUtDLElBQUlDLFVBQVQ7QUFBQSxDQUFSIiwiZmlsZSI6ImZvby5qcyIsInNvdXJjZXNDb250ZW50IjpbImFyci5tYXAoeCA9PiB4ICogTVVMVElQTElFUik7Il19
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uL3NyYy9mb28uanMiXSwibmFtZXMiOlsiYXJyIiwibWFwIiwieCIsIk1VTFRJUExJRVIiXSwibWFwcGluZ3MiOiI7O0FBQUFBLElBQUlDLEdBQUosQ0FBUTtBQUFBLFNBQUtDLElBQUlDLFVBQVQ7QUFBQSxDQUFSIiwic291cmNlc0NvbnRlbnQiOlsiYXJyLm1hcCh4ID0+IHggKiBNVUxUSVBMSUVSKTsiXX0=

View File

@@ -1,2 +1,3 @@
src/bar/bar.js -> lib/bar/bar.js
src/foo.js -> lib/foo.js
🎉 Successfully compiled 2 files with Babel.

View File

@@ -1,3 +1,3 @@
{
"args": ["src", "--source-maps", "--out-dir", "lib"]
"args": ["src", "--source-maps", "--out-dir", "lib", "--verbose"]
}

View File

@@ -1 +1 @@
{"version":3,"sources":["../../src/bar/bar.js"],"names":["Test"],"mappings":";;;;;;IAAMA,I","file":"bar.js","sourcesContent":["class Test {\n\n}"]}
{"version":3,"sources":["../../src/bar/bar.js"],"names":["Test"],"mappings":";;;;;;IAAMA,I","sourcesContent":["class Test {\n\n}"],"file":"bar.js"}

View File

@@ -1 +1 @@
{"version":3,"sources":["../src/foo.js"],"names":["arr","map","x","MULTIPLIER"],"mappings":";;AAAAA,IAAIC,GAAJ,CAAQ;AAAA,SAAKC,IAAIC,UAAT;AAAA,CAAR","file":"foo.js","sourcesContent":["arr.map(x => x * MULTIPLIER);"]}
{"version":3,"sources":["../src/foo.js"],"names":["arr","map","x","MULTIPLIER"],"mappings":";;AAAAA,IAAIC,GAAJ,CAAQ;AAAA,SAAKC,IAAIC,UAAT;AAAA,CAAR","sourcesContent":["arr.map(x => x * MULTIPLIER);"],"file":"foo.js"}

View File

@@ -1,2 +1,3 @@
src/bar/bar.js -> lib/bar/bar.js
src/foo.js -> lib/foo.js
🎉 Successfully compiled 2 files with Babel.

View File

@@ -0,0 +1,3 @@
class Test {
}

View File

@@ -0,0 +1 @@
arr.map(x => x * MULTIPLIER);

View File

@@ -0,0 +1,3 @@
{
"args": ["src", "--out-dir", "lib", "--verbose"]
}

View File

@@ -0,0 +1,9 @@
"use strict";
function _instanceof(left, right) { if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { return right[Symbol.hasInstance](left); } else { return left instanceof right; } }
function _classCallCheck(instance, Constructor) { if (!_instanceof(instance, Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Test = function Test() {
_classCallCheck(this, Test);
};

View File

@@ -0,0 +1,5 @@
"use strict";
arr.map(function (x) {
return x * MULTIPLIER;
});

View File

@@ -0,0 +1,3 @@
src/bar/bar.js -> lib/bar/bar.js
src/foo.js -> lib/foo.js
🎉 Successfully compiled 2 files with Babel.

View File

@@ -1,2 +1 @@
src/bar/bar.js -> lib/bar/bar.js
src/foo.js -> lib/foo.js
🎉 Successfully compiled 2 files with Babel.

View File

@@ -0,0 +1,3 @@
{
"args": ["src", "--out-dir", "lib"]
}

View File

@@ -1,3 +1,3 @@
{
"args": ["src/foo.js", "--out-dir", "../lib", "--relative"]
"args": ["src/foo.js", "--out-dir", "../lib", "--relative", "--verbose"]
}

View File

@@ -1 +1,2 @@
src/foo.js -> lib/foo.js
🎉 Successfully compiled 1 file with Babel.

View File

@@ -1,3 +1,3 @@
{
"args": ["src/foo.js", "--out-dir", "lib"]
"args": ["src/foo.js", "--out-dir", "lib", "--verbose"]
}

View File

@@ -1 +1,2 @@
src/foo.js -> lib/foo.js
🎉 Successfully compiled 1 file with Babel.

View File

@@ -1,3 +1,3 @@
{
"args": ["--out-file", "script.js"]
"args": ["--out-file", "script.js", "-f", "file.js"]
}

View File

@@ -0,0 +1,3 @@
{
"args": ["-f", "file.js"]
}

View File

@@ -122,7 +122,13 @@ const buildTest = function(binName, testName, opts) {
const binLoc = path.join(__dirname, "../lib", binName);
return function(callback) {
clear();
const dir = process.cwd();
process.chdir(__dirname);
if (fs.existsSync(tmpLoc)) rimraf.sync(tmpLoc);
fs.mkdirSync(tmpLoc);
process.chdir(tmpLoc);
saveInFiles(opts.inFiles);
let args = [binLoc];
@@ -160,6 +166,7 @@ const buildTest = function(binName, testName, opts) {
args.map(arg => `"${arg}"`).join(" ") + ": " + err.message;
}
process.chdir(dir);
callback(err);
});
@@ -170,13 +177,6 @@ const buildTest = function(binName, testName, opts) {
};
};
const clear = function() {
process.chdir(__dirname);
if (fs.existsSync(tmpLoc)) rimraf.sync(tmpLoc);
fs.mkdirSync(tmpLoc);
process.chdir(tmpLoc);
};
fs.readdirSync(fixtureLoc).forEach(function(binName) {
if (binName[0] === ".") return;

View File

@@ -68,6 +68,7 @@ console.log(result);
Toggles syntax highlighting the code as JavaScript for terminals.
### `linesAbove`
`number`, defaults to `2`.
@@ -86,6 +87,21 @@ Adjust the number of lines to show below the error.
Enable this to forcibly syntax highlight the code as JavaScript (for non-terminals); overrides `highlightCode`.
### `message`
`string`, otherwise nothing
Pass in a string to be displayed inline (if possible) next to the highlighted
location in the code. If it can't be positioned inline, it will be placed above
the code frame.
```
1 | class Foo {
> 2 | constructor()
| ^ Missing {
3 | };
```
## Upgrading from prior versions
Prior to version 7, the only API exposed by this module was for a single line and optional column pointer. The old API will now log a deprecation warning.

View File

@@ -1,6 +1,6 @@
{
"name": "@babel/code-frame",
"version": "7.0.0-beta.38",
"version": "7.0.0-beta.44",
"description": "Generate errors that contain a code frame that point to source locations.",
"author": "Sebastian McKenzie <sebmck@gmail.com>",
"homepage": "https://babeljs.io/",
@@ -8,11 +8,10 @@
"repository": "https://github.com/babel/babel/tree/master/packages/babel-code-frame",
"main": "lib/index.js",
"dependencies": {
"chalk": "^2.0.0",
"esutils": "^2.0.2",
"js-tokens": "^3.0.0"
"@babel/highlight": "7.0.0-beta.44"
},
"devDependencies": {
"chalk": "^2.0.0",
"strip-ansi": "^4.0.0"
}
}

View File

@@ -1,6 +1,4 @@
import jsTokens, { matchToToken } from "js-tokens";
import esutils from "esutils";
import Chalk from "chalk";
import highlight, { shouldHighlight, getChalk } from "@babel/highlight";
let deprecationWarningShown = false;
@@ -15,23 +13,13 @@ type NodeLocation = {
};
/**
* Chalk styles for token types.
* Chalk styles for code frame token types.
*/
function getDefs(chalk) {
return {
keyword: chalk.cyan,
capitalized: chalk.yellow,
jsx_tag: chalk.yellow,
punctuator: chalk.yellow,
// bracket: intentionally omitted.
number: chalk.magenta,
string: chalk.green,
regex: chalk.magenta,
comment: chalk.grey,
invalid: chalk.white.bgRed.bold,
gutter: chalk.grey,
marker: chalk.red.bold,
message: chalk.red.bold,
};
}
@@ -41,76 +29,6 @@ function getDefs(chalk) {
const NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
/**
* RegExp to test for what seems to be a JSX tag name.
*/
const JSX_TAG = /^[a-z][\w-]*$/i;
/**
* RegExp to test for the three types of brackets.
*/
const BRACKET = /^[()[\]{}]$/;
/**
* Get the type of token, specifying punctuator type.
*/
function getTokenType(match) {
const [offset, text] = match.slice(-2);
const token = matchToToken(match);
if (token.type === "name") {
if (esutils.keyword.isReservedWordES6(token.value)) {
return "keyword";
}
if (
JSX_TAG.test(token.value) &&
(text[offset - 1] === "<" || text.substr(offset - 2, 2) == "</")
) {
return "jsx_tag";
}
if (token.value[0] !== token.value[0].toLowerCase()) {
return "capitalized";
}
}
if (token.type === "punctuator" && BRACKET.test(token.value)) {
return "bracket";
}
if (
token.type === "invalid" &&
(token.value === "@" || token.value === "#")
) {
return "punctuator";
}
return token.type;
}
/**
* Highlight `text`.
*/
function highlight(defs: Object, text: string) {
return text.replace(jsTokens, function(...args) {
const type = getTokenType(args);
const colorize = defs[type];
if (colorize) {
return args[0]
.split(NEWLINE)
.map(str => colorize(str))
.join("\n");
} else {
return args[0];
}
});
}
/**
* Extract what lines should be marked and highlighted.
*/
@@ -126,9 +44,7 @@ function getMarkerLines(
loc.start,
);
const endLoc: Location = Object.assign({}, startLoc, loc.end);
const linesAbove = opts.linesAbove || 2;
const linesBelow = opts.linesBelow || 3;
const { linesAbove = 2, linesBelow = 3 } = opts || {};
const startLine = startLoc.line;
const startColumn = startLoc.column;
const endLine = endLoc.line;
@@ -187,29 +103,28 @@ export function codeFrameColumns(
opts: Object = {},
): string {
const highlighted =
(opts.highlightCode && Chalk.supportsColor) || opts.forceColor;
let chalk = Chalk;
if (opts.forceColor) {
chalk = new Chalk.constructor({ enabled: true, level: 1 });
}
(opts.highlightCode || opts.forceColor) && shouldHighlight(opts);
const chalk = getChalk(opts);
const defs = getDefs(chalk);
const maybeHighlight = (chalkFn, string) => {
return highlighted ? chalkFn(string) : string;
};
const defs = getDefs(chalk);
if (highlighted) rawLines = highlight(defs, rawLines);
if (highlighted) rawLines = highlight(rawLines, opts);
const lines = rawLines.split(NEWLINE);
const { start, end, markerLines } = getMarkerLines(loc, lines, opts);
const hasColumns = loc.start && typeof loc.start.column === "number";
const numberMaxWidth = String(end).length;
const frame = lines
let frame = lines
.slice(start, end)
.map((line, index) => {
const number = start + 1 + index;
const paddedNumber = ` ${number}`.slice(-numberMaxWidth);
const gutter = ` ${paddedNumber} | `;
const hasMarker = markerLines[number];
const lastMarkerLine = !markerLines[number + 1];
if (hasMarker) {
let markerLine = "";
if (Array.isArray(hasMarker)) {
@@ -224,6 +139,10 @@ export function codeFrameColumns(
markerSpacing,
maybeHighlight(defs.marker, "^").repeat(numberOfMarkers),
].join("");
if (lastMarkerLine && opts.message) {
markerLine += " " + maybeHighlight(defs.message, opts.message);
}
}
return [
maybeHighlight(defs.marker, ">"),
@@ -237,6 +156,10 @@ export function codeFrameColumns(
})
.join("\n");
if (opts.message && !hasColumns) {
frame = `${" ".repeat(numberMaxWidth + 1)}${opts.message}\n${frame}`;
}
if (highlighted) {
return chalk.reset(frame);
} else {
@@ -257,15 +180,17 @@ export default function(
if (!deprecationWarningShown) {
deprecationWarningShown = true;
const deprecationError = new Error(
"Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`.",
);
deprecationError.name = "DeprecationWarning";
const message =
"Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`.";
if (process.emitWarning) {
process.emitWarning(deprecationError);
// A string is directly supplied to emitWarning, because when supplying an
// Error object node throws in the tests because of different contexts
process.emitWarning(message, "DeprecationWarning");
} else {
console.warn(deprecationError);
const deprecationError = new Error(message);
deprecationError.name = "DeprecationWarning";
console.warn(new Error(message));
}
}

View File

@@ -1,13 +1,11 @@
import assert from "assert";
import chalk from "chalk";
import stripAnsi from "strip-ansi";
import codeFrame, { codeFrameColumns } from "..";
describe("@babel/code-frame", function() {
it("basic usage", function() {
test("basic usage", function() {
const rawLines = ["class Foo {", " constructor()", "};"].join("\n");
assert.equal(
codeFrame(rawLines, 2, 16),
expect(codeFrame(rawLines, 2, 16)).toEqual(
[
" 1 | class Foo {",
"> 2 | constructor()",
@@ -17,15 +15,14 @@ describe("@babel/code-frame", function() {
);
});
it("optional column number", function() {
test("optional column number", function() {
const rawLines = ["class Foo {", " constructor()", "};"].join("\n");
assert.equal(
codeFrame(rawLines, 2, null),
expect(codeFrame(rawLines, 2, null)).toEqual(
[" 1 | class Foo {", "> 2 | constructor()", " 3 | };"].join("\n"),
);
});
it("maximum context lines and padding", function() {
test("maximum context lines and padding", function() {
const rawLines = [
"/**",
" * Sums two numbers.",
@@ -39,8 +36,7 @@ describe("@babel/code-frame", function() {
" return a + b",
"}",
].join("\n");
assert.equal(
codeFrame(rawLines, 7, 2),
expect(codeFrame(rawLines, 7, 2)).toEqual(
[
" 5 | * @param b Number",
" 6 | * @returns Number",
@@ -53,7 +49,7 @@ describe("@babel/code-frame", function() {
);
});
it("no unnecessary padding due to one-off errors", function() {
test("no unnecessary padding due to one-off errors", function() {
const rawLines = [
"/**",
" * Sums two numbers.",
@@ -67,8 +63,7 @@ describe("@babel/code-frame", function() {
" return a + b",
"}",
].join("\n");
assert.equal(
codeFrame(rawLines, 6, 2),
expect(codeFrame(rawLines, 6, 2)).toEqual(
[
" 4 | * @param a Number",
" 5 | * @param b Number",
@@ -81,14 +76,13 @@ describe("@babel/code-frame", function() {
);
});
it("tabs", function() {
test("tabs", function() {
const rawLines = [
"\tclass Foo {",
"\t \t\t constructor\t(\t)",
"\t};",
].join("\n");
assert.equal(
codeFrame(rawLines, 2, 25),
expect(codeFrame(rawLines, 2, 25)).toEqual(
[
" 1 | \tclass Foo {",
"> 2 | \t \t\t constructor\t(\t)",
@@ -98,18 +92,17 @@ describe("@babel/code-frame", function() {
);
});
it("opts.highlightCode", function() {
test("opts.highlightCode", function() {
const rawLines = "console.log('babel')";
const result = codeFrame(rawLines, 1, 9, { highlightCode: true });
const stripped = stripAnsi(result);
assert.ok(result.length > stripped.length);
assert.equal(
stripped,
expect(result.length).toBeGreaterThan(stripped.length);
expect(stripped).toEqual(
["> 1 | console.log('babel')", " | ^"].join("\n"),
);
});
it("opts.linesAbove", function() {
test("opts.linesAbove", function() {
const rawLines = [
"/**",
" * Sums two numbers.",
@@ -123,8 +116,7 @@ describe("@babel/code-frame", function() {
" return a + b",
"}",
].join("\n");
assert.equal(
codeFrame(rawLines, 7, 2, { linesAbove: 1 }),
expect(codeFrame(rawLines, 7, 2, { linesAbove: 1 })).toEqual(
[
" 6 | * @returns Number",
"> 7 | */",
@@ -136,7 +128,7 @@ describe("@babel/code-frame", function() {
);
});
it("opts.linesBelow", function() {
test("opts.linesBelow", function() {
const rawLines = [
"/**",
" * Sums two numbers.",
@@ -150,8 +142,7 @@ describe("@babel/code-frame", function() {
" return a + b",
"}",
].join("\n");
assert.equal(
codeFrame(rawLines, 7, 2, { linesBelow: 1 }),
expect(codeFrame(rawLines, 7, 2, { linesBelow: 1 })).toEqual(
[
" 5 | * @param b Number",
" 6 | * @returns Number",
@@ -162,7 +153,7 @@ describe("@babel/code-frame", function() {
);
});
it("opts.linesAbove and opts.linesBelow", function() {
test("opts.linesAbove and opts.linesBelow", function() {
const rawLines = [
"/**",
" * Sums two numbers.",
@@ -176,25 +167,75 @@ describe("@babel/code-frame", function() {
" return a + b",
"}",
].join("\n");
assert.equal(
codeFrame(rawLines, 7, 2, { linesAbove: 1, linesBelow: 1 }),
expect(codeFrame(rawLines, 7, 2, { linesAbove: 1, linesBelow: 1 })).toEqual(
[" 6 | * @returns Number", "> 7 | */", " | ^", " 8 | "].join(
"\n",
),
);
});
it("opts.forceColor", function() {
test("opts.linesAbove no lines above", function() {
const rawLines = [
"class Foo {",
" constructor() {",
" console.log(arguments);",
" }",
"};",
].join("\n");
expect(
codeFrameColumns(rawLines, { start: { line: 2 } }, { linesAbove: 0 }),
).toEqual(
[
"> 2 | constructor() {",
" 3 | console.log(arguments);",
" 4 | }",
" 5 | };",
].join("\n"),
);
});
test("opts.linesBelow no lines below", function() {
const rawLines = [
"class Foo {",
" constructor() {",
" console.log(arguments);",
" }",
"};",
].join("\n");
expect(
codeFrameColumns(rawLines, { start: { line: 2 } }, { linesBelow: 0 }),
).toEqual([" 1 | class Foo {", "> 2 | constructor() {"].join("\n"));
});
test("opts.linesBelow single line", function() {
const rawLines = [
"class Foo {",
" constructor() {",
" console.log(arguments);",
" }",
"};",
].join("\n");
expect(
codeFrameColumns(
rawLines,
{ start: { line: 2 } },
{ linesAbove: 0, linesBelow: 0 },
),
).toEqual(["> 2 | constructor() {"].join("\n"));
});
test("opts.forceColor", function() {
const marker = chalk.red.bold;
const gutter = chalk.grey;
const rawLines = ["", "", "", ""].join("\n");
assert.equal(
expect(
codeFrame(rawLines, 3, null, {
linesAbove: 1,
linesBelow: 1,
forceColor: true,
}),
).toEqual(
chalk.reset(
[
" " + gutter(" 2 | "),
@@ -205,10 +246,11 @@ describe("@babel/code-frame", function() {
);
});
it("basic usage, new API", function() {
test("basic usage, new API", function() {
const rawLines = ["class Foo {", " constructor()", "};"].join("\n");
assert.equal(
expect(
codeFrameColumns(rawLines, { start: { line: 2, column: 16 } }),
).toEqual(
[
" 1 | class Foo {",
"> 2 | constructor()",
@@ -218,13 +260,14 @@ describe("@babel/code-frame", function() {
);
});
it("mark multiple columns", function() {
test("mark multiple columns", function() {
const rawLines = ["class Foo {", " constructor()", "};"].join("\n");
assert.equal(
expect(
codeFrameColumns(rawLines, {
start: { line: 2, column: 3 },
end: { line: 2, column: 16 },
}),
).toEqual(
[
" 1 | class Foo {",
"> 2 | constructor()",
@@ -234,15 +277,16 @@ describe("@babel/code-frame", function() {
);
});
it("mark multiple columns across lines", function() {
test("mark multiple columns across lines", function() {
const rawLines = ["class Foo {", " constructor() {", " }", "};"].join(
"\n",
);
assert.equal(
expect(
codeFrameColumns(rawLines, {
start: { line: 2, column: 17 },
end: { line: 3, column: 3 },
}),
).toEqual(
[
" 1 | class Foo {",
"> 2 | constructor() {",
@@ -254,7 +298,7 @@ describe("@babel/code-frame", function() {
);
});
it("mark multiple columns across multiple lines", function() {
test("mark multiple columns across multiple lines", function() {
const rawLines = [
"class Foo {",
" constructor() {",
@@ -262,11 +306,12 @@ describe("@babel/code-frame", function() {
" }",
"};",
].join("\n");
assert.equal(
expect(
codeFrameColumns(rawLines, {
start: { line: 2, column: 17 },
end: { line: 4, column: 3 },
}),
).toEqual(
[
" 1 | class Foo {",
"> 2 | constructor() {",
@@ -280,7 +325,7 @@ describe("@babel/code-frame", function() {
);
});
it("mark across multiple lines without columns", function() {
test("mark across multiple lines without columns", function() {
const rawLines = [
"class Foo {",
" constructor() {",
@@ -288,8 +333,9 @@ describe("@babel/code-frame", function() {
" }",
"};",
].join("\n");
assert.equal(
expect(
codeFrameColumns(rawLines, { start: { line: 2 }, end: { line: 4 } }),
).toEqual(
[
" 1 | class Foo {",
"> 2 | constructor() {",
@@ -299,4 +345,105 @@ describe("@babel/code-frame", function() {
].join("\n"),
);
});
test("opts.message", function() {
const rawLines = ["class Foo {", " constructor()", "};"].join("\n");
expect(
codeFrameColumns(
rawLines,
{ start: { line: 2, column: 16 } },
{
message: "Missing {",
},
),
).toEqual(
[
" 1 | class Foo {",
"> 2 | constructor()",
" | ^ Missing {",
" 3 | };",
].join("\n"),
);
});
test("opts.message without column", function() {
const rawLines = ["class Foo {", " constructor()", "};"].join("\n");
expect(
codeFrameColumns(
rawLines,
{ start: { line: 2 } },
{
message: "Missing {",
},
),
).toEqual(
[
" Missing {",
" 1 | class Foo {",
"> 2 | constructor()",
" 3 | };",
].join("\n"),
);
});
test("opts.message with multiple lines", function() {
const rawLines = [
"class Foo {",
" constructor() {",
" console.log(arguments);",
" }",
"};",
].join("\n");
expect(
codeFrameColumns(
rawLines,
{
start: { line: 2, column: 17 },
end: { line: 4, column: 3 },
},
{
message: "something about the constructor body",
},
),
).toEqual(
[
" 1 | class Foo {",
"> 2 | constructor() {",
" | ^",
"> 3 | console.log(arguments);",
" | ^^^^^^^^^^^^^^^^^^^^^^^^^^^",
"> 4 | }",
" | ^^^ something about the constructor body",
" 5 | };",
].join("\n"),
);
});
test("opts.message with multiple lines without columns", function() {
const rawLines = [
"class Foo {",
" constructor() {",
" console.log(arguments);",
" }",
"};",
].join("\n");
expect(
codeFrameColumns(
rawLines,
{ start: { line: 2 }, end: { line: 4 } },
{
message: "something about the constructor body",
},
),
).toEqual(
[
" something about the constructor body",
" 1 | class Foo {",
"> 2 | constructor() {",
"> 3 | console.log(arguments);",
"> 4 | }",
" 5 | };",
].join("\n"),
);
});
});

View File

@@ -93,7 +93,7 @@ babel.transformFileSync("filename.js", options).code;
```
## babel.transformFromAst(ast: Object, code?: string, [options?](#options): Object, callback: Function)
## babel.transformFromAst(ast: Object, code?: string, [options?](#options): Object, callback: Function): FileNode | null
Given an [AST](https://astexplorer.net/), transform it.
@@ -123,6 +123,79 @@ const parsedAst = babylon.parse(sourceCode, { allowReturnOutsideFunction: true }
const { code, map, ast } = babel.transformFromAstSync(parsedAst, sourceCode, options);
```
## babel.parse(code: string, [options?](#options): Object)
Given some code, parse it using Babel's standard behavior. Referenced presets and
plugins will be loaded such that optional syntax plugins are automatically
enabled.
## Advanced APIs
Many systems that wrap Babel like to automatically inject plugins and presets,
or override options. To accomplish this goal, Babel exposes several functions
that aid in loading the configuration part-way without transforming.
### babel.loadOptions([options?](#options): Object)
Resolve Babel's options fully, resulting in an options object where:
* `opts.plugins` is a full list of `Plugin` instances.
* `opts.presets` is empty and all presets are flattened into `opts`.
* It can be safely passed back to Babel. Fields like `babelrc` have been set to
false so that later calls to Babel will not make a second attempt to load
config files.
`Plugin` instances aren't meant to be manipulated directly, but often
callers will serialize this `opts` to JSON to use it as a cache key representing
the options Babel has received. Caching on this isn't 100% guaranteed to
invalidate properly, but it is the best we have at the moment.
### babel.loadPartialConfig([options?](#options): Object): PartialConfig
To allow systems to easily manipulate and validate a user's config, this function
resolves the plugins and presets and proceeds no further. The expectation is
that callers will take the config's `.options`, manipulate it as then see fit
and pass it back to Babel again.
* `babelrc: string | void` - The path of the `.babelrc` file, if there was one.
* `babelignore: string | void` - The path of the `.babelignore` file, if there was one.
* `options: ValidatedOptions` - The partially resolved options, which can be manipulated and passed back to Babel again.
* `plugins: Array<ConfigItem>` - See below.
* `presets: Array<ConfigItem>` - See below.
* It can be safely passed back to Babel. Fields like `babelrc` have been set
to false so that later calls to Babel will not make a second attempt to
load config files.
* `hasFilesystemConfig(): boolean` - Check if the resolved config loaded any settings from the filesystem.
[`ConfigItem`](#configitem-type) instances expose properties to introspect the values, but each
item should be treated as immutable. If changes are desired, the item should be
removed from the list and replaced with either a normal Babel config value, or
with a replacement item created by `babel.createConfigItem`. See that
function for information about `ConfigItem` fields.
### babel.createConfigItem(value: string | {} | Function | [string | {} | Function, {} | void], { dirname?: string, type?: "preset" | "plugin" }): ConfigItem
Allows build tooling to create and cache config items up front. If this function
is called multiple times for a given plugin, Babel will call the plugin's function itself
multiple times. If you have a clear set of expected plugins and presets to
inject, pre-constructing the config items would be recommended.
### `ConfigItem` type
Each `ConfigItem` exposes all of the information Babel knows. The fields are:
* `value: {} | Function` - The resolved value of the plugin.
* `options: {} | void` - The options object passed to the plugin.
* `dirname: string` - The path that the options are relative to.
* `name: string | void` - The name that the user gave the plugin instance, e.g. `plugins: [ ['env', {}, 'my-env'] ]`
* `file: Object | void` - Information about the plugin's file, if Babel knows it.
* `request: string` - The file that the user requested, e.g. `"@babel/env"`
* `resolved: string` - The full path of the resolved file, e.g. `"/tmp/node_modules/@babel/preset-env/lib/index.js"`
## Options
@@ -169,7 +242,6 @@ Following is a table of the options you can use:
| `shouldPrintComment` | `null` | An optional callback that controls whether a comment should be output or not. Called as `shouldPrintComment(commentContents)`. **NOTE:** This overrides the `comment` option when used |
| `sourceFileName` | `(filenameRelative)` | Set `sources[0]` on returned source map |
| `sourceMaps` | `false` | If truthy, adds a `map` property to returned output. If set to `"inline"`, a comment with a sourceMappingURL directive is added to the bottom of the returned code. If set to `"both"` then a `map` property is returned as well as a source map comment appended. **This does not emit sourcemap files by itself!** To have sourcemaps emitted using the CLI, you must pass it the `--source-maps` option |
| `sourceMapTarget` | `(filenameRelative)` | Set `file` on returned source map |
| `sourceRoot` | `(moduleRoot)` | The root from which all sources are relative |
| `sourceType` | `"module"` | Indicate the mode the code should be parsed in. Can be one of "script", "module", or "unambiguous". `"unambiguous"` will make Babel attempt to _guess_, based on the presence of ES6 `import` or `export` statements. Files with ES6 `import`s and `export`s are considered `"module"` and are otherwise `"script"`. |
| `wrapPluginVisitorMethod`| `null` | An optional callback that can be used to wrap visitor methods. **NOTE:** This is useful for things like introspection, and not really needed for implementing anything. Called as `wrapPluginVisitorMethod(pluginAlias, visitorType, callback)`.

View File

@@ -1,6 +1,6 @@
{
"name": "@babel/core",
"version": "7.0.0-beta.38",
"version": "7.0.0-beta.44",
"description": "Babel compiler core.",
"main": "./lib/index.js",
"author": "Sebastian McKenzie <sebmck@gmail.com>",
@@ -28,23 +28,24 @@
"./lib/transform-file-sync.js": "./lib/transform-file-sync-browser.js"
},
"dependencies": {
"@babel/code-frame": "7.0.0-beta.38",
"@babel/generator": "7.0.0-beta.38",
"@babel/helpers": "7.0.0-beta.38",
"@babel/template": "7.0.0-beta.38",
"@babel/traverse": "7.0.0-beta.38",
"@babel/types": "7.0.0-beta.38",
"babylon": "7.0.0-beta.38",
"@babel/code-frame": "7.0.0-beta.44",
"@babel/generator": "7.0.0-beta.44",
"@babel/helpers": "7.0.0-beta.44",
"@babel/template": "7.0.0-beta.44",
"@babel/traverse": "7.0.0-beta.44",
"@babel/types": "7.0.0-beta.44",
"babylon": "7.0.0-beta.44",
"convert-source-map": "^1.1.0",
"debug": "^3.0.1",
"debug": "^3.1.0",
"json5": "^0.5.0",
"lodash": "^4.2.0",
"micromatch": "^2.3.11",
"resolve": "^1.3.2",
"semver": "^5.4.1",
"source-map": "^0.5.0"
},
"devDependencies": {
"@babel/helper-transform-fixture-test-runner": "7.0.0-beta.38",
"@babel/register": "7.0.0-beta.38"
"@babel/helper-transform-fixture-test-runner": "7.0.0-beta.44",
"@babel/register": "7.0.0-beta.44"
}
}

View File

@@ -1,6 +1,6 @@
// @flow
type SimpleCacheConfigurator = SimpleCacheConfiguratorFn &
export type SimpleCacheConfigurator = SimpleCacheConfiguratorFn &
SimpleCacheConfiguratorObj;
type SimpleCacheConfiguratorFn = {

View File

@@ -13,10 +13,10 @@ import {
const debug = buildDebug("babel:config:config-chain");
import {
findBabelrc,
findBabelignore,
findRelativeConfig,
loadConfig,
type ConfigFile,
type IgnoreFile,
} from "./files";
import { makeWeakCache, makeStrongCache } from "./caching";
@@ -104,14 +104,18 @@ const loadPresetOverridesEnvDescriptors = makeWeakCache(
),
);
export type RootConfigChain = ConfigChain & {
babelrc: ConfigFile | void,
ignore: IgnoreFile | void,
};
/**
* Build a config chain for Babel's full root configuration.
*/
export function buildRootChain(
cwd: string,
opts: ValidatedOptions,
context: ConfigContext,
): ConfigChain | null {
): RootConfigChain | null {
const programmaticChain = loadProgrammaticChain(
{
options: opts,
@@ -121,26 +125,24 @@ export function buildRootChain(
);
if (!programmaticChain) return null;
let ignore, babelrc;
const fileChain = emptyChain();
// resolve all .babelrc files
if (opts.babelrc !== false && context.filename !== null) {
const filename = context.filename;
const babelignoreFile = findBabelignore(filename);
if (
babelignoreFile &&
shouldIgnore(
context,
babelignoreFile.ignore,
null,
babelignoreFile.dirname,
)
) {
({ ignore, config: babelrc } = findRelativeConfig(
filename,
context.envName,
));
if (ignore && shouldIgnore(context, ignore.ignore, null, ignore.dirname)) {
return null;
}
const babelrcFile = findBabelrc(filename, context.envName);
if (babelrcFile) {
const result = loadFileChain(babelrcFile, context);
if (babelrc) {
const result = loadFileChain(babelrc, context);
if (!result) return null;
mergeChain(fileChain, result);
@@ -158,6 +160,8 @@ export function buildRootChain(
plugins: dedupDescriptors(chain.plugins),
presets: dedupDescriptors(chain.presets),
options: chain.options.map(o => normalizeOptions(o)),
ignore: ignore || undefined,
babelrc: babelrc || undefined,
};
}

View File

@@ -2,6 +2,8 @@
import { loadPlugin, loadPreset } from "./files";
import { getItemDescriptor } from "./item";
import {
makeWeakCache,
makeStrongCache,
@@ -33,6 +35,10 @@ export type UnloadedDescriptor = {
dirname: string,
alias: string,
ownPass?: boolean,
file?: {
request: string,
resolved: string,
} | void,
};
export type ValidatedFile = {
@@ -152,16 +158,11 @@ function createDescriptors(
ownPass?: boolean,
): Array<UnloadedDescriptor> {
const descriptors = items.map((item, index) =>
createDescriptor(
item,
type === "plugin" ? loadPlugin : loadPreset,
dirname,
{
index,
alias,
ownPass: !!ownPass,
},
),
createDescriptor(item, dirname, {
type,
alias: `${alias}$${index}`,
ownPass: !!ownPass,
}),
);
assertNoDuplicates(descriptors);
@@ -172,20 +173,24 @@ function createDescriptors(
/**
* Given a plugin/preset item, resolve it into a standard format.
*/
function createDescriptor(
export function createDescriptor(
pair: PluginItem,
resolver,
dirname,
dirname: string,
{
index,
type,
alias,
ownPass,
}: {
index: number,
type?: "plugin" | "preset",
alias: string,
ownPass?: boolean,
},
): UnloadedDescriptor {
const desc = getItemDescriptor(pair);
if (desc) {
return desc;
}
let name;
let options;
let value = pair;
@@ -198,9 +203,23 @@ function createDescriptor(
}
}
let file = undefined;
let filepath = null;
if (typeof value === "string") {
if (typeof type !== "string") {
throw new Error(
"To resolve a string-based item, the type of item must be given",
);
}
const resolver = type === "plugin" ? loadPlugin : loadPreset;
const request = value;
({ filepath, value } = resolver(value, dirname));
file = {
request,
resolved: filepath,
};
}
if (!value) {
@@ -226,17 +245,18 @@ function createDescriptor(
// config object, because it can be useful to define them in nested
// configuration contexts.
throw new Error(
"Plugin/Preset files are not allowed to export objects, only functions.",
`Plugin/Preset files are not allowed to export objects, only functions. In ${filepath}`,
);
}
return {
name,
alias: filepath || `${alias}$${index}`,
alias: filepath || alias,
value,
options,
dirname,
ownPass,
file,
};
}

View File

@@ -6,6 +6,7 @@ import fs from "fs";
import json5 from "json5";
import resolve from "resolve";
import { makeStrongCache, type CacheConfigurator } from "../caching";
import makeAPI from "../helpers/config-api";
const debug = buildDebug("babel:config:loading:files:configuration");
@@ -21,41 +22,58 @@ export type IgnoreFile = {
ignore: Array<string>,
};
export type RelativeConfig = {
config: ConfigFile | null,
ignore: IgnoreFile | null,
};
const BABELRC_FILENAME = ".babelrc";
const BABELRC_JS_FILENAME = ".babelrc.js";
const PACKAGE_FILENAME = "package.json";
const BABELIGNORE_FILENAME = ".babelignore";
export function findBabelrc(
export function findRelativeConfig(
filepath: string,
envName: string,
): ConfigFile | null {
): RelativeConfig {
let config = null;
let ignore = null;
const dirname = path.dirname(filepath);
let loc = dirname;
while (true) {
const conf = [
BABELRC_FILENAME,
BABELRC_JS_FILENAME,
PACKAGE_FILENAME,
].reduce((previousConfig: ConfigFile | null, name) => {
const filepath = path.join(loc, name);
const config = readConfig(filepath, envName);
if (!config) {
config = [BABELRC_FILENAME, BABELRC_JS_FILENAME, PACKAGE_FILENAME].reduce(
(previousConfig: ConfigFile | null, name) => {
const filepath = path.join(loc, name);
const config = readConfig(filepath, envName);
if (config && previousConfig) {
throw new Error(
`Multiple configuration files found. Please remove one:\n` +
` - ${path.basename(previousConfig.filepath)}\n` +
` - ${name}\n` +
`from ${loc}`,
);
if (config && previousConfig) {
throw new Error(
`Multiple configuration files found. Please remove one:\n` +
` - ${path.basename(previousConfig.filepath)}\n` +
` - ${name}\n` +
`from ${loc}`,
);
}
return config || previousConfig;
},
null,
);
if (config) {
debug("Found configuration %o from %o.", config.filepath, dirname);
}
}
return config || previousConfig;
}, null);
if (!ignore) {
const ignoreLoc = path.join(loc, BABELIGNORE_FILENAME);
ignore = readIgnoreConfig(ignoreLoc);
if (conf) {
debug("Found configuration %o from %o.", conf.filepath, dirname);
return conf;
if (ignore) {
debug("Found ignore %o from %o.", ignore.filepath, dirname);
}
}
const nextLoc = path.dirname(loc);
@@ -63,27 +81,7 @@ export function findBabelrc(
loc = nextLoc;
}
return null;
}
export function findBabelignore(filepath: string): IgnoreFile | null {
const dirname = path.dirname(filepath);
let loc = dirname;
while (true) {
const ignoreLoc = path.join(loc, BABELIGNORE_FILENAME);
const ignore = readIgnoreConfig(ignoreLoc);
if (ignore) {
debug("Found ignore %o from %o.", ignore.filepath, dirname);
return ignore;
}
const nextLoc = path.dirname(loc);
if (loc === nextLoc) break;
loc = nextLoc;
}
return null;
return { config, ignore };
}
export function loadConfig(
@@ -106,7 +104,7 @@ export function loadConfig(
* Read the given config file, returning the result. Returns null if no config was found, but will
* throw if there are parsing errors while loading a config.
*/
function readConfig(filepath, envName) {
function readConfig(filepath, envName): ConfigFile | null {
return path.extname(filepath) === ".js"
? readConfigJS(filepath, { envName })
: readConfigFile(filepath);
@@ -153,12 +151,7 @@ const readConfigJS = makeStrongCache(
}
if (typeof options === "function") {
options = options({
cache: cache.simple(),
// Expose ".env()" so people can easily get the same env that we expose using the "env" key.
env: () => cache.using(data => data.envName),
async: () => false,
});
options = options(makeAPI(cache));
if (!cache.configured()) throwConfigError();
}

View File

@@ -1,27 +1,14 @@
// @flow
export type ConfigFile = {
filepath: string,
dirname: string,
options: {},
};
import type { ConfigFile, IgnoreFile, RelativeConfig } from "./configuration";
export type IgnoreFile = {
filepath: string,
dirname: string,
ignore: Array<string>,
};
export type { ConfigFile, IgnoreFile, RelativeConfig };
export function findBabelrc(
export function findRelativeConfig(
filepath: string,
envName: string, // eslint-disable-line no-unused-vars
): ConfigFile | null {
return null;
}
// eslint-disable-next-line no-unused-vars
export function findBabelignore(filepath: string): IgnoreFile | null {
return null;
): RelativeConfig {
return { config: null, ignore: null };
}
export function loadConfig(name: string, dirname: string): ConfigFile {

View File

@@ -105,7 +105,6 @@ function resolveStandardizedName(
} catch (e2) {}
if (resolvedOriginal) {
// eslint-disable-next-line max-len
e.message += `\n- If you want to resolve "${name}", use "module:${name}"`;
}
}
@@ -119,7 +118,6 @@ function resolveStandardizedName(
} catch (e2) {}
if (resolvedBabel) {
// eslint-disable-next-line max-len
e.message += `\n- Did you mean "@babel/${name}"?`;
}
@@ -131,7 +129,6 @@ function resolveStandardizedName(
} catch (e2) {}
if (resolvedOppositeType) {
// eslint-disable-next-line max-len
e.message += `\n- Did you accidentally pass a ${type} as a ${oppositeType}?`;
}
@@ -143,8 +140,9 @@ const LOADING_MODULES = new Set();
function requireModule(type: string, name: string): mixed {
if (LOADING_MODULES.has(name)) {
throw new Error(
// eslint-disable-next-line max-len
`Reentrant ${type} detected trying to load "${name}". This module is not ignored and is trying to load itself while compiling itself, leading to a dependency cycle. We recommend adding it to your "ignore" list in your babelrc, or to a .babelignore.`,
`Reentrant ${type} detected trying to load "${name}". This module is not ignored ` +
"and is trying to load itself while compiling itself, leading to a dependency cycle. " +
'We recommend adding it to your "ignore" list in your babelrc, or to a .babelignore.',
);
}

View File

@@ -0,0 +1,299 @@
// @flow
import { mergeOptions } from "./util";
import * as context from "../index";
import Plugin from "./plugin";
import { getItemDescriptor } from "./item";
import {
buildPresetChain,
type ConfigContext,
type ConfigChain,
type PresetInstance,
} from "./config-chain";
import type { UnloadedDescriptor } from "./config-descriptors";
import traverse from "@babel/traverse";
import { makeWeakCache, type CacheConfigurator } from "./caching";
import { validate } from "./validation/options";
import { validatePluginObject } from "./validation/plugins";
import makeAPI from "./helpers/config-api";
import loadPrivatePartialConfig from "./partial";
type LoadedDescriptor = {
value: {},
options: {},
dirname: string,
alias: string,
};
export type { InputOptions } from "./validation/options";
export type ResolvedConfig = {
options: Object,
passes: PluginPasses,
};
export type { Plugin };
export type PluginPassList = Array<Plugin>;
export type PluginPasses = Array<PluginPassList>;
// Context not including filename since it is used in places that cannot
// process 'ignore'/'only' and other filename-based logic.
type SimpleContext = {
envName: string,
};
export default function loadFullConfig(
inputOpts: mixed,
): ResolvedConfig | null {
const result = loadPrivatePartialConfig(inputOpts);
if (!result) {
return null;
}
const { options, context } = result;
const optionDefaults = {};
const passes = [[]];
try {
const { plugins, presets } = options;
if (!plugins || !presets) {
throw new Error("Assertion failure - plugins and presets exist");
}
const ignored = (function recurseDescriptors(
config: {
plugins: Array<UnloadedDescriptor>,
presets: Array<UnloadedDescriptor>,
},
pass: Array<Plugin>,
) {
const plugins = config.plugins.map(descriptor => {
return loadPluginDescriptor(descriptor, context);
});
const presets = config.presets.map(descriptor => {
return {
preset: loadPresetDescriptor(descriptor, context),
pass: descriptor.ownPass ? [] : pass,
};
});
// resolve presets
if (presets.length > 0) {
// The passes are created in the same order as the preset list, but are inserted before any
// existing additional passes.
passes.splice(
1,
0,
...presets.map(o => o.pass).filter(p => p !== pass),
);
for (const { preset, pass } of presets) {
if (!preset) return true;
const ignored = recurseDescriptors(
{
plugins: preset.plugins,
presets: preset.presets,
},
pass,
);
if (ignored) return true;
preset.options.forEach(opts => {
mergeOptions(optionDefaults, opts);
});
}
}
// resolve plugins
if (plugins.length > 0) {
pass.unshift(...plugins);
}
})(
{
plugins: plugins.map(item => {
const desc = getItemDescriptor(item);
if (!desc) {
throw new Error("Assertion failure - must be config item");
}
return desc;
}),
presets: presets.map(item => {
const desc = getItemDescriptor(item);
if (!desc) {
throw new Error("Assertion failure - must be config item");
}
return desc;
}),
},
passes[0],
);
if (ignored) return null;
} catch (e) {
// There are a few case where thrown errors will try to annotate themselves multiple times, so
// to keep things simple we just bail out if re-wrapping the message.
if (!/^\[BABEL\]/.test(e.message)) {
e.message = `[BABEL] ${context.filename || "unknown"}: ${e.message}`;
}
throw e;
}
const opts: Object = optionDefaults;
mergeOptions(opts, options);
opts.plugins = passes[0];
opts.presets = passes
.slice(1)
.filter(plugins => plugins.length > 0)
.map(plugins => ({ plugins }));
opts.passPerPreset = opts.presets.length > 0;
return {
options: opts,
passes: passes,
};
}
/**
* Load a generic plugin/preset from the given descriptor loaded from the config object.
*/
const loadDescriptor = makeWeakCache(
(
{ value, options, dirname, alias }: UnloadedDescriptor,
cache: CacheConfigurator<SimpleContext>,
): LoadedDescriptor => {
// Disabled presets should already have been filtered out
if (options === false) throw new Error("Assertion failure");
options = options || {};
let item = value;
if (typeof value === "function") {
const api = Object.assign({}, context, makeAPI(cache));
try {
item = value(api, options, dirname);
} catch (e) {
if (alias) {
e.message += ` (While processing: ${JSON.stringify(alias)})`;
}
throw e;
}
}
if (!item || typeof item !== "object") {
throw new Error("Plugin/Preset did not return an object.");
}
if (typeof item.then === "function") {
throw new Error(
`You appear to be using an async plugin, ` +
`which your current version of Babel does not support.` +
`If you're using a published plugin, ` +
`you may need to upgrade your @babel/core version.`,
);
}
return { value: item, options, dirname, alias };
},
);
/**
* Instantiate a plugin for the given descriptor, returning the plugin/options pair.
*/
function loadPluginDescriptor(
descriptor: UnloadedDescriptor,
context: SimpleContext,
): Plugin {
if (descriptor.value instanceof Plugin) {
if (descriptor.options) {
throw new Error(
"Passed options to an existing Plugin instance will not work.",
);
}
return descriptor.value;
}
return instantiatePlugin(loadDescriptor(descriptor, context), context);
}
const instantiatePlugin = makeWeakCache(
(
{ value, options, dirname, alias }: LoadedDescriptor,
cache: CacheConfigurator<SimpleContext>,
): Plugin => {
const pluginObj = validatePluginObject(value);
const plugin = Object.assign({}, pluginObj);
if (plugin.visitor) {
plugin.visitor = traverse.explode(Object.assign({}, plugin.visitor));
}
if (plugin.inherits) {
const inheritsDescriptor = {
name: undefined,
alias: `${alias}$inherits`,
value: plugin.inherits,
options,
dirname,
};
// If the inherited plugin changes, reinstantiate this plugin.
const inherits = cache.invalidate(data =>
loadPluginDescriptor(inheritsDescriptor, data),
);
plugin.pre = chain(inherits.pre, plugin.pre);
plugin.post = chain(inherits.post, plugin.post);
plugin.manipulateOptions = chain(
inherits.manipulateOptions,
plugin.manipulateOptions,
);
plugin.visitor = traverse.visitors.merge([
inherits.visitor || {},
plugin.visitor || {},
]);
}
return new Plugin(plugin, options, alias);
},
);
/**
* Generate a config object that will act as the root of a new nested config.
*/
const loadPresetDescriptor = (
descriptor: UnloadedDescriptor,
context: ConfigContext,
): ConfigChain | null => {
return buildPresetChain(
instantiatePreset(loadDescriptor(descriptor, context)),
context,
);
};
const instantiatePreset = makeWeakCache(
({ value, dirname, alias }: LoadedDescriptor): PresetInstance => {
return {
options: validate("preset", value),
alias,
dirname,
};
},
);
function chain(a, b) {
const fns = [a, b].filter(Boolean);
if (fns.length <= 1) return fns[0];
return function(...args) {
for (const fn of fns) {
fn.apply(this, args);
}
};
}

View File

@@ -0,0 +1,91 @@
// @flow
import semver from "semver";
import { version as coreVersion } from "../../";
import type { CacheConfigurator, SimpleCacheConfigurator } from "../caching";
type EnvFunction = {
(): string,
<T>((string) => T): T,
(string): boolean,
(Array<string>): boolean,
};
export type PluginAPI = {
version: string,
cache: SimpleCacheConfigurator,
env: EnvFunction,
async: () => boolean,
assertVersion: typeof assertVersion,
};
export default function makeAPI(
cache: CacheConfigurator<{ envName: string }>,
): PluginAPI {
const env: any = value =>
cache.using(data => {
if (typeof value === "undefined") return data.envName;
if (typeof value === "function") return value(data.envName);
if (!Array.isArray(value)) value = [value];
return value.some(entry => {
if (typeof entry !== "string") {
throw new Error("Unexpected non-string value");
}
return entry === data.envName;
});
});
return {
version: coreVersion,
cache: cache.simple(),
// Expose ".env()" so people can easily get the same env that we expose using the "env" key.
env,
async: () => false,
assertVersion,
};
}
function assertVersion(range: string | number): void {
if (typeof range === "number") {
if (!Number.isInteger(range)) {
throw new Error("Expected string or integer value.");
}
range = `^${range}.0.0-0`;
}
if (typeof range !== "string") {
throw new Error("Expected string or integer value.");
}
if (semver.satisfies(coreVersion, range)) return;
const limit = Error.stackTraceLimit;
if (typeof limit === "number" && limit < 25) {
// Bump up the limit if needed so that users are more likely
// to be able to see what is calling Babel.
Error.stackTraceLimit = 25;
}
const err = new Error(
`Requires Babel "${range}", but was loaded with "${coreVersion}". ` +
`If you are sure you have a compatible version of @babel/core, ` +
`it is likely that something in your build process is loading the ` +
`wrong version. Inspect the stack trace of this error to look for ` +
`the first entry that doesn't mention "@babel/core" or "babel-core" ` +
`to see what is calling Babel.`,
);
if (typeof limit === "number") {
Error.stackTraceLimit = limit;
}
throw Object.assign(
err,
({
code: "BABEL_VERSION_UNSUPPORTED",
version: coreVersion,
range,
}: any),
);
}

View File

@@ -1,306 +1,26 @@
// @flow
import path from "path";
import * as context from "../index";
import Plugin from "./plugin";
import merge from "lodash/merge";
import {
buildRootChain,
buildPresetChain,
type ConfigContext,
type ConfigChain,
type PresetInstance,
} from "./config-chain";
import type { UnloadedDescriptor } from "./config-descriptors";
import traverse from "@babel/traverse";
import clone from "lodash/clone";
import { makeWeakCache, type CacheConfigurator } from "./caching";
import { getEnv } from "./helpers/environment";
import { validate } from "./validation/options";
import { validatePluginObject } from "./validation/plugins";
import loadFullConfig from "./full";
export type {
ResolvedConfig,
InputOptions,
PluginPasses,
Plugin,
} from "./full";
type LoadedDescriptor = {
value: {},
options: {},
dirname: string,
alias: string,
};
export { loadFullConfig as default };
export { loadPartialConfig } from "./partial";
export type { PartialConfig } from "./partial";
export type { InputOptions } from "./validation/options";
export function loadOptions(opts: {}): Object | null {
const config = loadFullConfig(opts);
export type ResolvedConfig = {
options: Object,
passes: PluginPasses,
};
export type { Plugin };
export type PluginPassList = Array<Plugin>;
export type PluginPasses = Array<PluginPassList>;
// Context not including filename since it is used in places that cannot
// process 'ignore'/'only' and other filename-based logic.
type SimpleContext = {
envName: string,
};
export default function loadConfig(inputOpts: mixed): ResolvedConfig | null {
if (
inputOpts != null &&
(typeof inputOpts !== "object" || Array.isArray(inputOpts))
) {
throw new Error("Babel options must be an object, null, or undefined");
}
const args = inputOpts ? validate("arguments", inputOpts) : {};
const { envName = getEnv(), cwd = "." } = args;
const absoluteCwd = path.resolve(cwd);
const context: ConfigContext = {
filename: args.filename ? path.resolve(cwd, args.filename) : null,
cwd: absoluteCwd,
envName,
};
const configChain = buildRootChain(absoluteCwd, args, context);
if (!configChain) return null;
const optionDefaults = {};
const options = {};
const passes = [[]];
try {
const ignored = (function recurseDescriptors(
config: {
plugins: Array<UnloadedDescriptor>,
presets: Array<UnloadedDescriptor>,
},
pass: Array<Plugin>,
) {
const plugins = config.plugins.map(descriptor =>
loadPluginDescriptor(descriptor, context),
);
const presets = config.presets.map(descriptor => {
return {
preset: loadPresetDescriptor(descriptor, context),
pass: descriptor.ownPass ? [] : pass,
};
});
// resolve presets
if (presets.length > 0) {
// The passes are created in the same order as the preset list, but are inserted before any
// existing additional passes.
passes.splice(
1,
0,
...presets.map(o => o.pass).filter(p => p !== pass),
);
for (const { preset, pass } of presets) {
if (!preset) return true;
const ignored = recurseDescriptors(
{
plugins: preset.plugins,
presets: preset.presets,
},
pass,
);
if (ignored) return true;
preset.options.forEach(opts => {
merge(optionDefaults, opts);
});
}
}
// resolve plugins
if (plugins.length > 0) {
pass.unshift(...plugins);
}
})(
{
plugins: configChain.plugins,
presets: configChain.presets,
},
passes[0],
);
if (ignored) return null;
configChain.options.forEach(opts => {
merge(options, opts);
});
} catch (e) {
// There are a few case where thrown errors will try to annotate themselves multiple times, so
// to keep things simple we just bail out if re-wrapping the message.
if (!/^\[BABEL\]/.test(e.message)) {
e.message = `[BABEL] ${args.filename || "unknown"}: ${e.message}`;
}
throw e;
}
const opts: Object = merge(optionDefaults, options);
// Tack the passes onto the object itself so that, if this object is passed back to Babel a second time,
// it will be in the right structure to not change behavior.
opts.babelrc = false;
opts.plugins = passes[0];
opts.presets = passes
.slice(1)
.filter(plugins => plugins.length > 0)
.map(plugins => ({ plugins }));
opts.passPerPreset = opts.presets.length > 0;
opts.envName = envName;
opts.cwd = absoluteCwd;
return {
options: opts,
passes: passes,
};
return config ? config.options : null;
}
/**
* Load a generic plugin/preset from the given descriptor loaded from the config object.
*/
const loadDescriptor = makeWeakCache(
(
{ value, options, dirname, alias }: UnloadedDescriptor,
cache: CacheConfigurator<SimpleContext>,
): LoadedDescriptor => {
// Disabled presets should already have been filtered out
if (options === false) throw new Error("Assertion failure");
options = options || {};
let item = value;
if (typeof value === "function") {
const api = Object.assign(Object.create(context), {
cache: cache.simple(),
env: () => cache.using(data => data.envName),
async: () => false,
});
try {
item = value(api, options, dirname);
} catch (e) {
if (alias) {
e.message += ` (While processing: ${JSON.stringify(alias)})`;
}
throw e;
}
}
if (!item || typeof item !== "object") {
throw new Error("Plugin/Preset did not return an object.");
}
if (typeof item.then === "function") {
throw new Error(
`You appear to be using an async plugin, ` +
`which your current version of Babel does not support.` +
`If you're using a published plugin, ` +
`you may need to upgrade your @babel/core version.`,
);
}
return { value: item, options, dirname, alias };
},
);
/**
* Instantiate a plugin for the given descriptor, returning the plugin/options pair.
*/
function loadPluginDescriptor(
descriptor: UnloadedDescriptor,
context: SimpleContext,
): Plugin {
if (descriptor.value instanceof Plugin) {
if (descriptor.options) {
throw new Error(
"Passed options to an existing Plugin instance will not work.",
);
}
return descriptor.value;
// For easier backward-compatibility, provide an API like the one we exposed in Babel 6.
export class OptionManager {
init(opts: {}) {
return loadOptions(opts);
}
return instantiatePlugin(loadDescriptor(descriptor, context), context);
}
const instantiatePlugin = makeWeakCache(
(
{ value, options, dirname, alias }: LoadedDescriptor,
cache: CacheConfigurator<SimpleContext>,
): Plugin => {
const pluginObj = validatePluginObject(value);
const plugin = Object.assign({}, pluginObj);
if (plugin.visitor) {
plugin.visitor = traverse.explode(clone(plugin.visitor));
}
if (plugin.inherits) {
const inheritsDescriptor = {
name: undefined,
alias: `${alias}$inherits`,
value: plugin.inherits,
options,
dirname,
};
// If the inherited plugin changes, reinstantiate this plugin.
const inherits = cache.invalidate(data =>
loadPluginDescriptor(inheritsDescriptor, data),
);
plugin.pre = chain(inherits.pre, plugin.pre);
plugin.post = chain(inherits.post, plugin.post);
plugin.manipulateOptions = chain(
inherits.manipulateOptions,
plugin.manipulateOptions,
);
plugin.visitor = traverse.visitors.merge([
inherits.visitor || {},
plugin.visitor || {},
]);
}
return new Plugin(plugin, options, alias);
},
);
/**
* Generate a config object that will act as the root of a new nested config.
*/
const loadPresetDescriptor = (
descriptor: UnloadedDescriptor,
context: ConfigContext,
): ConfigChain | null => {
return buildPresetChain(
instantiatePreset(loadDescriptor(descriptor, context)),
context,
);
};
const instantiatePreset = makeWeakCache(
({ value, dirname, alias }: LoadedDescriptor): PresetInstance => {
return {
options: validate("preset", value),
alias,
dirname,
};
},
);
function chain(a, b) {
const fns = [a, b].filter(Boolean);
if (fns.length <= 1) return fns[0];
return function(...args) {
for (const fn of fns) {
fn.apply(this, args);
}
};
}

View File

@@ -0,0 +1,128 @@
// @flow
import type { PluginTarget, PluginOptions } from "./validation/options";
import path from "path";
import {
createDescriptor,
type UnloadedDescriptor,
} from "./config-descriptors";
export function createItemFromDescriptor(desc: UnloadedDescriptor): ConfigItem {
return new ConfigItem(desc);
}
/**
* Create a config item using the same value format used in Babel's config
* files. Items returned from this function should be cached by the caller
* ideally, as recreating the config item will mean re-resolving the item
* and re-evaluating the plugin/preset function.
*/
export function createConfigItem(
value:
| PluginTarget
| [PluginTarget, PluginOptions]
| [PluginTarget, PluginOptions, string | void],
{
dirname = ".",
type,
}: {
dirname?: string,
type?: "preset" | "plugin",
} = {},
): ConfigItem {
const descriptor = createDescriptor(value, path.resolve(dirname), {
type,
alias: "programmatic item",
});
return createItemFromDescriptor(descriptor);
}
export function getItemDescriptor(item: mixed): UnloadedDescriptor | void {
if (item instanceof ConfigItem) {
return item._descriptor;
}
return undefined;
}
export type { ConfigItem };
/**
* A public representation of a plugin/preset that will _eventually_ be load.
* Users can use this to interact with the results of a loaded Babel
* configuration.
*
* Any changes to public properties of this class should be considered a
* breaking change to Babel's API.
*/
class ConfigItem {
/**
* The private underlying descriptor that Babel actually cares about.
* If you access this, you are a bad person.
*/
_descriptor: UnloadedDescriptor;
/**
* The resolved value of the item itself.
*/
value: {} | Function;
/**
* The options, if any, that were passed to the item.
* Mutating this will lead to undefined behavior. If you need
*/
options: {} | void;
/**
* The directory that the options for this item are relative to.
*/
dirname: string;
/**
* Get the name of the plugin, if the user gave it one.
*/
name: string | void;
/**
* Data about the file that the item was loaded from, if Babel knows it.
*/
file: {
// The requested path, e.g. "@babel/env".
request: string,
// The resolved absolute path of the file.
resolved: string,
} | void;
constructor(descriptor: UnloadedDescriptor) {
// Make people less likely to stumble onto this if they are exploring
// programmatically, and also make sure that if people happen to
// pass the item through JSON.stringify, it doesn't show up.
this._descriptor = descriptor;
Object.defineProperty(this, "_descriptor", ({ enumerable: false }: any));
if (this._descriptor.options === false) {
throw new Error("Assertion failure - unexpected false options");
}
this.value = this._descriptor.value;
this.options = this._descriptor.options;
this.dirname = this._descriptor.dirname;
this.name = this._descriptor.name;
this.file = this._descriptor.file
? {
request: this._descriptor.file.request,
resolved: this._descriptor.file.resolved,
}
: undefined;
// Freeze the object to make it clear that people shouldn't expect mutating
// this object to do anything. A new item should be created if they want
// to change something.
Object.freeze(this);
}
}
Object.freeze(ConfigItem.prototype);

View File

@@ -0,0 +1,128 @@
// @flow
import path from "path";
import Plugin from "./plugin";
import { mergeOptions } from "./util";
import { createItemFromDescriptor } from "./item";
import { buildRootChain, type ConfigContext } from "./config-chain";
import { getEnv } from "./helpers/environment";
import { validate, type ValidatedOptions } from "./validation/options";
import type { ConfigFile, IgnoreFile } from "./files";
export default function loadPrivatePartialConfig(
inputOpts: mixed,
): {
options: ValidatedOptions,
context: ConfigContext,
ignore: IgnoreFile | void,
babelrc: ConfigFile | void,
} | null {
if (
inputOpts != null &&
(typeof inputOpts !== "object" || Array.isArray(inputOpts))
) {
throw new Error("Babel options must be an object, null, or undefined");
}
const args = inputOpts ? validate("arguments", inputOpts) : {};
const { envName = getEnv(), cwd = "." } = args;
const absoluteCwd = path.resolve(cwd);
const context: ConfigContext = {
filename: args.filename ? path.resolve(cwd, args.filename) : null,
cwd: absoluteCwd,
envName,
};
const configChain = buildRootChain(args, context);
if (!configChain) return null;
const options = {};
configChain.options.forEach(opts => {
mergeOptions(options, opts);
});
// Tack the passes onto the object itself so that, if this object is
// passed back to Babel a second time, it will be in the right structure
// to not change behavior.
options.babelrc = false;
options.envName = envName;
options.cwd = absoluteCwd;
options.passPerPreset = false;
options.plugins = configChain.plugins.map(descriptor =>
createItemFromDescriptor(descriptor),
);
options.presets = configChain.presets.map(descriptor =>
createItemFromDescriptor(descriptor),
);
return {
options,
context,
ignore: configChain.ignore,
babelrc: configChain.babelrc,
};
}
export function loadPartialConfig(inputOpts: mixed): PartialConfig | null {
const result = loadPrivatePartialConfig(inputOpts);
if (!result) return null;
const { options, babelrc, ignore } = result;
(options.plugins || []).forEach(item => {
if (item.value instanceof Plugin) {
throw new Error(
"Passing cached plugin instances is not supported in " +
"babel.loadPartialConfig()",
);
}
});
return new PartialConfig(
options,
babelrc ? babelrc.filepath : undefined,
ignore ? ignore.filepath : undefined,
);
}
export type { PartialConfig };
class PartialConfig {
/**
* These properties are public, so any changes to them should be considered
* a breaking change to Babel's API.
*/
options: ValidatedOptions;
babelrc: string | void;
babelignore: string | void;
constructor(
options: ValidatedOptions,
babelrc: string | void,
ignore: string | void,
) {
this.options = options;
this.babelignore = ignore;
this.babelrc = babelrc;
// Freeze since this is a public API and it should be extremely obvious that
// reassigning properties on here does nothing.
Object.freeze(this);
}
/**
* Returns true if their is a config file in the filesystem for this config.
*
* While this only means .babelrc(.mjs)?/package.json#babel right now, it
* may well expand in the future, so using this is recommended vs checking
* this.babelrc directly.
*/
hasFilesystemConfig(): boolean {
return this.babelrc !== undefined;
}
}
Object.freeze(PartialConfig.prototype);

View File

@@ -0,0 +1,30 @@
// @flow
import type { ValidatedOptions } from "./validation/options";
export function mergeOptions(
target: ValidatedOptions,
source: ValidatedOptions,
): void {
for (const k of Object.keys(source)) {
if (k === "parserOpts" && source.parserOpts) {
const parserOpts = source.parserOpts;
const targetObj = (target.parserOpts = target.parserOpts || {});
mergeDefaultFields(targetObj, parserOpts);
} else if (k === "generatorOpts" && source.generatorOpts) {
const generatorOpts = source.generatorOpts;
const targetObj = (target.generatorOpts = target.generatorOpts || {});
mergeDefaultFields(targetObj, generatorOpts);
} else {
const val = source[k];
if (val !== undefined) target[k] = (val: any);
}
}
}
function mergeDefaultFields<T: {}>(target: T, source: T) {
for (const k of Object.keys(source)) {
const val = source[k];
if (val !== undefined) target[k] = (val: any);
}
}

View File

@@ -140,6 +140,8 @@ export function assertConfigApplicableTest(
key: string,
value: mixed,
): ConfigApplicableTest | void {
if (value === undefined) return value;
if (Array.isArray(value)) {
value.forEach((item, i) => {
if (!checkValidTest(item)) {

View File

@@ -1,5 +1,8 @@
// @flow
import type { ConfigItem } from "../item";
import Plugin from "../plugin";
import removed from "./removed";
import {
assertString,
@@ -116,9 +119,6 @@ const COMMON_VALIDATORS: ValidatorSet = {
sourceMap: (assertSourceMaps: Validator<
$PropertyType<ValidatedOptions, "sourceMap">,
>),
sourceMapTarget: (assertString: Validator<
$PropertyType<ValidatedOptions, "sourceMapTarget">,
>),
sourceFileName: (assertString: Validator<
$PropertyType<ValidatedOptions, "sourceFileName">,
>),
@@ -189,7 +189,6 @@ export type ValidatedOptions = {
// Sourcemap generation options.
sourceMaps?: SourceMapsOption,
sourceMap?: SourceMapsOption,
sourceMapTarget?: string,
sourceFileName?: string,
sourceRoot?: string,
@@ -214,10 +213,11 @@ export type IgnoreList = $ReadOnlyArray<IgnoreItem>;
export type PluginOptions = {} | void | false;
export type PluginTarget = string | {} | Function;
export type PluginItem =
| ConfigItem
| Plugin
| PluginTarget
| [PluginTarget, PluginOptions]
| [PluginTarget, PluginOptions, string];
| [PluginTarget, PluginOptions, string | void];
export type PluginList = $ReadOnlyArray<PluginItem>;
export type OverridesList = Array<ValidatedOptions>;

View File

@@ -1,5 +1,4 @@
// @flow
/* eslint max-len: "off" */
export default {
auxiliaryComment: {
@@ -16,35 +15,42 @@ export default {
},
externalHelpers: {
message:
"Use the `external-helpers` plugin instead. Check out http://babeljs.io/docs/plugins/external-helpers/",
"Use the `external-helpers` plugin instead. " +
"Check out http://babeljs.io/docs/plugins/external-helpers/",
},
extra: {
message: "",
},
jsxPragma: {
message:
"use the `pragma` option in the `react-jsx` plugin . Check out http://babeljs.io/docs/plugins/transform-react-jsx/",
"use the `pragma` option in the `react-jsx` plugin. " +
"Check out http://babeljs.io/docs/plugins/transform-react-jsx/",
},
loose: {
message:
"Specify the `loose` option for the relevant plugin you are using or use a preset that sets the option.",
"Specify the `loose` option for the relevant plugin you are using " +
"or use a preset that sets the option.",
},
metadataUsedHelpers: {
message: "Not required anymore as this is enabled by default",
},
modules: {
message:
"Use the corresponding module transform plugin in the `plugins` option. Check out http://babeljs.io/docs/plugins/#modules",
"Use the corresponding module transform plugin in the `plugins` option. " +
"Check out http://babeljs.io/docs/plugins/#modules",
},
nonStandard: {
message:
"Use the `react-jsx` and `flow-strip-types` plugins to support JSX and Flow. Also check out the react preset http://babeljs.io/docs/plugins/preset-react/",
"Use the `react-jsx` and `flow-strip-types` plugins to support JSX and Flow. " +
"Also check out the react preset http://babeljs.io/docs/plugins/preset-react/",
},
optional: {
message: "Put the specific transforms you want in the `plugins` option",
},
sourceMapName: {
message: "Use the `sourceMapTarget` option",
message:
"The `sourceMapName` option has been removed because it makes more sense for the " +
"tooling that calls Babel to assign `map.file` themselves.",
},
stage: {
message:
@@ -64,4 +70,11 @@ export default {
message:
"Generated plugin metadata is always included in the output result",
},
sourceMapTarget: {
version: 6,
message:
"The `sourceMapTarget` option has been removed because it makes more sense for the tooling " +
"that calls Babel to assign `map.file` themselves.",
},
};

Some files were not shown because too many files have changed in this diff Show More