Compare commits

...

168 Commits

Author SHA1 Message Date
Henry Zhu
663c96db04 v7.0.0-beta.52 2018-07-05 20:59:03 -04:00
Rubén Norte
85b7154f91 Add visitor key for Flow typeArguments in call expressions (#8273)
| Q                        | A <!--(Can use an emoji 👍) -->
| ------------------------ | ---
| Fixed Issues?            | Fixes #8272 <!-- remove the (`) quotes to link the issues -->
| Patch: Bug Fix?          | Yes
| Major: Breaking Change?  |
| Minor: New Feature?      |
| Tests Added + Pass?      | Yes
| Documentation PR         | <!-- If so, add `[skip ci]` to your commit message to skip CI -->
| Any Dependency Changes?  |
| License                  | MIT

The visitor for `typeArguments` in function calls wasn't set in the definition, so type annotations added there weren't visited.

This is required to fix https://github.com/babel/babel-eslint/issues/644
2018-07-05 14:58:15 -05:00
Henry Zhu
f70d7c8dfe update template [skip ci]
link to babel/website
2018-07-05 14:19:15 -04:00
Justin Ridgewell
e229ebbb8a Optimize async to generator (#8267)
* Optimize async to generator

We can reuse the step function, avoiding a closure on every invocation.

* Rename step
2018-07-05 10:51:16 -04:00
dnalborczyk
db1385fb82 upgrades eslint v5 (major), babel-eslint, eslint-plugin-flowtype, eslint-plugin-prettier (#8259)
* upgrade eslint v5 (major), babel-eslint (minor), eslint-plugin-flowtype (minor), eslint-plugin-prettier (patch)

* fix makefile: remove (default) .js file extension, remove non-existing glob pattern

* fix linting errors

* add '*.js' glob back to include babel.config.js for linting
2018-07-05 09:17:01 -05:00
Logan Smyth
b6eba87daa Rename some test fixtures so they run properly. (#8265) 2018-07-04 18:33:26 -07:00
Logan Smyth
2cf2fd544b Ensure that we don't get unexpected output files for tests that throw. (#8208) 2018-07-04 16:06:58 -07:00
Logan Smyth
9bd4b46fd6 Merge pull request #8198 from loganfsmyth/sourcemap-loading
Prefer explicit object maps, and properly load relative maps.
2018-07-04 15:39:42 -07:00
Pierre-Marie Dartus
4d125c391a Typescript: Avoid stripping class properties when a decorator is set (#8238)
The `babel-plugin-transform-typescript` removes class properties without value regardless if decorators are assigned to it or not.
2018-07-04 07:44:33 -04:00
dnalborczyk
afa1207224 upgrade flow to v0.75.0 (#8256) 2018-07-03 11:23:32 -05:00
Rodolfo Rodriguez
c6a4108e57 Update READMEs for yarn (#8215) [skip ci]
Closes https://github.com/babel/babel/pull/8255
2018-07-03 09:03:18 -04:00
John Buffington
236bd9309c remove emojis from cli output (#8243) (#8250) 2018-07-02 09:34:55 +02:00
James DiGioia
eac4c5bc17 Add proposal flag to pipeline plugin (#8196)
This is going to be required so we can add support for other proposals,
as well as later set the accepted proposal as the default.

Update stage-0 and stage-1 presets with `pipelineProposal` to thread down to
the plugin.
2018-06-28 01:19:40 +02:00
Mateusz Burzyński
e1662759ed Remove regenerator hacks in checkDuplicatedNodes (#8220) 2018-06-24 15:40:47 +02:00
Ben Newman
12c75cc08c Update regenerator-{runtime,transform} to latest versions. (#8219)
https://github.com/facebook/regenerator/pull/347
https://github.com/facebook/regenerator/pull/349
https://github.com/facebook/regenerator/pull/350
2018-06-24 10:19:21 +02:00
Sven Sauleau
9283efaeb7 Merge pull request #8197 from loganfsmyth/babel-plugin-allowed
Allow @foo/babel-plugin as an unexpanded plugin name, and @foo as a shorthand for it.
2018-06-20 16:36:03 +02:00
Logan Smyth
532c25c8db Ensure that file-path sourcemaps load relative to the file containing the comment. 2018-06-18 22:06:08 -07:00
Logan Smyth
3c90baaf6c Prefer object sourcemaps over file-inlined sourcemaps. 2018-06-18 21:49:23 -07:00
Logan Smyth
add5f8d0fe Allow @foo/babel-plugin as an unexpanded plugin name, and @foo as a shorthand for it. 2018-06-18 21:36:02 -07:00
Soumya Himanish Mohapatra
cb79473499 remove regression to support output of full directory hierarchy with --out-dir (#8189)
* remove regression to support output of full directory hierarchy with --out-dir

* add mkdirp to package.json
2018-06-18 21:19:46 -07:00
Brian Ng
d383659ca6 Compile against beta 51 (#8158) 2018-06-15 10:28:15 -04:00
Ger Hobbelt
e86d1e0d6a babel/parser: test helpers: write expected throw message to options.json ~ complete jest -u functionality (#8178) [skip ci]
* babel/parser: test helpers: when test fails with an exception and both reference output file and options.json file do not exist, write a simple options.json with the error message to expect when such a file doesn't exist yet. This completes the `jest -u` capability for new tests which are expected to *fail*.
2018-06-15 10:27:19 -04:00
Ger Hobbelt
a2cd264211 jest binary is a bash shell script, not a nodeJS file. (#8179) [skip ci] 2018-06-15 10:18:14 -04:00
Sven Sauleau
8f8b4e8e82 Switch new website in READMEs (#8181) [skip ci] 2018-06-15 10:13:20 -04:00
Ger Hobbelt
07c88e6f0b Use charCodes at more places in the parser (#8176) 2018-06-15 13:21:32 +02:00
Ger Hobbelt
ba98cf782a Removed constant condition in parser (#8177) 2018-06-15 13:14:14 +02:00
kenju
bc64e02bf8 fix issue number of link for #3508 in CHANGELOG (#8175) [skip ci] 2018-06-15 12:12:21 +02:00
dnalborczyk
814fce946d bump flow to v0.74.0 (#8162) 2018-06-13 15:00:09 -04:00
dnalborczyk
6894465df8 fix flow typeof refinement (#8161) [skip ci] 2018-06-13 14:59:57 -04:00
Ben Newman
60c4f30c71 Update regenerator-transform to latest version (0.13.0). (#8154)
| Q                        | A <!--(Can use an emoji 👍) -->
| ------------------------ | ---
| Fixed Issues?            | None
| Patch: Bug Fix?          | No
| Major: Breaking Change?  | No
| Minor: New Feature?      | No
| Tests Added + Pass?      | Existing tests pass
| Documentation PR         | No
| Any Dependency Changes?  | `regenerator-transform` in `@babel/plugin-transform-regenerator`
| License                  | MIT

I recently updated `regenerator`, `regenerator-transform`, and `regenerator-preset` to fix a number of vulnerabilities surfaced by `npm audit`. There was no need to update `regenerator-runtime`, as it does not have any dependencies of its own. I'm happy to report the latest versions of these packages have zero vulnerability warnings according to `npm audit`.

While I was at it, I also updated all dependencies of these packages to their Babel 7 equivalents, so there should hopefully be fewer legacy package dependencies installed because of Regenerator.
2018-06-13 09:36:27 -05:00
Henry Zhu
c313b267f7 v7.0.0-beta.51 2018-06-12 17:18:28 -04:00
Henry Zhu
eb54adb755 use a semver range for core peerDep [skip ci] 2018-06-12 17:10:15 -04:00
Henry Zhu
e0ef50c00f Use older semver range since lerna update does not change peerDeps on publish [skip ci] (#8152) 2018-06-12 16:45:10 -04:00
Henry Zhu
3af623678f v7.0.0-beta.50 2018-06-12 15:46:05 -04:00
Henry Zhu
96528d36df keep lerna version 2018-06-12 15:22:34 -04:00
Henry Zhu
5de12c26f6 update to latest 2.x lerna 2018-06-12 15:02:56 -04:00
Henry Zhu
4b5a55d937 fix merge issue again 2018-06-12 13:59:43 -04:00
Guy Bedford
036c429ce1 system hoisting and export refinements (#8104) 2018-06-12 13:45:53 -04:00
Nicolò Ribaudo
3c46e75b8f Don't split an exported class when renaming an inner binding (#8051) 2018-06-12 13:45:21 -04:00
晏兵兵
106907e605 fix: import Parser as type (#8146) [skip ci] 2018-06-12 13:42:10 -04:00
Nicolò Ribaudo
387cda8fbb isConstantExpression should return true for immuable bindings (#8122)
* isConstantExpression should return true for immuable bindings

* New test

* Don't return undefined
2018-06-12 13:40:52 -04:00
Henry Zhu
86c10ff4f3 fix merge issue 2018-06-12 13:33:07 -04:00
Miguel Albernaz
6d5392554f Adds JSXFragment to plugin-transform-typescript check for the presence of jsx (#7996) 2018-06-12 13:17:25 -04:00
Alexey Zaslavsky
0b25e3327c Fix 'Missing class properties transform' error when parsing class properties with Typescript syntax (#8007) 2018-06-12 13:13:30 -04:00
Brian Ng
b6455c611b Allow ts modifier names to be used as function argument names (#8030) 2018-06-12 08:38:38 -05:00
Yuri Karadzhov
313960e601 Remove preset-env outdated test (#8149) 2018-06-12 08:51:11 -04:00
Yuri Karadzhov
9e4c56f990 Fix Safari TP and regular versions comparison (#8132) 2018-06-11 14:36:45 -04:00
Nicolò Ribaudo
119db23ee3 Don't regenerate babel-types docs in the readme (#8142) 2018-06-11 14:35:21 -04:00
Vincent Chan
3432792568 add jsesc options support (#8143) 2018-06-11 14:34:41 -04:00
Brian Ng
cc4ee350e4 Ensure regex-dot-all runs before unicode-regex in preset-env (#8138)
<!--
Before making a PR please make sure to read our contributing guidelines
https://github.com/babel/babel/blob/master/CONTRIBUTING.md

For issue references: Add a comma-separated list of a [closing word](https://help.github.com/articles/closing-issues-via-commit-messages/) followed by the ticket number fixed by the PR. It should be underlined in the preview if done correctly.
-->

| Q                        | A <!--(Can use an emoji 👍) -->
| ------------------------ | ---
| Fixed Issues?            | --
| Patch: Bug Fix?          |
| Major: Breaking Change?  |
| Minor: New Feature?      |
| Tests Added + Pass?      | Yes
| Documentation PR         | <!-- If so, add `[skip ci]` to your commit message to skip CI -->
| Any Dependency Changes?  |
| License                  | MIT

Good ol' plugin ordering 🙃

Ref: https://github.com/babel/babel/pull/7065#issuecomment-395959112
2018-06-11 08:09:44 -05:00
Sven Sauleau
5bd79c70a5 Merge pull request #8144 from BeniCheni/add-labels-to-readmes
Add Labels to READMEs Generator & Update README's w. Links To Open Issues (for some pkg's)
2018-06-11 07:32:34 +02:00
BeniCheni
01f6f4c66d Revert babel-types README to "master" 2018-06-11 01:19:18 -04:00
BeniCheni
000fa83b9e For selective packages, update READMES w. links for open issues
babel-generator; babel-node; babel-standalone; babel-template
2018-06-11 00:16:48 -04:00
BeniCheni
efb34aa7dc For selective packages, add items for labels mapping of pkg => labels & update READMES w. links for open issues
babel-generator; babel-node; babel-standalone; babel-template
2018-06-10 23:41:55 -04:00
Brian Ng
ab928713af Bump test262-stream and update test262 tests (#8139) 2018-06-10 10:55:40 +02:00
Serhii Nanovskyi
3de053cc6c Validate @babel/preset-env options (#8031) 2018-06-09 18:38:14 -05:00
Sven Sauleau
110779e9f3 Merge pull request #8133 from alexzherdev/8131-open-issues-link
Link to open issues in READMEs [skip ci]
2018-06-09 15:03:49 +02:00
Alex Zherdev
8070a2204d Link to open issues in READMEs [skip ci] 2018-06-08 20:54:44 -07:00
Nicolò Ribaudo
9f4e2f81d8 [class-properties] Remove unnecessary return and temp variable (#8123)
* Remove unnecessary temp variable

* Update tests
2018-06-08 07:02:36 +02:00
Mathias Bynens
415d79bdfe Update plugin-proposal-unicode-property-regex for Unicode v11 (#8127)
Ref. https://github.com/tc39/ecma262/pulls/1218.
Ref. https://github.com/tc39/ecma262/issues/1219.
2018-06-07 21:54:44 +02:00
Mathias Bynens
62eb32677c ECMAScript follows the latest version of the Unicode Standard. Earlier this week, Unicode v11 was officially released. This patch updates babel-parser to support the new identifier characters. (#8125)
Ref. https://github.com/tc39/ecma262/issues/1219.
2018-06-07 21:54:12 +02:00
Guy Bedford
7da7e760a6 support import.meta in system transform 2018-06-07 13:24:19 -05:00
hassanAli321
bd44902024 update fixture 2018-06-07 13:22:45 -05:00
hassanAli321
6480ae4a9f fix flow-double-nullable-type-cant-be-parsed 2018-06-07 13:22:45 -05:00
Marco Massarotto
80b3362fcc update micromatch to ^3.1.10 (#8038) 2018-06-06 12:44:02 +02:00
Sven SAULEAU
8bc0182489 Merge pull request #8119 from palashmon/fix-package-readmes
fix(typo): in readmes package label
2018-06-05 19:24:25 +02:00
Palash Mondal
e9d861537f [skip ci] updated babel-register readme 2018-06-05 22:43:46 +05:30
Palash Mondal
153ad4c6f3 fix(typo): in readmes package label
"babel-regiser" to "babel-register" and "pkg: regiser" to "pkg: register"
2018-06-05 21:19:51 +05:30
Sven SAULEAU
218d69007e Merge pull request #8112 from babel/feat-add-issues-link-in-readmes
Feat add issues link in readmes
2018-06-05 07:39:41 +02:00
Nicolò Ribaudo
f838a7e9f1 Test on node 10 (#7908)
* Use node 10 on circle an node 9 on travis

* Update v8flag
2018-06-04 22:22:30 +02:00
Nicolò Ribaudo
6349118bed Change decoratorsBeforeExport default to false (#8113) 2018-06-04 21:12:01 +02:00
Sven SAULEAU
8bbb10c021 chore: [skip ci] regen READMEs 2018-06-04 17:33:21 +02:00
Sven SAULEAU
f614809002 feat: [skip ci] add link to issues in READMEs 2018-06-04 17:33:16 +02:00
Sven SAULEAU
b445b79734 Refactor move docs (#8108)
* feat: [skip] generate readme script

* docs: [skip ci] update READMEs

* docs: [skip ci] fix code block type

* chore: [skip ci] move generator script
2018-06-04 10:32:39 -04:00
Sven SAULEAU
b6eaaa2496 Merge pull request #8107 from babel/xtuc-patch-3
docs: [skip ci] update polyfill README
2018-06-04 08:46:51 +02:00
Sven SAULEAU
e2471337f4 docs: [skip ci] update polyfill README 2018-06-04 08:46:08 +02:00
Sven SAULEAU
826edd0bd5 Merge pull request #8106 from babel/xtuc-patch-3
update runtime README
2018-06-04 08:43:15 +02:00
Sven SAULEAU
f434a50829 docs: update runtime README 2018-06-04 08:42:48 +02:00
Brian Ng
5895277b32 Bump prettier to v1.13.2 2018-06-03 07:54:39 -05:00
Brian Ng
62114b807b Remove unneeded prettier call in make fix 2018-06-03 07:54:39 -05:00
chocolateboy
2abd7839e1 Fix ReferenceError in the wrapNativeSuper helper (#8100)
Fix a ReferenceError caused by a typo (`_construct` instead of
`construct`) in the external `wrapNativeSuper` helper. (The typo
doesn't usually cause an error in inline helpers because `_construct`
happens to be the default name given to the `construct` helper
function.)
2018-06-02 18:00:02 +02:00
Nicolò Ribaudo
b8dcd6f593 Remove parser support for decorators optional parentheses (#8037)
* Remove parser support for decorators optional parentheses

* Update fixtures
2018-06-02 13:07:15 +02:00
dnalborczyk
fe556c502d fix folder name (#8074) 2018-06-01 17:58:37 +02:00
Peter Leonov
ab62a94399 make isReferenced() recognise ObjectTypeProperty (#8060)
fixes #8057
2018-05-31 00:07:56 +02:00
Nicolò Ribaudo
d83d141e00 Move tests from babylon/ to babel-parserr/ 2018-05-30 22:12:33 +02:00
Nicolò Ribaudo
cb17f07ac9 Update syntax-decorators options (#7938)
* Add decoratorsBeforeExport to the syntax plugin
* Require legacy: true, like in the transform plugin
2018-05-30 22:00:18 +02:00
Logan Smyth
21b9b2e42d Avoid a race condition in CLI directory creation. (#8082) 2018-05-30 10:35:08 -07:00
Erik Arvidsson
2a8ebbe7ae Remove parenthesizedArgument (#7981)
The extra field parenthesizedArgument was never set to true. It was
always set to false and the code that read this was incorrectly
checking if extra was present.

Fixes #7957
2018-05-29 13:58:21 -07:00
Brian Ng
9add6d88f5 Update regenerator version and test retain lines fixture (#8072) 2018-05-29 10:46:05 -07:00
ilya
2d2f37fa6c Update core-js to v2.5.7 (#8064) 2018-05-29 09:47:15 -05:00
Erik Arvidsson
7846eaebaa Do not quote JSX attribute keys for IdentifierName (#8045)
Given the following

```js
a = <F new/>
```

We used to generate:

```js
a = React.createElement(F, {"new": true})
```

but now we generate

```js
a = React.createElement(F, {new: true})
```

If you need to quote these (ie for ES3 you can use
transform-property-literals)
2018-05-27 12:48:18 -04:00
Nicolò Ribaudo
d45ee5e025 Add "decoratorsBeforeExport" option to @babel/generator (#7948)
* Add "decoratorsBeforeExport" option to @babel/generator

* Docs
2018-05-27 08:50:26 +02:00
Brian Ng
f699f1bbbf flow@0.73.0 (#8032) 2018-05-25 16:53:23 -05:00
Sam Goldman
f0283572a5 Support Flow's proto modifier syntax for declared classes (#7978)
<!--
Before making a PR please make sure to read our contributing guidelines
https://github.com/babel/babel/blob/master/CONTRIBUTING.md

For issue references: Add a comma-separated list of a [closing word](https://help.github.com/articles/closing-issues-via-commit-messages/) followed by the ticket number fixed by the PR. It should be underlined in the preview if done correctly.
-->

| Q                        | A <!--(Can use an emoji 👍) -->
| ------------------------ | ---
| Fixed Issues?            | <!-- remove the (`) quotes to link the issues -->
| Patch: Bug Fix?          |
| Major: Breaking Change?  | No
| Minor: New Feature?      | Yes
| Tests Added + Pass?      | Yes
| Documentation PR         | <!-- If so, add `[skip ci]` to your commit message to skip CI -->
| Any Dependency Changes?  |
| License                  | MIT

See eb815be907 for more information about this feature.
    
The proto modifier indicates that a property declared using `x: T` syntax is actually present on the prototype object of the class, rather than an own property.
    
The proto and static modifiers are mutually exclusive, as class declarations don't simultaneously define the static prototype object, as they do the instance prototype.
    
This syntax is only supported on declared classes, not object types, interfaces, or runtime class declarations, and as such should only appear in library definitions.
2018-05-25 15:40:56 -05:00
Logan Smyth
90566103a6 v7.0.0-beta.49 2018-05-25 09:00:02 -07:00
Logan Smyth
cf8058e5b6 Handle kebab-case args in babel-node. (#8046) 2018-05-25 08:40:52 -07:00
Nicolò Ribaudo
90a174e7c4 Transform decorated classes from the export visitor (#8047)
Fixes gh-8041

<!--
Before making a PR please make sure to read our contributing guidelines
https://github.com/babel/babel/blob/master/CONTRIBUTING.md

For issue references: Add a comma-separated list of a [closing word](https://help.github.com/articles/closing-issues-via-commit-messages/) followed by the ticket number fixed by the PR. It should be underlined in the preview if done correctly.
-->

| Q                        | A <!--(Can use an emoji 👍) -->
| ------------------------ | ---
| Fixed Issues?            | #8041
| Patch: Bug Fix?          |👍
| Major: Breaking Change?  |
| Minor: New Feature?      |
| Tests Added + Pass?      | Yes
| Documentation PR         | <!-- If so, add `[skip ci]` to your commit message to skip CI -->
| Any Dependency Changes?  |
| License                  | MIT

<!-- Describe your changes below in as much detail as possible -->
2018-05-25 08:36:30 -07:00
Logan Smyth
9c707f9670 Update docs 2018-05-24 20:57:44 -07:00
Logan Smyth
53e4d74ebe Treat all filenames as absolute paths. (#8044) 2018-05-24 20:56:19 -07:00
Logan Smyth
98ff2ce877 Merge pull request #8023 from loganfsmyth/sync-async
Add a promise-returning *Async version of the transform and parse fns
2018-05-24 19:04:38 -07:00
Henry Zhu
0ffc8ed209 Compile against beta 48 (#8036) 2018-05-24 16:25:39 -07:00
Henry Zhu
e6d198eef5 v7.0.0-beta.48 2018-05-24 15:20:31 -04:00
Logan Smyth
86aacad2bc Disallow coverage on bundles. 2018-05-24 09:15:44 -07:00
Nicolò Ribaudo
6eab6f5863 [Babylon] Take the first set of options for plugins (#7994)
* [Babylon] Take the first set of options for plugins

* Fix test

* Docs
2018-05-24 08:54:32 -07:00
Brian Ng
555ee80f43 Fix some ts test fixtures 2018-05-24 10:03:03 -05:00
Brian Ng
a94cbf760a Set exprAllowed to false when parsing TSNonNullExpression (#7968) 2018-05-24 09:31:08 -05:00
Logan Smyth
0bc3027554 Add a promise version of each of Babel's transform functions. 2018-05-23 21:18:17 -07:00
Logan Smyth
6f3093b557 Track the sync and async implementations in the same files. 2018-05-23 21:18:15 -07:00
Jimmy Jia
7489f8da7b Fix include/exclude syntax in preset-env README [ci skip] (#8020) 2018-05-23 22:09:54 -04:00
Nicolò Ribaudo
dccaec7691 Update types (BigInt) 2018-05-24 00:30:57 +02:00
Nicolò Ribaudo
c992f5b61e Remove duplicated test (in the old babylon folder) 2018-05-24 00:30:57 +02:00
Logan Smyth
5cd1276a27 Expose the Flow 'all' option on the preset too. (#8016)
| Q                        | A <!--(Can use an emoji 👍) -->
| ------------------------ | ---
| Fixed Issues?            | 
| Patch: Bug Fix?          | 
| Major: Breaking Change?  |
| Minor: New Feature?      |
| Tests Added + Pass?      | Yes
| Documentation PR         | <!-- If so, add `[skip ci]` to your commit message to skip CI -->
| Any Dependency Changes?  |
| License                  | MIT

The `all` option landed in https://github.com/babel/babel/pull/7934/files#diff-3a8233bcd2766d2c7d87f23f944f7726R3 but it is only exposed from the plugin, not the preset, so this exposes it there too since the flow preset is what we want people to use.
2018-05-23 13:40:22 -07:00
Justin Ridgewell
2af7a33c4e Fix class inheritance in IE10 (#7969)
* Revert "Move subclass inheritance to end (#7772)"

This reverts commit f8ab9466d3.

* Only use getPrototypeOf if setPrototypeOf is implemented

* Update fixtures

* Helpers updates

* Update fixtures

* Fall back to getPrototypeOf

* Update fixtures
2018-05-23 16:21:21 -04:00
Nicolò Ribaudo
ffe04d9195 [babylon] Refactor mixin plugins handling & validation (#7999) 2018-05-23 15:28:05 -04:00
Nicolò Ribaudo
b33823e7f8 Better error message for invalid decorators syntax (#7986) 2018-05-23 15:26:35 -04:00
Logan Smyth
007bfb6565 Merge pull request #8010 from loganfsmyth/babel-node-options
Add more of babel-cli's options to babel-node too for consistency.
2018-05-23 09:47:58 -07:00
Logan Smyth
c8faa34848 Only set '.babelrc' option if user explicitly set it. 2018-05-23 09:25:43 -07:00
Logan Smyth
5bcca0123a Add --env-name option to babel-node, like babel-cli's option. 2018-05-23 09:25:05 -07:00
Logan Smyth
1d987fb655 Add --config-file option to babel-node, like babel-cli's option. 2018-05-23 09:23:50 -07:00
Logan Smyth
06e5c46c8d Fix typo in option validation. 2018-05-23 09:23:14 -07:00
Sven SAULEAU
52b800decb Add no-babelrc option in babel-node (#5621)
<!-- 
Before making a PR please make sure to read our contributing guidelines 
https://github.com/babel/babel/blob/master/CONTRIBUTING.md

For any issue references: Add a comma-separated list of a [closing word](https://help.github.com/articles/closing-issues-via-commit-messages/) followed by the ticket number fixed by the PR
-->

| Q                        | A <!--(yes/no) -->
| ------------------------ | ---
| Patch: Bug Fix?          | 
| Major: Breaking Change?  | 
| Minor: New Feature?      | y
| Deprecations?            | 
| Spec Compliancy?         | 
| Tests Added/Pass?        | y/y
| Fixed Tickets            | #5616
| License                  | MIT
| Doc PR                   | <!-- if yes, add `[skip ci]` to your commit message to skip CI builds -->
| Dependency Changes       | 

<!-- Describe your changes below in as much detail as possible -->

Once merged I will make the corresponding documentation changes on the website (in a 7 branch)
2018-05-23 09:19:39 -07:00
Sven SAULEAU
01d969a182 Merge pull request #8009 from babel/xtuc-patch-2
update AST spec - interpreter
2018-05-23 12:57:10 +02:00
Sven SAULEAU
7d99a96f9f docs: [skip ci] add InterpreterDirective 2018-05-23 09:50:23 +02:00
Sven SAULEAU
ad1de09b5f docs: [skip ci] update AST spec 2018-05-23 09:42:33 +02:00
Logan Smyth
6b91d6434d Add a try/catch on inline data-uri sourcemaps too, and add debug logging. 2018-05-22 23:38:16 -07:00
Michael Lavina
18796173ab feat(sourcemap): parse external source maps when normalizing (#7980) 2018-05-22 23:29:10 -07:00
Logan Smyth
eb3334a14e Merge pull request #7955 from loganfsmyth/typescript-filename-required
Verify that files are .ts/.tsx before treating as Typescript files.
2018-05-22 22:41:39 -07:00
Logan Smyth
5e00c96368 Handle Infinity, -Infinity, NaN, and -0 in t.valueToNode(). (#8005)
| Q                        | A <!--(Can use an emoji 👍) -->
| ------------------------ | ---
| Fixed Issues?            | Fixes #8001
| Patch: Bug Fix?          | Y
| Major: Breaking Change?  | Not unless things were relying on a very specific AST structure as output
| Minor: New Feature?      |
| Tests Added + Pass?      | Yes
| Documentation PR         | <!-- If so, add `[skip ci]` to your commit message to skip CI -->
| Any Dependency Changes?  |
| License                  | MIT

The filed bug was for `-0`, but I also realize that `numericLiteral` also shouldn't be getting `-Infinity`/`Infinity` or `NaN` since those just get stringified with the JS-standard stringification logic which means we get a reference to `NaN` or `Infinity` identifiers, which could have been shadowed in a local scope and thus not be the right value. I've avoided that by generating `NaN` as `0/0` and the infinity values as `1/0` and `-1/0`.
2018-05-22 14:37:06 -07:00
Henry Zhu
b4d18f4764 Bigint Support without transform (#8006) 2018-05-22 15:31:34 -04:00
Brian Ng
981bff08e4 Fix some flow issues in @babel/parser flow plugin (#8002) 2018-05-22 10:48:49 -07:00
Nicolò Ribaudo
7d641d2e74 Update babel-types docs (InterpreterDirective) [skip ci] (#8004)
Introduced in #7928
2018-05-22 17:50:15 +02:00
Logan Smyth
f2882d570a Tests for react/ts compat and flow/ts compat. 2018-05-21 21:21:00 -07:00
Logan Smyth
cc5aeb3b50 Allow .ts and .tsx test fixtures. 2018-05-21 20:31:40 -07:00
Logan Smyth
d164f820e6 Merge pull request #7928 from loganfsmyth/shebang-node
Create InterpreterDirective AST node type and use to replace babel/core File's 'shebang' handling
2018-05-21 20:02:12 -07:00
Logan Smyth
43aa61d6be Make the typescript preset require a filename unless the user configured it for general use. 2018-05-21 18:34:50 -07:00
Logan Smyth
ca1c98b255 Allow .overrides and .env inside presets. 2018-05-21 18:23:07 -07:00
Logan Smyth
0963dbddea Rely on Babylon for interpreter directive parsing, instead of babel/core. 2018-05-21 18:19:59 -07:00
Logan Smyth
2058e0686e Add support for an InterpreterDirective AST node. 2018-05-21 18:19:58 -07:00
Logan Smyth
c0013264b7 Add tests for interpreter directive with retainLines and sourcemaps. 2018-05-21 18:08:32 -07:00
Logan Smyth
442ead701c Fix a few out-of-order test results. 2018-05-21 18:08:31 -07:00
Logan Smyth
5fb3696955 Avoid flow errors now that we've renamed Babylon to babel-parser. 2018-05-21 18:06:17 -07:00
Logan Smyth
69cca412eb Make the filename option, as exposed to the plugins, consistently relative to the working directory (#7956)
| Q                        | A <!--(Can use an emoji 👍) -->
| ------------------------ | ---
| Fixed Issues?            | 
| Patch: Bug Fix?          | Y
| Major: Breaking Change?  | N
| Minor: New Feature?      |
| Tests Added + Pass?      | Yes
| Documentation PR         | <!-- If so, add `[skip ci]` to your commit message to skip CI -->
| Any Dependency Changes?  |
| License                  | MIT

Currently the `opts.filename` value exposed to plugins is just whatever the user passed. While it _could_ be relative to the working directory, if Babel was passed an absolute URL, it'll be absolute.

This PR explicitly ensures the filename is a relative path based on the working directory. This also exposes an officially endorsed API for reading the working directory path.
2018-05-21 17:10:57 -07:00
Mike Nason
3bee37b14d fix typo in error message (#7995) 2018-05-21 12:18:09 -07:00
Miguel Albernaz
bc757c8b75 passes the jsxPragma options from preset-typescript to plugin-transform-typescript (#7990) 2018-05-21 14:33:43 -04:00
Conor Hastings
c558dedd7b fix typo of babel in readme (#7992) [skip ci] 2018-05-21 07:42:13 +02:00
Justin Ridgewell
0879a6d608 Subsume json (#7985)
* Add Subsume JSON transform

https://github.com/tc39/proposal-json-superset is at stage 3.

This allows U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR to appear unescaped inside strings and directives.

* Move to Stage 3

* Break diretive parsing

* Update README

* Handle multi-escape sequences

* Remove babylon files after rename
2018-05-19 15:32:05 -04:00
Henry Zhu
51eef099b3 fixes [skip ci] 2018-05-19 00:12:26 -04:00
Chaitanya Kumar Kamatham
daf0ca8680 Rename "babylon" to "@babel/parser" (#7937) 🎉 2018-05-19 00:03:05 -04:00
Justin Ridgewell
0200a3e510 Build InterfaceTypeAnnotation generated type code (#7982) 2018-05-18 14:41:19 -04:00
Justin Ridgewell
27c39c512d Class private properties (#7842)
* Update member-expression-to-functions

1. Babel using British spellings, so `memoise`
2. Provide a helper `AssignmentMemoiser` class, which will assign the memo'd value with the `n`th access.

* Private properties!

* Fixes

* Tests

* Update helper name

* Fix privates that reference other privates

* Don't extend a builtin

* Rebase
2018-05-18 14:03:23 -04:00
Ben Newman
70eb206c03 TypeScript: Fix TSInferType .typeParameter type. (#7967)
Follow-up to https://github.com/babel/babel/pull/7404

There is no TypeParameter type in the Babylon TypeScript AST hierarchy.
Flow does have a TypeParameter type, but it should not be confused with
the TypeScript TSTypeParameter, since Flow !== TypeScript, and the types
have totally different fields. Instead, the .typeParameter.type of a
Babylon-parsed TSInferType node should be TSTypeParameter.

It would probably be fine to leave the declared type of the TSInferType
.typeParameter field as TSType instead of TSTypeParameter, but the more
specific TSTypeParameter type should be safe/correct, since the TypeScript
parseInferType function always uses SyntaxKind.TypeParameter:
66d6e5e6e0/src/compiler/parser.ts (L3006)

I noticed this typo because it has been causing ast-types test failures
lately, e.g. https://travis-ci.org/benjamn/ast-types/jobs/369634972
2018-05-18 10:15:48 -05:00
Nicolò Ribaudo
229179b8aa Update babel-types (flow internal slots) (#7977) 2018-05-18 08:47:31 -05:00
Sam Goldman
6baa36cdc5 Support Flow's inline interface syntax (#7973)
* Support Flow's inline interface syntax

* Fix babel-generator
2018-05-18 08:11:27 -05:00
Sam Goldman
a40f54f847 Add support for explicit type arguments in new and call expressions (#7934)
* Add all option to babel-plugin-syntax-flow

The Flow parser has some conditional logic based on whether types should
be parsed or not, which is based on either (a) the @flow pragma in the
docblock of the file of (b) the `all` configuration, provided via
command line or .flowconfig.

This commit adds the ability to provide the `all` configuration to
Babel as well, via the syntax-flow plugin. This should be set to `true`
if the project uses all=true.

* Parse @flow pragma

The Flow parser has some conditional logic based on whether types should
be parsed or not, which is based on either (a) the @flow pragma in the
docblock of the file of (b) the `all` configuration, provided via
command line or .flowconfig.

This commit parses the @flow (or @noflow) pragma from the first comment
in the source file. Directives are allowed to appear before the comment.

* WIP: add tests for explicit type arguments

This commit includes tests which have unexpected output, but will change
to the expected output as later commits add parsing support for various
features.

* Parse type arguments in new expressions

* Parse type arguments in call expressions

* Parse optional call expressions with explicit type args

* Add explicit type arguments to babel-types

Flow calls these typeArguments instead of typeParameters, which clearly
separates formal/actual parameters, and mirrors the existing arguments
key.

The existing definitions to support TypeScript also included Flow's
TypeParameterInstantiation node type, which I've moved to the the new
field.

* Add support for explicit type arguments to babel-generator

* Add test for explicit type args to transform-flow-strip-types plugin

* Oops. Forgot to regenerate the babel-types README.

* Fix Flow parser shouldParseTypes() function

I was looking at `options.all`, but the correct property ws
`options.flowAll`. Oops!

* Remove typeapp_call from whitelist of expected failures

Now that Babylon parses this syntax extension, we can remove the
typeapp_call tests from the list of expected differences.

Note that I am using the `flowAll` option, mirroring the behavior of the
Flow tests, which assume types without requiring the `@flow` pragma.

* Use Babylon plugin options instead of parser options

* Parse optional call expressions type arguments unambiguously
2018-05-18 08:05:16 -05:00
Nicolò Ribaudo
6226c52f43 Add "legacy" prefix to legacy decorators tests (#7975) 2018-05-18 14:46:07 +02:00
Lars Willighagen
25153359f7 helper-plugin-utils: Move README [skip ci] (#7972)
Move README from src to package root, as in other packages.

Closes #7971
2018-05-18 10:00:25 +02:00
Nicolò Ribaudo
2351a638b5 Fix bugs in the _wrapNativeSuper helper (#7533)
* Remove second wrapper from _wrapNativeSuper

* Fix tests on node 4

I DON'T KNOW WHY IT WORKS.

* Update fixtures

* Use Reflect.construct

* Parens

* Fix things

* Fix things

* Undo changes

* Fix with sham

* Typo
2018-05-18 00:04:12 +02:00
Rubén Norte
bc6f0f989d Re-add support for local Flow bindings (TypeAlias, OpaqueTypeAlias and Interface) (#7900) 2018-05-17 10:54:14 -07:00
Sam Goldman
af7ab71486 Allow flow internal slot properties to be optional (#7959)
See 23d1b1c5f2
2018-05-17 19:01:03 +02:00
Logan Smyth
ac13c302f7 Merge pull request #7929 from loganfsmyth/cli-refactoring
Refactor babel-cli to use async functions for async handling, and centralize option loading
2018-05-16 20:58:46 -07:00
Sam Goldman
b396cdcbe5 Internal slot properties (#7947)
* Support internalSlots to babel-types and babel-generator

* Parsing support for internal slot properties

* Print internal slots in babel-generator

* Add whitespace before first internal slot property
2018-05-16 22:48:12 -05:00
Michal Artazov
8dcfabd0d7 update core-js to 2.5.6 (#7950) 2018-05-16 10:08:19 -07:00
Nicolò Ribaudo
e45d5c3b65 Add an option to Babylon to have decorators before export (#7869)
* Add support for plugin options in Babylon

They work similarly to how they work in Babel. e.g.
  babylon.parse({
    options: [
      "plugin1",
      ["plugin2", { option: true }]
    ]
  });

The inernal api to get an option is
  this.getPluginOption("pluginName", "option")
If the plugin isn't defined, it returns undefined.

* Add Babylon option decorators.secoratorsBeforeExport

* Nit
2018-05-15 11:39:53 -05:00
Logan Smyth
8ff675ad69 Refactor CLI to use promises/async fns. 2018-05-14 23:07:50 -07:00
Logan Smyth
a955efa3e3 Ensure that calling register fully resets the state. (#7930) 2018-05-14 23:04:56 -07:00
Logan Smyth
51db3e9a5d Bug fixing for Node 10 (#7931) 2018-05-14 23:02:01 -07:00
Logan Smyth
41ca312545 Define a clear separation between Babel and CLI options. 2018-05-14 22:03:47 -07:00
Logan Smyth
a192f8beb4 Limit node version to current LTS. 2018-05-14 21:54:16 -07:00
10680 changed files with 391547 additions and 386432 deletions

View File

@@ -34,7 +34,7 @@ jobs:
build:
working_directory: ~/babel
docker:
- image: circleci/node:9
- image: circleci/node:10
steps:
- checkout
- restore-cache: *restore-yarn-cache

View File

@@ -22,4 +22,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/test/expressions
packages/babel-parser/test/expressions

View File

@@ -1,8 +1,10 @@
<!--
Before making a PR please make sure to read our contributing guidelines
Before making a PR, please read our contributing guidelines
https://github.com/babel/babel/blob/master/CONTRIBUTING.md
For issue references: Add a comma-separated list of a [closing word](https://help.github.com/articles/closing-issues-via-commit-messages/) followed by the ticket number fixed by the PR. It should be underlined in the preview if done correctly.
For issue references: Add a comma-separated list of a [closing word](https://help.github.com/articles/closing-issues-via-commit-messages/) followed by the ticket number fixed by the PR. (it should be underlined in the preview if done correctly)
If you are making a change that should have a docs update: submit another PR to https://github.com/babel/website
-->
| Q                       | A <!--(Can use an emoji 👍) -->
@@ -12,7 +14,7 @@ For issue references: Add a comma-separated list of a [closing word](https://hel
| Major: Breaking Change? |
| Minor: New Feature? |
| Tests Added + Pass? | Yes
| Documentation PR | <!-- If so, add `[skip ci]` to your commit message to skip CI -->
| Documentation PR Link | <!-- If only readme change, add `[skip ci]` to your commits -->
| Any Dependency Changes? |
| License | MIT

2
.gitignore vendored
View File

@@ -42,6 +42,6 @@ packages/babel-preset-env-standalone/babel-preset-env.js
packages/babel-preset-env-standalone/babel-preset-env.min.js
/codemods/*/lib
/codemods/*/node_modules
/packages/babylon/build
/packages/babel-parser/build
.idea/
/.changelog

View File

@@ -8,6 +8,7 @@ cache:
- node_modules
node_js:
# We test the latest version on circleci
- '9'
- '8'
- '6'
@@ -22,14 +23,14 @@ before_install:
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'
- 'if [ "$JOB" = "babel-parser-flow-tests" ]; then make bootstrap-flow; fi'
- 'if [ "$JOB" = "babel-parser-test262-tests" ]; then make bootstrap-test262; fi'
script:
- 'if [ "$JOB" = "test" ]; then make test-ci; fi'
- 'if [ "$JOB" = "lint" ]; then make lint && make flow; fi'
- 'if [ "$JOB" = "babylon-flow-tests" ]; then make test-flow-ci; fi'
- 'if [ "$JOB" = "babylon-test262-tests" ]; then make test-test262-ci; fi'
- 'if [ "$JOB" = "babel-parser-flow-tests" ]; then make test-flow-ci; fi'
- 'if [ "$JOB" = "babel-parser-test262-tests" ]; then make test-test262-ci; fi'
matrix:
fast_finish: true
@@ -37,9 +38,9 @@ matrix:
- node_js: "node"
env: JOB=lint
- node_js: "node"
env: JOB=babylon-flow-tests
env: JOB=babel-parser-flow-tests
- node_js: "node"
env: JOB=babylon-test262-tests
env: JOB=babel-parser-test262-tests
notifications:
slack:

View File

@@ -2452,7 +2452,7 @@ Also, thanks to [@mucsi96](https://github.com/mucsi96) for catching the extraneo
#### Bug Fix
* `babel-core`
* [#3508](https://github.com/babel/babel/pull/3510) Assign `_this` to `this` when there is no `Superclass` in a `Class` when using class properties. Fixes T7364. ([@ehjay](https://github.com/ehjay))
* [#3508](https://github.com/babel/babel/pull/3508) Assign `_this` to `this` when there is no `Superclass` in a `Class` when using class properties. Fixes T7364. ([@ehjay](https://github.com/ehjay))
The fix correctly set this: `var _this;` -> `var _this = this;`

View File

@@ -24,7 +24,7 @@ contributing, please read the
## Not sure where to start?
- If you aren't just making a documentation change, you'll probably want to learn a bit about a few topics.
- [ASTs](https://en.wikipedia.org/wiki/Abstract_syntax_tree) (Abstract Syntax Tree): The Babel AST [spec](https://github.com/babel/babel/blob/master/packages/babylon/ast/spec.md) is a bit different from [ESTree](https://github.com/estree/estree). The differences are listed [here](https://github.com/babel/babel/tree/master/packages/babylon#output).
- [ASTs](https://en.wikipedia.org/wiki/Abstract_syntax_tree) (Abstract Syntax Tree): The Babel AST [spec](https://github.com/babel/babel/blob/master/packages/babel-parser/ast/spec.md) is a bit different from [ESTree](https://github.com/estree/estree). The differences are listed [here](https://github.com/babel/babel/tree/master/packages/babel-parser#output).
- Check out [`/doc`](https://github.com/babel/babel/tree/master/doc) for information about Babel's internals
- Check out [the Babel Plugin Handbook](https://github.com/thejameskyle/babel-handbook/blob/master/translations/en/plugin-handbook.md#babel-plugin-handbook) - core plugins are written the same way as any other plugin!
- Check out [AST Explorer](http://astexplorer.net/#/scUfOmVOG5) to learn more about ASTs or make your own plugin in the browser
@@ -226,19 +226,19 @@ If the test requires a minimum Node version, you can add `minNodeVersion` (must
}
```
#### `babylon`
#### `@babel/parser` (babylon)
Writing tests for Babylon is very
Writing tests for the babel parser is very
similar to the other packages.
Inside the `packages/babylon/tests/fixtures` folder are categories/groupings of test fixtures (es2015, flow,
Inside the `packages/babel-parser/tests/fixtures` folder are categories/groupings of test fixtures (es2015, flow,
etc.). To add a test, create a folder under one of these groupings (or create a new one) with a
descriptive name, and add the following:
* Create an `input.js` file that contains the code you want Babylon to parse.
* Create an `input.js` file that contains the code you want the babel parser to parse.
* Add an `output.json` file with the expected parser output. For added convenience, if there is no `output.json` present, the test runner will generate one for you.
After writing tests for babylon, just build it by running:
After writing tests for @babel/parser, just build it by running:
```sh
$ make build
@@ -247,17 +247,17 @@ $ make build
Then, to run the tests, use:
```sh
$ TEST_ONLY=babylon make test-only
$ TEST_ONLY=babel-parser make test-only
```
#### Bootstrapping expected output
For both `@babel/plugin-x` and `babylon`, you can easily generate an `output.js`/`output.json` automatically by just providing `input.js` and running the tests as you usually would.
For both `@babel/plugin-x` and `@babel/parser`, you can easily generate an `output.js`/`output.json` automatically by just providing `input.js` and running the tests as you usually would.
```
// Example
- packages
- babylon
- babel-parser
- test
- fixtures
- comments
@@ -309,14 +309,14 @@ Note that the code shown in Chrome DevTools is compiled code and therefore diffe
- Create a new issue that describes the proposal (ex: [#538](https://github.com/babel/babylon/issues/538)). Include any relevant information like proposal repo/author, examples, parsing approaches, meeting notes, presentation slides, and more.
- The pull request should include:
- [ ] An update to the [plugins](https://github.com/babel/babel/tree/master/packages/babylon#plugins) part of the readme. Add a new entry to that list for the new plugin flag (and link to the proposal)
- [ ] If any new nodes or modifications need to be added to the AST, update [ast/spec.md](https://github.com/babel/babel/bloc/master/packages/babylon/ast/spec.md)
- [ ] Make sure you use the `this.hasPlugin("plugin-name-here")` check in Babylon so that your new plugin code only runs when that flag is turned on (not default behavior)
- [ ] An update to the [plugins](https://github.com/babel/babel/tree/master/packages/babel-parser#plugins) part of the readme. Add a new entry to that list for the new plugin flag (and link to the proposal)
- [ ] If any new nodes or modifications need to be added to the AST, update [ast/spec.md](https://github.com/babel/babel/bloc/master/packages/babel-parser/ast/spec.md)
- [ ] Make sure you use the `this.hasPlugin("plugin-name-here")` check in the babel parser so that your new plugin code only runs when that flag is turned on (not default behavior)
- [ ] Add failing/passing tests according to spec behavior
- Start working about the Babel transform itself!
## Internals
- AST spec ([babylon/ast/spec.md](https://github.com/babel/babel/blob/master/packages/babylon/ast/spec.md))
- AST spec ([babel-parser/ast/spec.md](https://github.com/babel/babel/blob/master/packages/babel-parser/ast/spec.md))
- Versioning ([doc/design/versioning.md](https://github.com/babel/babel/blob/master/doc/design/versioning.md))
- Monorepo ([doc/design/monorepo.md](https://github.com/babel/babel/blob/master/doc/design/monorepo.md))
- Compiler environment support ([doc/design/compiler-environment-support.md](https://github.com/babel/babel/blob/master/doc/design/compiler-environment-support.md))

View File

@@ -98,7 +98,7 @@ function buildRollup(packages) {
format: "cjs",
plugins: [
rollupBabel({
envName: "babylon",
envName: "babel-parser",
}),
rollupNodeResolve(),
],
@@ -113,7 +113,7 @@ function buildRollup(packages) {
}
gulp.task("build", function() {
const bundles = ["packages/babylon"];
const bundles = ["packages/babel-parser"];
return merge([buildBabel(/* exclude */ bundles), buildRollup(bundles)]);
});

View File

@@ -1,6 +1,6 @@
MAKEFLAGS = -j1
FLOW_COMMIT = 395e045c18d537fcbbc552a96ef2cdcd70b4ab52
TEST262_COMMIT = 40883f4c6ae17e073dfd03e34f73a6bf8c855595
TEST262_COMMIT = f90a52b39609a620c0854e0bd0b3a906c930fd17
# Fix color output until TravisCI fixes https://github.com/travis-ci/travis-ci/issues/7967
export FORCE_COLOR = true
@@ -17,8 +17,6 @@ build: clean clean-lib
# generate flow and typescript typings
node scripts/generators/flow.js > ./packages/babel-types/lib/index.js.flow
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_COVERAGE)", "true")
make build-standalone
make build-preset-env-standalone
@@ -49,12 +47,10 @@ flow:
./node_modules/.bin/flow check --strip-root
lint:
./node_modules/.bin/eslint scripts $(SOURCES) '*.js' '**/.*.js' --format=codeframe --rulesdir="./scripts/eslint_rules"
./node_modules/.bin/eslint scripts $(SOURCES) '*.js' --format=codeframe --rulesdir="./scripts/eslint_rules"
fix:
# 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"
./node_modules/.bin/eslint scripts $(SOURCES) '*.js' --format=codeframe --fix --rulesdir="./scripts/eslint_rules"
clean: test-clean
rm -rf packages/babel-polyfill/browser*
@@ -87,12 +83,12 @@ bootstrap-flow:
cd build/flow && git checkout $(FLOW_COMMIT)
test-flow:
node scripts/tests/flow/run_babylon_flow_tests.js
node scripts/tests/flow/run_babel_parser_flow_tests.js
test-flow-ci: bootstrap test-flow
test-flow-update-whitelist:
node scripts/tests/flow/run_babylon_flow_tests.js --update-whitelist
node scripts/tests/flow/run_babel_parser_flow_tests.js --update-whitelist
bootstrap-test262:
rm -rf ./build/test262
@@ -101,12 +97,12 @@ bootstrap-test262:
cd build/test262 && git checkout $(TEST262_COMMIT)
test-test262:
node scripts/tests/test262/run_babylon_test262.js
node scripts/tests/test262/run_babel_parser_test262.js
test-test262-ci: bootstrap test-test262
test-test262-update-whitelist:
node scripts/tests/test262/run_babylon_test262.js --update-whitelist
node scripts/tests/test262/run_babel_parser_test262.js --update-whitelist
publish:
git pull --rebase

View File

@@ -16,7 +16,7 @@ module.exports = function(api) {
switch (env) {
// Configs used during bundling builds.
case "babylon":
case "babel-parser":
case "standalone":
convertESM = false;
ignoreLib = false;
@@ -24,7 +24,7 @@ module.exports = function(api) {
case "production":
// Config during builds before publish.
envOpts.targets = {
node: 6,
node: "6.9",
};
break;
case "development":
@@ -69,7 +69,7 @@ module.exports = function(api) {
].filter(Boolean),
overrides: [
{
test: "packages/babylon",
test: "packages/babel-parser",
plugins: [
"babel-plugin-transform-charcodes",
["@babel/transform-for-of", { assumeArray: true }],

View File

@@ -1,6 +1,6 @@
{
"name": "@babel/plugin-codemod-object-assign-to-object-spread",
"version": "7.0.0-beta.47",
"version": "7.0.0-beta.52",
"description": "Transforms Object.assign into object spread syntax",
"repository": "https://github.com/babel/babel/tree/master/codemods/babel-plugin-codemod-object-assign-to-object-spread",
"license": "MIT",
@@ -10,14 +10,14 @@
"@babel/plugin"
],
"dependencies": {
"@babel/plugin-syntax-object-rest-spread": "7.0.0-beta.47"
"@babel/plugin-syntax-object-rest-spread": "7.0.0-beta.52"
},
"peerDependencies": {
"@babel/core": "7.0.0-beta.47"
"@babel/core": ">=7.0.0-beta.50 <7.0.0-rc.0"
},
"devDependencies": {
"@babel/core": "7.0.0-beta.47",
"@babel/helper-plugin-test-runner": "7.0.0-beta.47"
"@babel/core": "7.0.0-beta.52",
"@babel/helper-plugin-test-runner": "7.0.0-beta.52"
},
"publishConfig": {
"access": "public"

View File

@@ -1,6 +1,6 @@
{
"name": "@babel/plugin-codemod-optional-catch-binding",
"version": "7.0.0-beta.47",
"version": "7.0.0-beta.52",
"description": "Remove unused catch bindings",
"repository": "https://github.com/babel/babel/tree/master/codemods/babel-plugin-codemod-remove-unused-catch-binding",
"license": "MIT",
@@ -10,13 +10,13 @@
"@babel/plugin"
],
"dependencies": {
"@babel/plugin-syntax-optional-catch-binding": "7.0.0-beta.47"
"@babel/plugin-syntax-optional-catch-binding": "7.0.0-beta.52"
},
"peerDependencies": {
"@babel/core": "7.0.0-beta.47"
"@babel/core": ">=7.0.0-beta.50 <7.0.0-rc.0"
},
"devDependencies": {
"@babel/core": "7.0.0-beta.47",
"@babel/helper-plugin-test-runner": "7.0.0-beta.47"
"@babel/core": "7.0.0-beta.52",
"@babel/helper-plugin-test-runner": "7.0.0-beta.52"
}
}

View File

@@ -1 +1 @@
The [AST specification](https://github.com/babel/babel/blob/master/packages/babylon/ast/spec.md) has been moved to the Babylon package, `packages/babylon`.
The [AST specification](https://github.com/babel/babel/blob/master/packages/babel-parser/ast/spec.md) has been moved to the babel parser package, `packages/babel-parser`.

View File

@@ -1,6 +1,6 @@
{
"lerna": "2.0.0-rc.4",
"version": "7.0.0-beta.47",
"lerna": "2.11.0",
"version": "7.0.0-beta.52",
"changelog": {
"repo": "babel/babel",
"cacheDir": ".changelog",

View File

@@ -160,9 +160,15 @@ declare module "convert-source-map" {
fromComment(str: string): Converter,
fromMapFileComment(str: string): Converter,
fromSource(str: string): Converter,
fromMapFileSource(str: string): Converter,
fromMapFileSource(str: string, dir: string): Converter,
removeComments(str: string): string,
removeMapFileComments(str: string): string,
generateMapFileComment(path: string, options?: ?{ multiline: boolean }): string,
};
}
declare module "js-levenshtein" {
declare module.exports: {
(string, string): number,
};
}

View File

@@ -10,30 +10,29 @@
"test": "make test"
},
"devDependencies": {
"@babel/cli": "7.0.0-beta.46",
"@babel/core": "7.0.0-beta.46",
"@babel/plugin-transform-modules-commonjs": "7.0.0-beta.46",
"@babel/preset-env": "7.0.0-beta.46",
"@babel/preset-flow": "7.0.0-beta.46",
"@babel/preset-stage-0": "7.0.0-beta.46",
"@babel/register": "7.0.0-beta.46",
"@babel/cli": "7.0.0-beta.51",
"@babel/core": "7.0.0-beta.51",
"@babel/plugin-transform-modules-commonjs": "7.0.0-beta.51",
"@babel/preset-env": "7.0.0-beta.51",
"@babel/preset-flow": "7.0.0-beta.51",
"@babel/preset-stage-0": "7.0.0-beta.51",
"@babel/register": "7.0.0-beta.51",
"babel-core": "^7.0.0-0",
"babel-eslint": "^8.0.1",
"babel-eslint": "^8.2.5",
"babel-jest": "^22.4.1",
"babel-loader": "8.0.0-beta.0",
"babel-plugin-transform-charcodes": "^0.1.0",
"babylon": "7.0.0-beta.46",
"browserify": "^13.1.1",
"bundle-collapser": "^1.2.1",
"chalk": "^2.3.2",
"charcodes": "^0.1.0",
"derequire": "^2.0.2",
"enhanced-resolve": "^3.0.0",
"eslint": "^4.18.2",
"eslint": "^5.0.1",
"eslint-config-babel": "^7.0.2",
"eslint-plugin-flowtype": "^2.20.0",
"eslint-plugin-prettier": "^2.5.0",
"flow-bin": "^0.66.0",
"eslint-plugin-flowtype": "^2.49.3",
"eslint-plugin-prettier": "^2.6.1",
"flow-bin": "^0.75.0",
"graceful-fs": "^4.1.11",
"gulp": "^4.0.0",
"gulp-babel": "^8.0.0-beta.2",
@@ -46,19 +45,19 @@
"gulp-watch": "^5.0.0",
"husky": "^0.14.3",
"jest": "^22.4.2",
"lerna": "2.0.0",
"lerna": "^2.11.0",
"lerna-changelog": "^0.5.0",
"lint-staged": "^6.0.1",
"lodash": "^4.17.5",
"merge-stream": "^1.0.1",
"output-file-sync": "^2.0.0",
"prettier": "1.11.1",
"prettier": "1.13.2",
"pump": "^1.0.2",
"rimraf": "^2.4.3",
"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",
"test262-stream": "^1.2.0",
"through2": "^2.0.0",
"uglify-js": "^2.4.16",
"vinyl-buffer": "^1.0.1",
@@ -68,7 +67,7 @@
"webpack-stream": "^4.0.0"
},
"engines": {
"node": ">= 6.x <= 9.x",
"node": ">= 6.9.0 <= 11.0.0-0",
"npm": ">= 2.x <= 5.x",
"yarn": ">=0.27.5 || >=1.0.0-20170811"
},
@@ -89,7 +88,7 @@
"/node_modules/",
"/test/fixtures/",
"/test/debug-fixtures/",
"/babylon/test/expressions/",
"/babel-parser/test/expressions/",
"/test/tmp/",
"/test/__data__/",
"/test/helpers/",
@@ -106,6 +105,12 @@
"/test/(fixtures|tmp|__data__)/",
"<rootDir>/(packages|codemods)/[^/]+/lib/"
],
"coveragePathIgnorePatterns": [
"/node_modules/",
"<rootDir>/packages/babel-standalone/babel(\\.min)?\\.js",
"<rootDir>/packages/babel-preset-env-standalone/babel-preset-env(\\.min)?\\.js",
"/test/(fixtures|tmp|__data__)/"
],
"modulePathIgnorePatterns": [
"/test/fixtures/",
"/test/tmp/",

View File

@@ -14,21 +14,21 @@ 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`](/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/parser`](/packages/@babel/parser) | [![npm](https://img.shields.io/npm/v/@babel/parser.svg?maxAge=2592000)](https://www.npmjs.com/package/@babel/parser) | [![Dependency Status](https://david-dm.org/babel/babel.svg?path=packages/babel-parser)](https://david-dm.org/babel/babel?path=packages/babel-parser) |
| [`@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`](/packages/babylon)
- The parser: [`@babel/parser`](/packages/babel-parser)
- 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)
The flow goes like this:
input string -> `babylon` parser -> `AST` -> transformer[s] -> `AST` -> `@babel/generator` -> output string
input string -> `@babel/parser` parser -> `AST` -> transformer[s] -> `AST` -> `@babel/generator` -> output string
Check out the [`babel-handbook`](https://github.com/thejameskyle/babel-handbook/blob/master/translations/en/plugin-handbook.md#introduction) for more information on this.

View File

@@ -2,20 +2,18 @@
> Babel command line.
In addition, various entry point scripts live in the top-level package at `@babel/cli/bin`.
There is a shell-executable utility script, `babel-external-helpers.js`, and the main Babel cli script, `babel.js`.
See our website [@babel/cli](https://babeljs.io/docs/en/next/babel-cli.html) for more information or the [issues](https://github.com/babel/babel/issues?utf8=%E2%9C%93&q=is%3Aissue+label%3A%22pkg%3A%20cli%22+is%3Aopen) associated with this package.
## Install
```sh
npm install --save-dev @babel/core @babel/cli
```
## Usage
Using npm:
```sh
babel script.js
npm install --save-dev @babel/cli
```
For more in depth documentation see: http://babeljs.io/docs/usage/cli/
or using yarn:
```sh
yarn add @babel/cli --dev
```

View File

@@ -1,6 +1,6 @@
{
"name": "@babel/cli",
"version": "7.0.0-beta.47",
"version": "7.0.0-beta.52",
"description": "Babel command line.",
"author": "Sebastian McKenzie <sebmck@gmail.com>",
"homepage": "https://babeljs.io/",
@@ -21,6 +21,7 @@
"fs-readdir-recursive": "^1.0.0",
"glob": "^7.0.0",
"lodash": "^4.17.5",
"mkdirp": "^0.5.1",
"output-file-sync": "^2.0.0",
"slash": "^1.0.0",
"source-map": "^0.5.0"
@@ -29,11 +30,11 @@
"chokidar": "^2.0.3"
},
"peerDependencies": {
"@babel/core": "7.0.0-beta.47"
"@babel/core": ">=7.0.0-beta.50 <7.0.0-rc.0"
},
"devDependencies": {
"@babel/core": "7.0.0-beta.47",
"@babel/helper-fixtures": "7.0.0-beta.47"
"@babel/core": "7.0.0-beta.52",
"@babel/helper-fixtures": "7.0.0-beta.52"
},
"bin": {
"babel": "./bin/babel.js",

View File

@@ -1,154 +1,136 @@
import defaults from "lodash/defaults";
import outputFileSync from "output-file-sync";
import { sync as mkdirpSync } from "mkdirp";
import slash from "slash";
import path from "path";
import fs from "fs";
import * as util from "./util";
let compiledFiles = 0;
export default async function({ cliOptions, babelOptions }) {
const filenames = cliOptions.filenames;
export default function(commander, filenames, opts) {
function write(src, base, callback) {
async function write(src, base) {
let relative = path.relative(base, src);
if (!util.isCompilableExtension(relative, commander.extensions)) {
return process.nextTick(callback);
if (!util.isCompilableExtension(relative, cliOptions.extensions)) {
return false;
}
// remove extension and then append back on .js
relative = util.adjustRelative(relative, commander.keepFileExtension);
relative = util.adjustRelative(relative, cliOptions.keepFileExtension);
const dest = getDest(commander, relative, base);
const dest = getDest(relative, base);
util.compile(
src,
defaults(
{
sourceFileName: slash(path.relative(dest + "/..", src)),
},
opts,
),
function(err, res) {
if (err) return callback(err);
if (!res) return callback();
try {
const res = await util.compile(
src,
defaults(
{
sourceFileName: slash(path.relative(dest + "/..", src)),
},
babelOptions,
),
);
// we've requested explicit sourcemaps to be written to disk
if (
res.map &&
commander.sourceMaps &&
commander.sourceMaps !== "inline"
) {
const mapLoc = dest + ".map";
res.code = util.addSourceMappingUrl(res.code, mapLoc);
res.map.file = path.basename(relative);
outputFileSync(mapLoc, JSON.stringify(res.map));
}
if (!res) return false;
outputFileSync(dest, res.code);
util.chmod(src, dest);
// we've requested explicit sourcemaps to be written to disk
if (
res.map &&
babelOptions.sourceMaps &&
babelOptions.sourceMaps !== "inline"
) {
const mapLoc = dest + ".map";
res.code = util.addSourceMappingUrl(res.code, mapLoc);
res.map.file = path.basename(relative);
outputFileSync(mapLoc, JSON.stringify(res.map));
}
compiledFiles += 1;
outputFileSync(dest, res.code);
util.chmod(src, dest);
util.log(src + " -> " + dest);
return callback(null, true);
},
if (cliOptions.verbose) {
console.log(src + " -> " + dest);
}
return true;
} catch (err) {
if (cliOptions.watch) {
console.error(err);
return false;
}
throw err;
}
}
function getDest(filename, base) {
if (cliOptions.relative) {
return path.join(base, cliOptions.outDir, filename);
}
return path.join(cliOptions.outDir, filename);
}
async function handleFile(src, base) {
const written = await write(src, base);
if (!written && cliOptions.copyFiles) {
const filename = path.relative(base, src);
const dest = getDest(filename, base);
outputFileSync(dest, fs.readFileSync(src));
util.chmod(src, dest);
}
return written;
}
async function handle(filenameOrDir) {
if (!fs.existsSync(filenameOrDir)) return 0;
const stat = fs.statSync(filenameOrDir);
if (stat.isDirectory(filenameOrDir)) {
const dirname = filenameOrDir;
let count = 0;
const files = util.readdir(dirname, cliOptions.includeDotfiles);
for (const filename of files) {
const src = path.join(dirname, filename);
const written = await handleFile(src, dirname);
if (written) count += 1;
}
return count;
} else {
const filename = filenameOrDir;
const written = await handleFile(filename, path.dirname(filename));
return written ? 1 : 0;
}
}
if (!cliOptions.skipInitialBuild) {
if (cliOptions.deleteDirOnStart) {
util.deleteDir(cliOptions.outDir);
}
mkdirpSync(cliOptions.outDir);
let compiledFiles = 0;
for (const filename of cliOptions.filenames) {
compiledFiles += await handle(filename);
}
console.log(
`Successfully compiled ${compiledFiles} ${
compiledFiles !== 1 ? "files" : "file"
} with Babel.`,
);
}
function getDest(commander, filename, base) {
if (commander.relative) return path.join(base, commander.outDir, filename);
return path.join(commander.outDir, filename);
}
function outputDestFolder(outDir) {
const outDirPath = path.resolve(outDir);
if (!fs.existsSync(outDirPath)) {
fs.mkdirSync(outDirPath);
}
}
function handleFile(src, base, callback) {
write(src, base, function(err, res) {
if (err) return callback(err);
if (!res && commander.copyFiles) {
const filename = path.relative(base, src);
const dest = getDest(commander, filename, base);
outputFileSync(dest, fs.readFileSync(src));
util.chmod(src, dest);
}
return callback();
});
}
function sequentialHandleFile(files, dirname, index, callback) {
if (files.length === 0) {
outputDestFolder(commander.outDir);
return;
}
if (typeof index === "function") {
callback = index;
index = 0;
}
const filename = files[index];
const src = path.join(dirname, filename);
handleFile(src, dirname, function(err) {
if (err) return callback(err);
index++;
if (index !== files.length) {
sequentialHandleFile(files, dirname, index, callback);
} else {
callback();
}
});
}
function handle(filename, callback) {
if (!fs.existsSync(filename)) return;
const stat = fs.statSync(filename);
if (stat.isDirectory(filename)) {
const dirname = filename;
if (commander.deleteDirOnStart) {
util.deleteDir(commander.outDir);
}
const files = util.readdir(dirname, commander.includeDotfiles);
sequentialHandleFile(files, dirname, callback);
} else {
write(filename, path.dirname(filename), callback);
}
}
function sequentialHandle(filenames, index = 0) {
const filename = filenames[index];
handle(filename, function(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,
);
}
});
}
if (!commander.skipInitialBuild) {
sequentialHandle(filenames);
}
if (commander.watch) {
if (cliOptions.watch) {
const chokidar = util.requireChokidar();
filenames.forEach(function(filenameOrDir) {
@@ -168,10 +150,9 @@ export default function(commander, filenames, opts) {
filename === filenameOrDir
? path.dirname(filenameOrDir)
: filenameOrDir,
function(err) {
if (err) console.error(err.stack);
},
);
).catch(err => {
console.error(err);
});
});
});
});

View File

@@ -7,26 +7,22 @@ import fs from "fs";
import * as util from "./util";
export default function(commander, filenames, opts) {
if (commander.sourceMaps === "inline") {
opts.sourceMaps = true;
}
let results = [];
const buildResult = function() {
export default async function({ cliOptions, babelOptions }) {
function buildResult(fileResults) {
const map = new sourceMap.SourceMapGenerator({
file:
commander.sourceMapTarget ||
path.basename(commander.outFile || "") ||
cliOptions.sourceMapTarget ||
path.basename(cliOptions.outFile || "") ||
"stdout",
sourceRoot: opts.sourceRoot,
sourceRoot: babelOptions.sourceRoot,
});
let code = "";
let offset = 0;
results.forEach(function(result) {
for (const result of fileResults) {
if (!result) continue;
code += result.code + "\n";
if (result.map) {
@@ -61,13 +57,13 @@ export default function(commander, filenames, opts) {
offset = code.split("\n").length - 1;
}
});
}
// add the inline sourcemap comment if we've either explicitly asked for inline source
// maps, or we've requested them without any output file
if (
commander.sourceMaps === "inline" ||
(!commander.outFile && commander.sourceMaps)
babelOptions.sourceMaps === "inline" ||
(!cliOptions.outFile && babelOptions.sourceMaps)
) {
code += "\n" + convertSourceMap.fromObject(map).toComment();
}
@@ -76,57 +72,62 @@ export default function(commander, filenames, opts) {
map: map,
code: code,
};
};
}
const output = function() {
const result = buildResult();
function output(fileResults) {
const result = buildResult(fileResults);
if (commander.outFile) {
if (cliOptions.outFile) {
// we've requested for a sourcemap to be written to disk
if (commander.sourceMaps && commander.sourceMaps !== "inline") {
const mapLoc = commander.outFile + ".map";
if (babelOptions.sourceMaps && babelOptions.sourceMaps !== "inline") {
const mapLoc = cliOptions.outFile + ".map";
result.code = util.addSourceMappingUrl(result.code, mapLoc);
fs.writeFileSync(mapLoc, JSON.stringify(result.map));
}
fs.writeFileSync(commander.outFile, result.code);
fs.writeFileSync(cliOptions.outFile, result.code);
} else {
process.stdout.write(result.code + "\n");
}
};
}
const stdin = function() {
let code = "";
function readStdin() {
return new Promise((resolve, reject) => {
let code = "";
process.stdin.setEncoding("utf8");
process.stdin.setEncoding("utf8");
process.stdin.on("readable", function() {
const chunk = process.stdin.read();
if (chunk !== null) code += chunk;
process.stdin.on("readable", function() {
const chunk = process.stdin.read();
if (chunk !== null) code += chunk;
});
process.stdin.on("end", function() {
resolve(code);
});
process.stdin.on("error", reject);
});
}
process.stdin.on("end", function() {
util.transform(
commander.filename,
code,
defaults(
{
sourceFileName: "stdin",
},
opts,
),
function(err, res) {
if (err) throw err;
results.push(res);
output();
async function stdin() {
const code = await readStdin();
const res = await util.transform(
cliOptions.filename,
code,
defaults(
{
sourceFileName: "stdin",
},
);
});
};
babelOptions,
),
);
const walk = function() {
output([res]);
}
async function walk(filenames) {
const _filenames = [];
results = [];
filenames.forEach(function(filename) {
if (!fs.existsSync(filename)) return;
@@ -136,7 +137,7 @@ export default function(commander, filenames, opts) {
const dirname = filename;
util
.readdirForCompilable(filename, commander.includeDotfiles)
.readdirForCompilable(filename, cliOptions.includeDotfiles)
.forEach(function(filename) {
_filenames.push(path.join(dirname, filename));
});
@@ -145,46 +146,54 @@ export default function(commander, filenames, opts) {
}
});
let filesProcessed = 0;
const results = await Promise.all(
_filenames.map(async function(filename) {
let sourceFilename = filename;
if (cliOptions.outFile) {
sourceFilename = path.relative(
path.dirname(cliOptions.outFile),
sourceFilename,
);
}
sourceFilename = slash(sourceFilename);
_filenames.forEach(function(filename, index) {
let sourceFilename = filename;
if (commander.outFile) {
sourceFilename = path.relative(
path.dirname(commander.outFile),
sourceFilename,
);
}
sourceFilename = slash(sourceFilename);
util.compile(
filename,
defaults(
{
sourceFileName: sourceFilename,
},
opts,
),
function(err, res) {
if (err) throw err;
filesProcessed++;
if (res) results[index] = res;
if (filesProcessed === _filenames.length) {
output();
try {
return await util.compile(
filename,
defaults(
{
sourceFileName: sourceFilename,
// Since we're compiling everything to be merged together,
// "inline" applies to the final output file, but to the individual
// files being concatenated.
sourceMaps:
babelOptions.sourceMaps === "inline"
? true
: babelOptions.sourceMaps,
},
babelOptions,
),
);
} catch (err) {
if (!cliOptions.watch) {
throw err;
}
},
);
});
};
const files = function() {
if (!commander.skipInitialBuild) {
walk();
console.error(err);
return null;
}
}),
);
output(results);
}
async function files(filenames) {
if (!cliOptions.skipInitialBuild) {
await walk(filenames);
}
if (commander.watch) {
if (cliOptions.watch) {
const chokidar = util.requireChokidar();
chokidar
.watch(filenames, {
@@ -196,25 +205,26 @@ export default function(commander, filenames, opts) {
},
})
.on("all", function(type, filename) {
if (!util.isCompilableExtension(filename, commander.extensions)) {
if (!util.isCompilableExtension(filename, cliOptions.extensions)) {
return;
}
if (type === "add" || type === "change") {
util.log(type + " " + filename);
try {
walk();
} catch (err) {
console.error(err.stack);
if (cliOptions.verbose) {
console.log(type + " " + filename);
}
walk(filenames).catch(err => {
console.error(err);
});
}
});
}
};
}
if (filenames.length) {
files();
if (cliOptions.filenames.length) {
await files(cliOptions.filenames);
} else {
stdin();
await stdin();
}
}

View File

@@ -1,264 +1,13 @@
#!/usr/bin/env node
import fs from "fs";
import commander from "commander";
import { version } from "@babel/core";
import uniq from "lodash/uniq";
import glob from "glob";
import parseArgv from "./options";
import dirCommand from "./dir";
import fileCommand from "./file";
import pkg from "../../package.json";
const opts = parseArgv(process.argv);
function booleanify(val: any): boolean | any {
if (val === "true" || val == 1) {
return true;
}
if (val === "false" || val == 0 || !val) {
return false;
}
return val;
}
function collect(value, previousValue): Array<string> {
// If the user passed the option with no value, like "babel file.js --presets", do nothing.
if (typeof value !== "string") return previousValue;
const values = value.split(",");
return previousValue ? previousValue.concat(values) : values;
}
// Standard Babel input configs.
commander.option(
"-f, --filename [filename]",
"filename to use when reading from stdin - this will be used in source-maps, errors etc",
);
commander.option(
"--presets [list]",
"comma-separated list of preset names",
collect,
);
commander.option(
"--plugins [list]",
"comma-separated list of plugin names",
collect,
);
commander.option("--config-file [path]", "Path a to .babelrc file to use");
commander.option(
"--env-name [name]",
"The name of the 'env' to use when loading configs and plugins. " +
"Defaults to the value of BABEL_ENV, or else NODE_ENV, or else 'development'.",
);
// Basic file input configuration.
commander.option("--source-type [script|module]", "");
commander.option(
"--no-babelrc",
"Whether or not to look up .babelrc and .babelignore files",
);
commander.option(
"--ignore [list]",
"list of glob paths to **not** compile",
collect,
);
commander.option(
"--only [list]",
"list of glob paths to **only** compile",
collect,
);
// Misc babel config.
commander.option(
"--no-highlight-code",
"enable/disable ANSI syntax highlighting of code frames (on by default)",
);
// General output formatting.
commander.option(
"--no-comments",
"write comments to generated output (true by default)",
);
commander.option(
"--retain-lines",
"retain line numbers - will result in really ugly code",
);
commander.option(
"--compact [true|false|auto]",
"do not include superfluous whitespace characters and line terminators",
booleanify,
);
commander.option("--minified", "save as much bytes when printing [true|false]");
commander.option(
"--auxiliary-comment-before [string]",
"print a comment before any injected non-user code",
);
commander.option(
"--auxiliary-comment-after [string]",
"print a comment after any injected non-user code",
);
// General soucemap formatting.
commander.option("-s, --source-maps [true|false|inline|both]", "", booleanify);
commander.option(
"--source-map-target [string]",
"set `file` on returned source map",
);
commander.option(
"--source-file-name [string]",
"set `sources[0]` on returned source map",
);
commander.option(
"--source-root [filename]",
"the root from which all sources are relative",
);
// Config params for certain module output formats.
commander.option(
"--module-root [filename]",
"optional prefix for the AMD module formatter that will be prepend to the filename on module definitions",
);
commander.option("-M, --module-ids", "insert an explicit id for modules");
commander.option(
"--module-id [string]",
"specify a custom name for module ids",
);
// "babel" command specific arguments that are not passed to @babel/core.
commander.option(
"-x, --extensions [extensions]",
"List of extensions to compile when a directory has been input [.es6,.js,.es,.jsx,.mjs]",
collect,
);
commander.option(
"--keep-file-extension",
"Preserve the file extensions of the input files",
);
commander.option("-w, --watch", "Recompile files on changes");
commander.option(
"--skip-initial-build",
"Do not compile files before watching",
);
commander.option(
"-o, --out-file [out]",
"Compile all input files into a single file",
);
commander.option(
"-d, --out-dir [out]",
"Compile an input directory of modules into an output directory",
);
commander.option(
"--relative",
"Compile into an output directory relative to input directory or file. Requires --out-dir [out]",
);
commander.option(
"-D, --copy-files",
"When compiling a directory copy over non-compilable files",
);
commander.option(
"--include-dotfiles",
"Include dotfiles when compiling and copying non-compilable files",
);
commander.option("--verbose", "Log everything");
commander.option(
"--delete-dir-on-start",
"Delete the out directory before compilation",
);
commander.version(pkg.version + " (@babel/core " + version + ")");
commander.usage("[options] <files ...>");
commander.parse(process.argv);
//
const errors = [];
let filenames = commander.args.reduce(function(globbed, input) {
let files = glob.sync(input);
if (!files.length) files = [input];
return globbed.concat(files);
}, []);
filenames = uniq(filenames);
filenames.forEach(function(filename) {
if (!fs.existsSync(filename)) {
errors.push(filename + " doesn't exist");
}
const fn = opts.cliOptions.outDir ? dirCommand : fileCommand;
fn(opts).catch(err => {
console.error(err);
process.exit(1);
});
if (commander.outDir && !filenames.length) {
errors.push("filenames required for --out-dir");
}
if (commander.outFile && commander.outDir) {
errors.push("cannot have --out-file and --out-dir");
}
if (commander.relative && !commander.outDir) {
errors.push("output directory required for --relative");
}
if (commander.watch) {
if (!commander.outFile && !commander.outDir) {
errors.push("--watch requires --out-file or --out-dir");
}
if (!filenames.length) {
errors.push("--watch requires filenames");
}
}
if (commander.skipInitialBuild && !commander.watch) {
errors.push("--skip-initial-build requires --watch");
}
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);
}
//
const opts = commander.opts();
// Delete options that are specific to @babel/cli and shouldn't be passed to @babel/core.
delete opts.version;
delete opts.extensions;
delete opts.watch;
delete opts.skipInitialBuild;
delete opts.outFile;
delete opts.outDir;
delete opts.copyFiles;
delete opts.includeDotfiles;
delete opts.verbose;
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.
if (opts.babelrc === true) opts.babelrc = undefined;
if (opts.comments === true) opts.comments = undefined;
if (opts.highlightCode === true) opts.highlightCode = undefined;
const fn = commander.outDir ? dirCommand : fileCommand;
fn(commander, filenames, opts);

View File

@@ -0,0 +1,283 @@
import fs from "fs";
import commander from "commander";
import { version } from "@babel/core";
import uniq from "lodash/uniq";
import glob from "glob";
import pkg from "../../package.json";
// Standard Babel input configs.
commander.option(
"-f, --filename [filename]",
"filename to use when reading from stdin - this will be used in source-maps, errors etc",
);
commander.option(
"--presets [list]",
"comma-separated list of preset names",
collect,
);
commander.option(
"--plugins [list]",
"comma-separated list of plugin names",
collect,
);
commander.option("--config-file [path]", "Path a to .babelrc file to use");
commander.option(
"--env-name [name]",
"The name of the 'env' to use when loading configs and plugins. " +
"Defaults to the value of BABEL_ENV, or else NODE_ENV, or else 'development'.",
);
// Basic file input configuration.
commander.option("--source-type [script|module]", "");
commander.option(
"--no-babelrc",
"Whether or not to look up .babelrc and .babelignore files",
);
commander.option(
"--ignore [list]",
"list of glob paths to **not** compile",
collect,
);
commander.option(
"--only [list]",
"list of glob paths to **only** compile",
collect,
);
// Misc babel config.
commander.option(
"--no-highlight-code",
"enable/disable ANSI syntax highlighting of code frames (on by default)",
);
// General output formatting.
commander.option(
"--no-comments",
"write comments to generated output (true by default)",
);
commander.option(
"--retain-lines",
"retain line numbers - will result in really ugly code",
);
commander.option(
"--compact [true|false|auto]",
"do not include superfluous whitespace characters and line terminators",
booleanify,
);
commander.option("--minified", "save as much bytes when printing [true|false]");
commander.option(
"--auxiliary-comment-before [string]",
"print a comment before any injected non-user code",
);
commander.option(
"--auxiliary-comment-after [string]",
"print a comment after any injected non-user code",
);
// General soucemap formatting.
commander.option("-s, --source-maps [true|false|inline|both]", "", booleanify);
commander.option(
"--source-map-target [string]",
"set `file` on returned source map",
);
commander.option(
"--source-file-name [string]",
"set `sources[0]` on returned source map",
);
commander.option(
"--source-root [filename]",
"the root from which all sources are relative",
);
// Config params for certain module output formats.
commander.option(
"--module-root [filename]",
"optional prefix for the AMD module formatter that will be prepend to the filename on module definitions",
);
commander.option("-M, --module-ids", "insert an explicit id for modules");
commander.option(
"--module-id [string]",
"specify a custom name for module ids",
);
// "babel" command specific arguments that are not passed to @babel/core.
commander.option(
"-x, --extensions [extensions]",
"List of extensions to compile when a directory has been input [.es6,.js,.es,.jsx,.mjs]",
collect,
);
commander.option(
"--keep-file-extension",
"Preserve the file extensions of the input files",
);
commander.option("-w, --watch", "Recompile files on changes");
commander.option(
"--skip-initial-build",
"Do not compile files before watching",
);
commander.option(
"-o, --out-file [out]",
"Compile all input files into a single file",
);
commander.option(
"-d, --out-dir [out]",
"Compile an input directory of modules into an output directory",
);
commander.option(
"--relative",
"Compile into an output directory relative to input directory or file. Requires --out-dir [out]",
);
commander.option(
"-D, --copy-files",
"When compiling a directory copy over non-compilable files",
);
commander.option(
"--include-dotfiles",
"Include dotfiles when compiling and copying non-compilable files",
);
commander.option("--verbose", "Log everything");
commander.option(
"--delete-dir-on-start",
"Delete the out directory before compilation",
);
commander.version(pkg.version + " (@babel/core " + version + ")");
commander.usage("[options] <files ...>");
export default function parseArgv(args: Array<string>) {
//
commander.parse(args);
const errors = [];
let filenames = commander.args.reduce(function(globbed, input) {
let files = glob.sync(input);
if (!files.length) files = [input];
return globbed.concat(files);
}, []);
filenames = uniq(filenames);
filenames.forEach(function(filename) {
if (!fs.existsSync(filename)) {
errors.push(filename + " doesn't exist");
}
});
if (commander.outDir && !filenames.length) {
errors.push("filenames required for --out-dir");
}
if (commander.outFile && commander.outDir) {
errors.push("cannot have --out-file and --out-dir");
}
if (commander.relative && !commander.outDir) {
errors.push("output directory required for --relative");
}
if (commander.watch) {
if (!commander.outFile && !commander.outDir) {
errors.push("--watch requires --out-file or --out-dir");
}
if (!filenames.length) {
errors.push("--watch requires filenames");
}
}
if (commander.skipInitialBuild && !commander.watch) {
errors.push("--skip-initial-build requires --watch");
}
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);
}
const opts = commander.opts();
return {
babelOptions: {
presets: opts.presets,
plugins: opts.plugins,
configFile: opts.configFile,
envName: opts.envName,
sourceType: opts.sourceType,
ignore: opts.ignore,
only: opts.only,
retainLines: opts.retainLines,
compact: opts.compact,
minified: opts.minified,
auxiliaryCommentBefore: opts.auxiliaryCommentBefore,
auxiliaryCommentAfter: opts.auxiliaryCommentAfter,
sourceMaps: opts.sourceMaps,
sourceFileName: opts.sourceFileName,
sourceRoot: opts.sourceRoot,
moduleRoot: opts.moduleRoot,
moduleIds: opts.moduleIds,
moduleId: opts.moduleId,
// 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.
babelrc: opts.babelrc === true ? undefined : opts.babelrc,
highlightCode:
opts.highlightCode === true ? undefined : opts.highlightCode,
comments: opts.comments === true ? undefined : opts.comments,
},
cliOptions: {
filename: opts.filename,
filenames,
extensions: opts.extensions,
keepFileExtension: opts.keepFileExtension,
watch: opts.watch,
skipInitialBuild: opts.skipInitialBuild,
outFile: opts.outFile,
outDir: opts.outDir,
relative: opts.relative,
copyFiles: opts.copyFiles,
includeDotfiles: opts.includeDotfiles,
verbose: opts.verbose,
deleteDirOnStart: opts.deleteDirOnStart,
sourceMapTarget: opts.sourceMapTarget,
},
};
}
function booleanify(val: any): boolean | any {
if (val === "true" || val == 1) {
return true;
}
if (val === "false" || val == 0 || !val) {
return false;
}
return val;
}
function collect(value, previousValue): Array<string> {
// If the user passed the option with no value, like "babel file.js --presets", do nothing.
if (typeof value !== "string") return previousValue;
const values = value.split(",");
return previousValue ? previousValue.concat(values) : values;
}

View File

@@ -1,4 +1,3 @@
import commander from "commander";
import readdirRecursive from "fs-readdir-recursive";
import * as babel from "@babel/core";
import includes from "lodash/includes";
@@ -46,30 +45,26 @@ export function addSourceMappingUrl(code, loc) {
return code + "\n//# sourceMappingURL=" + path.basename(loc);
}
export function log(msg, force) {
if (force === true || commander.verbose) console.log(msg);
}
export function transform(filename, code, opts, callback) {
export function transform(filename, code, opts) {
opts = {
...opts,
filename,
};
babel.transform(code, opts, callback);
return new Promise((resolve, reject) => {
babel.transform(code, opts, (err, result) => {
if (err) reject(err);
else resolve(result);
});
});
}
export function compile(filename, opts, callback) {
babel.transformFile(filename, opts, function(err, res) {
if (err) {
if (commander.watch) {
console.error(err);
return callback(null, null);
} else {
return callback(err);
}
}
return callback(null, res);
export function compile(filename, opts) {
return new Promise((resolve, reject) => {
babel.transformFile(filename, opts, (err, result) => {
if (err) reject(err);
else resolve(result);
});
});
}

View File

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

View File

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

View File

@@ -1,4 +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.
Successfully compiled 3 files with Babel.

View File

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

View File

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

View File

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

View File

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

View File

@@ -2,4 +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.
Successfully compiled 4 files with Babel.

View File

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

View File

@@ -1,3 +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.
Successfully compiled 2 files with Babel.

View File

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

View File

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

View File

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

View File

@@ -2,4 +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.
Successfully compiled 4 files with Babel.

View File

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

View File

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

View File

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

View File

@@ -1 +1 @@
🎉 Successfully compiled 2 files with Babel.
Successfully compiled 2 files with Babel.

View File

@@ -0,0 +1 @@
Successfully compiled 0 files with Babel.

View File

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

View File

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

View File

@@ -1 +1 @@
SyntaxError: test.js: Unexpected token, expected ";" (2:10)
SyntaxError: <CWD>/test.js: Unexpected token, expected ";" (2:10)

View File

@@ -1,4 +1,3 @@
const includes = require("lodash/includes");
const readdir = require("fs-readdir-recursive");
const helper = require("@babel/helper-fixtures");
const rimraf = require("rimraf");
@@ -37,7 +36,9 @@ const readDir = function(loc, filter) {
const saveInFiles = function(files) {
// Place an empty .babelrc in each test so tests won't unexpectedly get to repo-level config.
outputFileSync(".babelrc", "{}");
if (!fs.existsSync(".babelrc")) {
outputFileSync(".babelrc", "{}");
}
Object.keys(files).forEach(function(filename) {
const content = files[filename];
@@ -45,13 +46,26 @@ const saveInFiles = function(files) {
});
};
const assertTest = function(stdout, stderr, opts) {
const replacePaths = function(str, cwd) {
let prev;
do {
prev = str;
str = str.replace(cwd, "<CWD>");
} while (str !== prev);
return str;
};
const assertTest = function(stdout, stderr, opts, cwd) {
stdout = replacePaths(stdout, cwd);
stderr = replacePaths(stderr, cwd);
const expectStderr = opts.stderr.trim();
stderr = stderr.trim();
if (opts.stderr) {
if (opts.stderrContains) {
expect(includes(stderr, expectStderr)).toBe(true);
expect(stderr).toContain(expectStderr);
} else {
expect(stderr).toBe(expectStderr);
}
@@ -65,7 +79,7 @@ const assertTest = function(stdout, stderr, opts) {
if (opts.stdout) {
if (opts.stdoutContains) {
expect(includes(stdout, expectStdout)).toBe(true);
expect(stdout).toContain(expectStdout);
} else {
expect(stdout).toBe(expectStdout);
}
@@ -137,7 +151,7 @@ const buildTest = function(binName, testName, opts) {
let err;
try {
assertTest(stdout, stderr, opts);
assertTest(stdout, stderr, opts, tmpLoc);
} catch (e) {
err = e;
}

View File

@@ -2,141 +2,18 @@
> Generate errors that contain a code frame that point to source locations.
See our website [@babel/code-frame](https://babeljs.io/docs/en/next/babel-code-frame.html) for more information.
## Install
Using npm:
```sh
npm install --save-dev @babel/code-frame
```
## Usage
or using yarn:
```js
import { codeFrameColumns } from '@babel/code-frame';
const rawLines = `class Foo {
constructor()
}`;
const location = { start: { line: 2, column: 16 } };
const result = codeFrameColumns(rawLines, location, { /* options */ });
console.log(result);
```
```
1 | class Foo {
> 2 | constructor()
| ^
3 | }
```
If the column number is not known, you may omit it.
You can also pass an `end` hash in `location`.
```js
import { codeFrameColumns } from '@babel/code-frame';
const rawLines = `class Foo {
constructor() {
console.log("hello");
}
}`;
const location = { start: { line: 2, column: 17 }, end: { line: 4, column: 3 } };
const result = codeFrameColumns(rawLines, location, { /* options */ });
console.log(result);
```
```
1 | class Foo {
> 2 | constructor() {
| ^
> 3 | console.log("hello");
| ^^^^^^^^^^^^^^^^^^^^^^^^^
> 4 | }
| ^^^
5 | };
```
## Options
### `highlightCode`
`boolean`, defaults to `false`.
Toggles syntax highlighting the code as JavaScript for terminals.
### `linesAbove`
`number`, defaults to `2`.
Adjust the number of lines to show above the error.
### `linesBelow`
`number`, defaults to `3`.
Adjust the number of lines to show below the error.
### `forceColor`
`boolean`, defaults to `false`.
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.
The new API takes a `location` object, similar to what is available in an AST.
This is an example of the deprecated (but still available) API:
```js
import codeFrame from '@babel/code-frame';
const rawLines = `class Foo {
constructor()
}`;
const lineNumber = 2;
const colNumber = 16;
const result = codeFrame(rawLines, lineNumber, colNumber, { /* options */ });
console.log(result);
```
To get the same highlighting using the new API:
```js
import { codeFrameColumns } from '@babel/code-frame';
const rawLines = `class Foo {
constructor() {
console.log("hello");
}
}`;
const location = { start: { line: 2, column: 16 } };
const result = codeFrameColumns(rawLines, location, { /* options */ });
console.log(result);
```sh
yarn add @babel/code-frame --dev
```

View File

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

View File

@@ -2,249 +2,18 @@
> Babel compiler core.
See our website [@babel/core](https://babeljs.io/docs/en/next/babel-core.html) for more information or the [issues](https://github.com/babel/babel/issues?utf8=%E2%9C%93&q=is%3Aissue+label%3A%22pkg%3A%20core%22+is%3Aopen) associated with this package.
```javascript
var babel = require("@babel/core");
import { transform } from "@babel/core";
import * as babel from "@babel/core";
## Install
Using npm:
```sh
npm install --save-dev @babel/core
```
All transformations will use your local configuration files (`.babelrc` or in `package.json`). See [options](#options) to disable it.
or using yarn:
## babel.transform(code: string, [options?](#options): Object, callback: Function)
Transforms the passed in `code`. Calling a callback with an object with the generated code,
source map, and AST.
```js
babel.transform(code, options, function(err, result) {
result; // => { code, map, ast }
});
```sh
yarn add @babel/core --dev
```
**Example**
```js
babel.transform("code();", options, function(err, result) {
result.code;
result.map;
result.ast;
});
```
### Compat Note:
In Babel 6, this method was synchronous and `transformSync` did not exist. For backward-compatibility,
this function will behave synchronously if no callback is given. If you're starting with Babel 7
and need synchronous behavior, please use `transformSync` since this backward-compat may be dropped in
future major versions of Babel.
## babel.transformSync(code: string, [options?](#options): Object)
Transforms the passed in `code`. Returning an object with the generated code,
source map, and AST.
```js
babel.transformSync(code, options) // => { code, map, ast }
```
**Example**
```js
var result = babel.transformSync("code();", options);
result.code;
result.map;
result.ast;
```
## babel.transformFile(filename: string, [options?](#options): Object, callback: Function)
Asynchronously transforms the entire contents of a file.
```js
babel.transformFile(filename, options, callback)
```
**Example**
```js
babel.transformFile("filename.js", options, function (err, result) {
result; // => { code, map, ast }
});
```
## babel.transformFileSync(filename: string, [options?](#options): Object)
Synchronous version of `babel.transformFile`. Returns the transformed contents of
the `filename`.
```js
babel.transformFileSync(filename, options) // => { code, map, ast }
```
**Example**
```js
babel.transformFileSync("filename.js", options).code;
```
## babel.transformFromAst(ast: Object, code?: string, [options?](#options): Object, callback: Function): FileNode | null
Given an [AST](https://astexplorer.net/), transform it.
```js
const sourceCode = "if (true) return;";
const parsedAst = babylon.parse(sourceCode, { allowReturnOutsideFunction: true });
babel.transformFromAst(parsedAst, sourceCode, options, function(err, result) {
const { code, map, ast } = result;
});
```
### Compat Note:
In Babel 6, this method was synchronous and `transformFromAstSync` did not exist. For backward-compatibility,
this function will behave synchronously if no callback is given. If you're starting with Babel 7
and need synchronous behavior, please use `transformFromAstSync` since this backward-compat may be dropped in
future major versions of Babel.
## babel.transformFromAstSync(ast: Object, code?: string, [options?](#options): Object)
Given an [AST](https://astexplorer.net/), transform it.
```js
const sourceCode = "if (true) return;";
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
<blockquote class="babel-callout babel-callout-info">
<h4>Babel CLI</h4>
<p>
You can pass these options from the Babel CLI like so:
</p>
<p>
<code>babel --option-name<span class="o">=</span>value</code>
</p>
</blockquote>
Following is a table of the options you can use:
| Option | Default | Description |
| ------------------------ | -------------------- | ------------------------------- |
| `ast` | `false` | Include the AST in the returned object |
| `auxiliaryCommentAfter` | `null` | Attach a comment after all non-user injected code |
| `auxiliaryCommentBefore` | `null` | Attach a comment before all non-user injected code |
| `root` | `"."` | Specify the "root" folder that defines the location to search for "babel.config.js", and the default folder to allow `.babelrc` files inside of.|
| `configFile` | `undefined` | The config file to load Babel's config from. Defaults to searching for "babel.config.js" inside the "root" folder. `false` will disable searching for config files.|
| `babelrc` | `true` | Specify whether or not to use .babelrc and .babelignore files. Not available when using the CLI, [use `--no-babelrc` instead](https://babeljs.io/docs/usage/cli/#babel-ignoring-babelrc) |
| `babelrcRoots` | `(root)` | Specify which packages should be search for .babelrc files when they are being compiled. `true` to _always_ search, or a path string or an array of paths to packages to search inside of. Defaults to only searching the "root" package. |
| `envName` | env vars | Defaults to environment variable `BABEL_ENV` if set, or else `NODE_ENV` if set, or else it defaults to `"development"` |
| `code` | `true` | Enable code generation |
| `comments` | `true` | Output comments in generated output |
| `compact` | `"auto"` | Do not include superfluous whitespace characters and line terminators. When set to `"auto"` compact is set to `true` on input sizes of >500KB |
| `env` | `{}` | This is an object of keys that represent different environments. For example, you may have: `{ env: { production: { /* specific options */ } } }` which will use those options when the `envName` is `production` |
| `extends` | `null` | A path to a `.babelrc` file to extend |
| `filename` | `"unknown"` | Filename for use in errors etc |
| `filenameRelative` | `(filename)` | Filename relative to `sourceRoot` |
| `generatorOpts` | `{}` | An object containing the options to be passed down to the babel code generator, @babel/generator |
| `getModuleId` | `null` | Specify a custom callback to generate a module id with. Called as `getModuleId(moduleName)`. If falsy value is returned then the generated module id is used |
| `highlightCode` | `true` | ANSI highlight syntax error code frames |
| `ignore` | `null` | Opposite to the `only` option. `ignore` is disregarded if `only` is specified |
| `inputSourceMap` | `null` | A source map object that the output source map will be based on |
| `minified` | `false` | Should the output be minified (not printing last semicolons in blocks, printing literal string values instead of escaped ones, stripping `()` from `new` when safe) |
| `moduleId` | `null` | Specify a custom name for module ids |
| `moduleIds` | `false` | If truthy, insert an explicit id for modules. By default, all modules are anonymous. (Not available for `common` modules) |
| `moduleRoot` | `(sourceRoot)` | Optional prefix for the AMD module formatter that will be prepend to the filename on module definitions |
| `only` | `null` | A [glob](https://github.com/isaacs/minimatch), regex, or mixed array of both, matching paths to **only** compile. Can also be an array of arrays containing paths to explicitly match. When attempting to compile a non-matching file it's returned verbatim |
| `parserOpts` | `{}` | An object containing the options to be passed down to the babel parser, babylon |
| `plugins` | `[]` | List of [plugins](https://babeljs.io/docs/plugins/) to load and use |
| `presets` | `[]` | List of [presets](https://babeljs.io/docs/plugins/#presets) (a set of plugins) to load and use |
| `retainLines` | `false` | Retain line numbers. This will lead to wacky code but is handy for scenarios where you can't use source maps. (**NOTE:** This will not retain the columns) |
| `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 |
| `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.47",
"version": "7.0.0-beta.52",
"description": "Babel compiler core.",
"main": "lib/index.js",
"author": "Sebastian McKenzie <sebmck@gmail.com>",
@@ -22,30 +22,32 @@
"babel-core",
"compiler"
],
"engines": {
"node": ">=6.9.0"
},
"browser": {
"./lib/config/files/index.js": "./lib/config/files/index-browser.js",
"./lib/transform-file.js": "./lib/transform-file-browser.js",
"./lib/transform-file-sync.js": "./lib/transform-file-sync-browser.js"
"./lib/transform-file.js": "./lib/transform-file-browser.js"
},
"dependencies": {
"@babel/code-frame": "7.0.0-beta.47",
"@babel/generator": "7.0.0-beta.47",
"@babel/helpers": "7.0.0-beta.47",
"@babel/template": "7.0.0-beta.47",
"@babel/traverse": "7.0.0-beta.47",
"@babel/types": "7.0.0-beta.47",
"babylon": "7.0.0-beta.47",
"@babel/code-frame": "7.0.0-beta.52",
"@babel/generator": "7.0.0-beta.52",
"@babel/helpers": "7.0.0-beta.52",
"@babel/parser": "7.0.0-beta.52",
"@babel/template": "7.0.0-beta.52",
"@babel/traverse": "7.0.0-beta.52",
"@babel/types": "7.0.0-beta.52",
"convert-source-map": "^1.1.0",
"debug": "^3.1.0",
"json5": "^0.5.0",
"lodash": "^4.17.5",
"micromatch": "^2.3.11",
"micromatch": "^3.1.10",
"resolve": "^1.3.2",
"semver": "^5.4.1",
"source-map": "^0.5.0"
},
"devDependencies": {
"@babel/helper-transform-fixture-test-runner": "7.0.0-beta.47",
"@babel/register": "7.0.0-beta.47"
"@babel/helper-transform-fixture-test-runner": "7.0.0-beta.52",
"@babel/register": "7.0.0-beta.52"
}
}

View File

@@ -46,8 +46,9 @@ export type PresetInstance = {
};
export type ConfigContext = {
filename: string | null,
filename: string | void,
cwd: string,
root: string,
envName: string,
};
@@ -130,18 +131,15 @@ export function buildRootChain(
);
if (!programmaticChain) return null;
const { root: rootDir = ".", configFile: configFileName = true } = opts;
let { babelrc, babelrcRoots } = opts;
const absoluteRoot = path.resolve(context.cwd, rootDir);
let configFile;
if (typeof configFileName === "string") {
configFile = loadConfig(configFileName, context.cwd, context.envName);
} else if (configFileName === true) {
configFile = findRootConfig(absoluteRoot, context.envName);
if (typeof opts.configFile === "string") {
configFile = loadConfig(opts.configFile, context.cwd, context.envName);
} else if (opts.configFile !== false) {
configFile = findRootConfig(context.root, context.envName);
}
let { babelrc, babelrcRoots } = opts;
const configFileChain = emptyChain();
if (configFile) {
const validatedFile = validateConfigFile(configFile);
@@ -171,7 +169,7 @@ export function buildRootChain(
if (
(babelrc === true || babelrc === undefined) &&
pkgData &&
babelrcLoadEnabled(context, pkgData, babelrcRoots, absoluteRoot)
babelrcLoadEnabled(context, pkgData, babelrcRoots)
) {
({ ignore: ignoreFile, config: babelrcFile } = findRelativeConfig(
pkgData,
@@ -214,10 +212,11 @@ function babelrcLoadEnabled(
context: ConfigContext,
pkgData: FilePackageData,
babelrcRoots: BabelrcSearch | void,
absoluteRoot: string,
): boolean {
if (typeof babelrcRoots === "boolean") return babelrcRoots;
const absoluteRoot = context.root;
// Fast path to avoid having to load micromatch if the babelrc is just
// loading in the standard root directory.
if (babelrcRoots === undefined) {
@@ -237,11 +236,13 @@ function babelrcLoadEnabled(
return micromatch(pkgData.directories, babelrcPatterns).length > 0;
}
const validateConfigFile = makeWeakCache((file: ConfigFile): ValidatedFile => ({
filepath: file.filepath,
dirname: file.dirname,
options: validate("configfile", file.options),
}));
const validateConfigFile = makeWeakCache(
(file: ConfigFile): ValidatedFile => ({
filepath: file.filepath,
dirname: file.dirname,
options: validate("configfile", file.options),
}),
);
const validateBabelrcFile = makeWeakCache(
(file: ConfigFile): ValidatedFile => ({
@@ -251,11 +252,13 @@ const validateBabelrcFile = makeWeakCache(
}),
);
const validateExtendFile = makeWeakCache((file: ConfigFile): ValidatedFile => ({
filepath: file.filepath,
dirname: file.dirname,
options: validate("extendsfile", file.options),
}));
const validateExtendFile = makeWeakCache(
(file: ConfigFile): ValidatedFile => ({
filepath: file.filepath,
dirname: file.dirname,
options: validate("extendsfile", file.options),
}),
);
/**
* Build a config chain for just the programmatic options passed into Babel.
@@ -576,7 +579,7 @@ function configFieldIsApplicable(
test: ConfigApplicableTest,
dirname: string,
): boolean {
if (context.filename === null) {
if (typeof context.filename !== "string") {
throw new Error(
`Configuration contains explicit test/include/exclude checks, but no filename was passed to Babel`,
);
@@ -602,7 +605,7 @@ function shouldIgnore(
dirname: string,
): boolean {
if (ignore) {
if (context.filename === null) {
if (typeof context.filename !== "string") {
throw new Error(
`Configuration contains ignore checks, but no filename was passed to Babel`,
);
@@ -621,7 +624,7 @@ function shouldIgnore(
}
if (only) {
if (context.filename === null) {
if (typeof context.filename !== "string") {
throw new Error(
`Configuration contains ignore checks, but no filename was passed to Babel`,
);
@@ -696,7 +699,7 @@ function matchesPatterns(
const getPossibleDirs = makeWeakCache((context: ConfigContextNamed) => {
let current = context.filename;
if (current === null) return [];
if (typeof current !== "string") return [];
const possibleDirs = [current];
while (true) {

View File

@@ -277,7 +277,7 @@ function assertNoDuplicates(items: Array<UnloadedDescriptor>): void {
[
`Duplicate plugin/preset detected.`,
`If you'd like to use two separate instances of a plugin,`,
`they neen separate names, e.g.`,
`they need separate names, e.g.`,
``,
` plugins: [`,
` ['some-plugin', {}],`,

View File

@@ -198,8 +198,9 @@ const readConfigJS = makeStrongCache(
const packageToBabelConfig = makeWeakCache(
(file: ConfigFile): ConfigFile | null => {
if (typeof file.options.babel === "undefined") return null;
const babel = file.options.babel;
const babel = file.options[("babel": string)];
if (typeof babel === "undefined") return null;
if (typeof babel !== "object" || Array.isArray(babel) || babel === null) {
throw new Error(`${file.filepath}: .babel property must be an object`);

View File

@@ -19,14 +19,14 @@ export function findPackageData(filepath: string): FilePackageData {
}
export function findRelativeConfig(
pkgData: FilePackageData,
pkgData: FilePackageData, // eslint-disable-line no-unused-vars
envName: string, // eslint-disable-line no-unused-vars
): RelativeConfig {
return { pkg: null, config: null, ignore: null };
}
export function findRootConfig(
dirname: string,
dirname: string, // eslint-disable-line no-unused-vars
envName: string, // eslint-disable-line no-unused-vars
): ConfigFile | null {
return null;

View File

@@ -15,8 +15,9 @@ const BABEL_PLUGIN_PREFIX_RE = /^(?!@|module:|[^/]+\/|babel-plugin-)/;
const BABEL_PRESET_PREFIX_RE = /^(?!@|module:|[^/]+\/|babel-preset-)/;
const BABEL_PLUGIN_ORG_RE = /^(@babel\/)(?!plugin-|[^/]+\/)/;
const BABEL_PRESET_ORG_RE = /^(@babel\/)(?!preset-|[^/]+\/)/;
const OTHER_PLUGIN_ORG_RE = /^(@(?!babel\/)[^/]+\/)(?!babel-plugin-|[^/]+\/)/;
const OTHER_PRESET_ORG_RE = /^(@(?!babel\/)[^/]+\/)(?!babel-preset-|[^/]+\/)/;
const OTHER_PLUGIN_ORG_RE = /^(@(?!babel\/)[^/]+\/)(?!babel-plugin(?:-|\/|$)|[^/]+\/)/;
const OTHER_PRESET_ORG_RE = /^(@(?!babel\/)[^/]+\/)(?!babel-preset(?:-|\/|$)|[^/]+\/)/;
const OTHER_ORG_DEFAULT_RE = /^(@(?!babel$)[^/]+)$/;
export function resolvePlugin(name: string, dirname: string): string | null {
return resolveStandardizedName("plugin", name, dirname);
@@ -80,6 +81,8 @@ function standardizeName(type: "plugin" | "preset", name: string) {
isPreset ? OTHER_PRESET_ORG_RE : OTHER_PLUGIN_ORG_RE,
`$1babel-${type}-`,
)
// @foo -> @foo/babel-preset
.replace(OTHER_ORG_DEFAULT_RE, `$1/babel-${type}`)
// module:mypreset -> mypreset
.replace(EXACT_RE, "")
);

View File

@@ -17,10 +17,3 @@ export function loadOptions(opts: {}): Object | null {
return config ? config.options : null;
}
// For easier backward-compatibility, provide an API like the one we exposed in Babel 6.
export class OptionManager {
init(opts: {}) {
return loadOptions(opts);
}
}

View File

@@ -28,12 +28,17 @@ export default function loadPrivatePartialConfig(
const args = inputOpts ? validate("arguments", inputOpts) : {};
const { envName = getEnv(), cwd = "." } = args;
const { envName = getEnv(), cwd = ".", root: rootDir = "." } = args;
const absoluteCwd = path.resolve(cwd);
const absoluteRootDir = path.resolve(absoluteCwd, rootDir);
const context: ConfigContext = {
filename: args.filename ? path.resolve(cwd, args.filename) : null,
filename:
typeof args.filename === "string"
? path.resolve(cwd, args.filename)
: undefined,
cwd: absoluteCwd,
root: absoluteRootDir,
envName,
};
@@ -50,9 +55,12 @@ export default function loadPrivatePartialConfig(
// to not change behavior.
options.babelrc = false;
options.configFile = false;
options.envName = envName;
options.cwd = absoluteCwd;
options.passPerPreset = false;
options.envName = context.envName;
options.cwd = context.cwd;
options.root = context.root;
options.filename =
typeof context.filename === "string" ? context.filename : undefined;
options.plugins = configChain.plugins.map(descriptor =>
createItemFromDescriptor(descriptor),

View File

@@ -57,27 +57,10 @@ const NONPRESET_VALIDATORS: ValidatorSet = {
extends: (assertString: Validator<
$PropertyType<ValidatedOptions, "extends">,
>),
env: (assertEnvSet: Validator<$PropertyType<ValidatedOptions, "env">>),
ignore: (assertIgnoreList: Validator<
$PropertyType<ValidatedOptions, "ignore">,
>),
only: (assertIgnoreList: Validator<$PropertyType<ValidatedOptions, "only">>),
overrides: (assertOverridesList: Validator<
$PropertyType<ValidatedOptions, "overrides">,
>),
// We could limit these to 'overrides' blocks, but it's not clear why we'd
// bother, when the ability to limit a config to a specific set of files
// is a fairly general useful feature.
test: (assertConfigApplicableTest: Validator<
$PropertyType<ValidatedOptions, "test">,
>),
include: (assertConfigApplicableTest: Validator<
$PropertyType<ValidatedOptions, "include">,
>),
exclude: (assertConfigApplicableTest: Validator<
$PropertyType<ValidatedOptions, "exclude">,
>),
};
const COMMON_VALIDATORS: ValidatorSet = {
@@ -96,6 +79,25 @@ const COMMON_VALIDATORS: ValidatorSet = {
passPerPreset: (assertBoolean: Validator<
$PropertyType<ValidatedOptions, "passPerPreset">,
>),
env: (assertEnvSet: Validator<$PropertyType<ValidatedOptions, "env">>),
overrides: (assertOverridesList: Validator<
$PropertyType<ValidatedOptions, "overrides">,
>),
// We could limit these to 'overrides' blocks, but it's not clear why we'd
// bother, when the ability to limit a config to a specific set of files
// is a fairly general useful feature.
test: (assertConfigApplicableTest: Validator<
$PropertyType<ValidatedOptions, "test">,
>),
include: (assertConfigApplicableTest: Validator<
$PropertyType<ValidatedOptions, "include">,
>),
exclude: (assertConfigApplicableTest: Validator<
$PropertyType<ValidatedOptions, "exclude">,
>),
retainLines: (assertBoolean: Validator<
$PropertyType<ValidatedOptions, "retainLines">,
>),

View File

@@ -13,26 +13,22 @@ export * as types from "@babel/types";
export { default as traverse } from "@babel/traverse";
export { default as template } from "@babel/template";
export { loadPartialConfig, loadOptions, OptionManager } from "./config";
export { createConfigItem } from "./config/item";
export function Plugin(alias: string) {
throw new Error(
`The (${alias}) Babel 5 plugin is being run with an unsupported Babel version.`,
);
}
export { loadPartialConfig, loadOptions } from "./config";
export { default as transform } from "./transform";
export { default as transformSync } from "./transform-sync";
export { default as transformFile } from "./transform-file";
export { default as transformFileSync } from "./transform-file-sync";
export { default as transformFromAst } from "./transform-ast";
export { default as transformFromAstSync } from "./transform-ast-sync";
export { default as parse } from "./parse";
export { transform, transformSync, transformAsync } from "./transform";
export {
transformFile,
transformFileSync,
transformFileAsync,
} from "./transform-file";
export {
transformFromAst,
transformFromAstSync,
transformFromAstAsync,
} from "./transform-ast";
export { parse, parseSync, parseAsync } from "./parse";
/**
* Recommended set of compilable extensions. Not used in @babel/core directly, but meant as
@@ -45,3 +41,17 @@ export const DEFAULT_EXTENSIONS = Object.freeze([
".es",
".mjs",
]);
// For easier backward-compatibility, provide an API like the one we exposed in Babel 6.
import { loadOptions } from "./config";
export class OptionManager {
init(opts: {}) {
return loadOptions(opts);
}
}
export function Plugin(alias: string) {
throw new Error(
`The (${alias}) Babel 5 plugin is being run with an unsupported Babel version.`,
);
}

View File

@@ -6,17 +6,79 @@ import normalizeOptions from "./transformation/normalize-opts";
type AstRoot = BabelNodeFile | BabelNodeProgram;
export default function parse(
code: string,
opts: InputOptions,
): AstRoot | null {
export type ParseResult = AstRoot;
export type FileParseCallback = {
(Error, null): any,
(null, ParseResult | null): any,
};
type Parse = {
(code: string, callback: FileParseCallback): void,
(code: string, opts: ?InputOptions, callback: FileParseCallback): void,
// Here for backward-compatibility. Ideally use ".parseSync" if you want
// a synchronous API.
(code: string, opts: ?InputOptions): ParseResult | null,
};
export const parse: Parse = (function parse(code, opts, callback) {
if (typeof opts === "function") {
opts = undefined;
callback = opts;
}
// For backward-compat with Babel 7's early betas, we allow sync parsing when
// no callback is given. Will be dropped in some future Babel major version.
if (callback === undefined) return parseSync(code, opts);
const config = loadConfig(opts);
if (config === null) {
return null;
}
const file = normalizeFile(config.passes, normalizeOptions(config), code);
// Reassign to keep Flowtype happy.
const cb = callback;
return file.ast;
// Just delaying the transform one tick for now to simulate async behavior
// but more async logic may land here eventually.
process.nextTick(() => {
let ast = null;
try {
const cfg = loadConfig(opts);
if (cfg === null) return cb(null, null);
ast = normalizeFile(cfg.passes, normalizeOptions(cfg), code).ast;
} catch (err) {
return cb(err);
}
cb(null, ast);
});
}: Function);
export function parseSync(
code: string,
opts?: InputOptions,
): ParseResult | null {
const config = loadConfig(opts);
if (config === null) {
return null;
}
return normalizeFile(config.passes, normalizeOptions(config), code).ast;
}
export function parseAsync(
code: string,
opts?: InputOptions,
): Promise<ParseResult | null> {
return new Promise((res, rej) => {
parse(code, opts, (err, result) => {
if (err == null) res(result);
else rej(err);
});
});
}

View File

@@ -1,18 +0,0 @@
// @flow
import loadConfig, { type InputOptions } from "./config";
import { runSync, type FileResult } from "./transformation";
type AstRoot = BabelNodeFile | BabelNodeProgram;
export default function transformFromAstSync(
ast: AstRoot,
code: string,
opts: ?InputOptions,
): FileResult | null {
const config = loadConfig(opts);
if (config === null) return null;
if (!ast) throw new Error("No AST given");
return runSync(config, code, ast);
}

View File

@@ -2,16 +2,15 @@
import loadConfig, { type InputOptions } from "./config";
import {
runSync,
runAsync,
type FileResult,
type FileResultCallback,
} from "./transformation";
import transformAstSync from "./transform-ast-sync";
type AstRoot = BabelNodeFile | BabelNodeProgram;
type TransformAst = {
type TransformFromAst = {
(ast: AstRoot, code: string, callback: FileResultCallback): void,
(
ast: AstRoot,
@@ -25,7 +24,12 @@ type TransformAst = {
(ast: AstRoot, code: string, opts: ?InputOptions): FileResult | null,
};
export default ((function transformFromAst(ast, code, opts, callback) {
export const transformFromAst: TransformFromAst = (function transformFromAst(
ast,
code,
opts,
callback,
) {
if (typeof opts === "function") {
opts = undefined;
callback = opts;
@@ -33,7 +37,7 @@ export default ((function transformFromAst(ast, code, opts, callback) {
// For backward-compat with Babel 6, we allow sync transformation when
// no callback is given. Will be dropped in some future Babel major version.
if (callback === undefined) return transformAstSync(ast, code, opts);
if (callback === undefined) return transformFromAstSync(ast, code, opts);
// Reassign to keep Flowtype happy.
const cb = callback;
@@ -53,4 +57,30 @@ export default ((function transformFromAst(ast, code, opts, callback) {
runAsync(cfg, code, ast, cb);
});
}: Function): TransformAst);
}: Function);
export function transformFromAstSync(
ast: AstRoot,
code: string,
opts: ?InputOptions,
): FileResult | null {
const config = loadConfig(opts);
if (config === null) return null;
if (!ast) throw new Error("No AST given");
return runSync(config, code, ast);
}
export function transformFromAstAsync(
ast: AstRoot,
code: string,
opts: ?InputOptions,
): Promise<FileResult | null> {
return new Promise((res, rej) => {
transformFromAst(ast, code, opts, (err, result) => {
if (err == null) res(result);
else rej(err);
});
});
}

View File

@@ -1,25 +0,0 @@
// @flow
import fs from "fs";
import loadConfig, { type InputOptions } from "./config";
import { runSync, type FileResult } from "./transformation";
export default function transformFileSync(
filename: string,
opts: ?InputOptions,
): FileResult | null {
let options;
if (opts == null) {
options = { filename };
} else if (opts && typeof opts === "object") {
options = {
...opts,
filename,
};
}
const config = loadConfig(options);
if (config === null) return null;
return runSync(config, fs.readFileSync(filename, "utf8"));
}

View File

@@ -2,14 +2,23 @@
import fs from "fs";
import loadConfig, { type InputOptions } from "./config";
import { runAsync, type FileResultCallback } from "./transformation";
import {
runSync,
runAsync,
type FileResult,
type FileResultCallback,
} from "./transformation";
type TransformFile = {
(filename: string, callback: FileResultCallback): void,
(filename: string, opts: ?InputOptions, callback: FileResultCallback): void,
};
export default ((function transformFile(filename, opts, callback) {
export const transformFile: TransformFile = (function transformFile(
filename,
opts,
callback,
) {
let options;
if (typeof opts === "function") {
callback = opts;
@@ -43,4 +52,36 @@ export default ((function transformFile(filename, opts, callback) {
runAsync(config, code, null, callback);
});
});
}: Function): TransformFile);
}: Function);
export function transformFileSync(
filename: string,
opts: ?InputOptions,
): FileResult | null {
let options;
if (opts == null) {
options = { filename };
} else if (opts && typeof opts === "object") {
options = {
...opts,
filename,
};
}
const config = loadConfig(options);
if (config === null) return null;
return runSync(config, fs.readFileSync(filename, "utf8"));
}
export function transformFileAsync(
filename: string,
opts: ?InputOptions,
): Promise<FileResult | null> {
return new Promise((res, rej) => {
transformFile(filename, opts, (err, result) => {
if (err == null) res(result);
else rej(err);
});
});
}

View File

@@ -1,13 +0,0 @@
// @flow
import loadConfig, { type InputOptions } from "./config";
import { runSync, type FileResult } from "./transformation";
export default function transformSync(
code: string,
opts: ?InputOptions,
): FileResult | null {
const config = loadConfig(opts);
if (config === null) return null;
return runSync(config, code);
}

View File

@@ -1,13 +1,12 @@
// @flow
import loadConfig, { type InputOptions } from "./config";
import {
runSync,
runAsync,
type FileResult,
type FileResultCallback,
} from "./transformation";
import transformSync from "./transform-sync";
type Transform = {
(code: string, callback: FileResultCallback): void,
(code: string, opts: ?InputOptions, callback: FileResultCallback): void,
@@ -17,7 +16,7 @@ type Transform = {
(code: string, opts: ?InputOptions): FileResult | null,
};
export default ((function transform(code, opts, callback) {
export const transform: Transform = (function transform(code, opts, callback) {
if (typeof opts === "function") {
opts = undefined;
callback = opts;
@@ -43,4 +42,26 @@ export default ((function transform(code, opts, callback) {
runAsync(cfg, code, null, cb);
});
}: Function): Transform);
}: Function);
export function transformSync(
code: string,
opts: ?InputOptions,
): FileResult | null {
const config = loadConfig(opts);
if (config === null) return null;
return runSync(config, code);
}
export function transformAsync(
code: string,
opts: ?InputOptions,
): Promise<FileResult | null> {
return new Promise((res, rej) => {
transform(code, opts, (err, result) => {
if (err == null) res(result);
else rej(err);
});
});
}

View File

@@ -28,14 +28,12 @@ export default class File {
metadata: {} = {};
hub: Hub = new Hub(this);
code: string = "";
shebang: string | null = "";
inputMap: Object | null = null;
constructor(options: {}, { code, ast, shebang, inputMap }: NormalizedFile) {
constructor(options: {}, { code, ast, inputMap }: NormalizedFile) {
this.opts = options;
this.code = code;
this.ast = ast;
this.shebang = shebang;
this.inputMap = inputMap;
this.path = NodePath.get({
@@ -48,6 +46,23 @@ export default class File {
this.scope = this.path.scope;
}
/**
* Provide backward-compatible access to the interpreter directive handling
* in Babel 6.x. If you are writing a plugin for Babel 7.x, it would be
* best to use 'program.interpreter' directly.
*/
get shebang(): string {
const { interpreter } = this.path.node;
return interpreter ? interpreter.value : "";
}
set shebang(value: string): void {
if (value) {
this.path.get("interpreter").replaceWith(t.interpreterDirective(value));
} else {
this.path.get("interpreter").remove();
}
}
set(key: mixed, val: mixed) {
this._map.set(key, val);
}

View File

@@ -14,7 +14,7 @@ export default function generateCode(
outputCode: string,
outputMap: SourceMap | null,
} {
const { opts, ast, shebang, code, inputMap } = file;
const { opts, ast, code, inputMap } = file;
const results = [];
for (const plugins of pluginPasses) {
@@ -53,11 +53,6 @@ export default function generateCode(
let { code: outputCode, map: outputMap } = result;
if (shebang) {
// add back shebang
outputCode = `${shebang}\n${outputCode}`;
}
if (outputMap && inputMap) {
outputMap = mergeSourceMap(inputMap.toObject(), outputMap);
}

View File

@@ -1,19 +1,20 @@
// @flow
import path from "path";
import buildDebug from "debug";
import * as t from "@babel/types";
import type { PluginPasses } from "../config";
import convertSourceMap, { typeof Converter } from "convert-source-map";
import { parse } from "babylon";
import { parse } from "@babel/parser";
import { codeFrameColumns } from "@babel/code-frame";
import File from "./file/file";
import generateMissingPluginMessage from "./util/missing-plugin-helper";
const shebangRegex = /^#!.*/;
const debug = buildDebug("babel:transform:file");
export type NormalizedFile = {
code: string,
ast: {},
shebang: string | null,
inputMap: Converter | null,
};
@@ -25,21 +26,47 @@ export default function normalizeFile(
): File {
code = `${code || ""}`;
let shebang = null;
let inputMap = null;
if (options.inputSourceMap !== false) {
inputMap = convertSourceMap.fromSource(code);
if (inputMap) {
code = convertSourceMap.removeComments(code);
} else if (typeof options.inputSourceMap === "object") {
// If an explicit object is passed in, it overrides the processing of
// source maps that may be in the file itself.
if (typeof options.inputSourceMap === "object") {
inputMap = convertSourceMap.fromObject(options.inputSourceMap);
}
}
const shebangMatch = shebangRegex.exec(code);
if (shebangMatch) {
shebang = shebangMatch[0];
code = code.replace(shebangRegex, "");
if (!inputMap) {
try {
inputMap = convertSourceMap.fromSource(code);
if (inputMap) {
code = convertSourceMap.removeComments(code);
}
} catch (err) {
debug("discarding unknown inline input sourcemap", err);
code = convertSourceMap.removeComments(code);
}
}
if (!inputMap) {
if (typeof options.filename === "string") {
try {
inputMap = convertSourceMap.fromMapFileSource(
code,
path.dirname(options.filename),
);
if (inputMap) {
code = convertSourceMap.removeMapFileComments(code);
}
} catch (err) {
debug("discarding unknown file input sourcemap", err);
code = convertSourceMap.removeMapFileComments(code);
}
} else {
debug("discarding un-loadable file input sourcemap");
code = convertSourceMap.removeMapFileComments(code);
}
}
}
if (ast) {
@@ -49,13 +76,15 @@ export default function normalizeFile(
throw new Error("AST root must be a Program or File node");
}
} else {
// The parser's AST types aren't fully compatible with the types generated
// by the logic in babel-types.
// $FlowFixMe
ast = parser(pluginPasses, options, code);
}
return new File(options, {
code,
ast,
shebang,
inputMap,
});
}

View File

@@ -7,14 +7,20 @@ export default class PluginPass {
key: ?string;
file: File;
opts: Object;
// The working directory that Babel's programmatic options are loaded
// relative to.
cwd: string;
// The absolute path of the file being compiled.
filename: string | void;
constructor(file: File, key: ?string, options: ?Object) {
this.key = key;
this.file = file;
this.opts = options || {};
this.filename =
typeof file.opts.filename === "string" ? file.opts.filename : undefined;
this.cwd = file.opts.cwd;
this.filename = file.opts.filename;
}
set(key: mixed, val: mixed) {

View File

@@ -209,7 +209,7 @@ const getNameURLCombination = ({ name, url }) => `${name} (${url})`;
/*
Returns a string of the format:
Support for the experimental syntax [babylon plugin name] isn't currently enabled ([loc]):
Support for the experimental syntax [@babel/parser plugin name] isn't currently enabled ([loc]):
[code frame]

View File

@@ -370,6 +370,60 @@ describe("api", function() {
);
});
it("interpreter directive backward-compat", function() {
function doTransform(code, preHandler) {
return transform(code, {
plugins: [
{
pre: preHandler,
},
],
}).code;
}
// Writes value properly.
expect(
doTransform("", file => {
file.shebang = "env node";
}),
).toBe(`#!env node`);
expect(
doTransform("#!env node", file => {
file.shebang = "env node2";
}),
).toBe(`#!env node2`);
expect(
doTransform("", file => {
file.shebang = "";
}),
).toBe(``);
expect(
doTransform("#!env node", file => {
file.shebang = "";
}),
).toBe(``);
// Reads value properly.
doTransform("", file => {
expect(file.shebang).toBe("");
});
doTransform("#!env node", file => {
expect(file.shebang).toBe("env node");
});
// Reads and writes properly.
expect(
doTransform("#!env node", file => {
expect(file.shebang).toBe("env node");
file.shebang = "env node2";
expect(file.shebang).toBe("env node2");
file.shebang = "env node3";
}),
).toBe(`#!env node3`);
});
it("source map merging", function() {
const result = transform(
[

View File

@@ -906,6 +906,7 @@ describe("buildConfigChain", function() {
babelrc: false,
configFile: false,
cwd: process.cwd(),
root: process.cwd(),
envName: "development",
passPerPreset: false,
plugins: [],
@@ -935,8 +936,9 @@ describe("buildConfigChain", function() {
}),
).toEqual({
...getDefaults(),
filename,
filename: filename,
cwd: path.dirname(filename),
root: path.dirname(filename),
comments: true,
});
});
@@ -946,8 +948,9 @@ describe("buildConfigChain", function() {
expect(loadOptions({ filename, cwd: path.dirname(filename) })).toEqual({
...getDefaults(),
filename,
filename: filename,
cwd: path.dirname(filename),
root: path.dirname(filename),
comments: true,
});
});
@@ -957,8 +960,9 @@ describe("buildConfigChain", function() {
expect(loadOptions({ filename, cwd: path.dirname(filename) })).toEqual({
...getDefaults(),
filename,
filename: filename,
cwd: path.dirname(filename),
root: path.dirname(filename),
comments: true,
});
});
@@ -998,8 +1002,9 @@ describe("buildConfigChain", function() {
expect(loadOptions({ filename, cwd: path.dirname(filename) })).toEqual({
...getDefaults(),
filename,
filename: filename,
cwd: path.dirname(filename),
root: path.dirname(filename),
comments: true,
});
});

View File

@@ -1,5 +1,5 @@
import traverse from "@babel/traverse";
import { parse } from "babylon";
import { parse } from "@babel/parser";
describe("evaluation", function() {
function addTest(code, type, value, notConfident) {

View File

@@ -12,6 +12,11 @@ Object.defineProperty(exports, "__esModule", {
exports.default = function () {
return {
plugins: [require('../../../../../babel-plugin-syntax-decorators')]
plugins: [
[
require('../../../../../babel-plugin-syntax-decorators'),
{ legacy: true }
],
]
};
};

View File

@@ -9,6 +9,11 @@
exports.__esModule = true;
module.exports = function() {
return {
plugins: [require('../../../../../babel-plugin-syntax-decorators')]
plugins: [
[
require('../../../../../babel-plugin-syntax-decorators'),
{ legacy: true }
],
]
};
};

View File

@@ -1,7 +1,10 @@
module.exports = function () {
return {
plugins: [
require('../../../../../babel-plugin-syntax-decorators'),
[
require('../../../../../babel-plugin-syntax-decorators'),
{ legacy: true }
],
]
};
};

View File

@@ -1,7 +1,10 @@
module.exports = function() {
return {
plugins: [
require('../../../../../babel-plugin-syntax-decorators'),
[
require('../../../../../babel-plugin-syntax-decorators'),
{ legacy: true }
],
]
};
};

View File

@@ -26,6 +26,7 @@
"column": 0
}
},
"interpreter": null,
"sourceType": "module",
"body": [
{
@@ -57,7 +58,7 @@
"column": 11
}
},
"callee": {
"expression": {
"type": "Identifier",
"start": 1,
"end": 11,

View File

@@ -0,0 +1,3 @@
module.exports = function() {
return {};
};

View File

@@ -0,0 +1,3 @@
module.exports = function() {
return {};
};

View File

@@ -3,6 +3,8 @@ var Foo =
function (_Bar) {
"use strict";
babelHelpers.inherits(Foo, _Bar);
function Foo(options) {
babelHelpers.classCallCheck(this, Foo);
var parentOptions = {};
@@ -14,6 +16,5 @@ function (_Bar) {
return babelHelpers.possibleConstructorReturn(this, babelHelpers.getPrototypeOf(Foo).call(this, parentOptions));
}
babelHelpers.inherits(Foo, _Bar);
return Foo;
}(Bar);

View File

@@ -7,7 +7,9 @@ exports.default = void 0;
function _instanceof(left, right) { if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { return right[Symbol.hasInstance](left); } else { return left instanceof right; } }
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } function _next(value) { step("next", value); } function _throw(err) { step("throw", err); } _next(); }); }; }
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
function _classCallCheck(instance, Constructor) { if (!_instanceof(instance, Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

View File

@@ -0,0 +1,2 @@
#!env node
var someFirstLine;

View File

@@ -0,0 +1,4 @@
{
"plugins": ["transform-strict-mode"],
"retainLines": true
}

View File

@@ -0,0 +1,2 @@
#!env node
"use strict";var someFirstLine;

View File

@@ -0,0 +1,3 @@
#!env node
console.log("Hello, world!");

View File

@@ -0,0 +1,3 @@
{
"sourceMap": true
}

View File

@@ -0,0 +1,2 @@
#!env node
console.log("Hello, world!");

View File

@@ -0,0 +1,14 @@
{
"mappings": "AAAA;AAEAA,QAAQC,GAAR,CAAY,eAAZ",
"names": [
"console",
"log"
],
"sources": [
"source-maps/interpreter-directive-prefix/input.js"
],
"sourcesContent": [
"#!env node\n\nconsole.log(\"Hello, world!\");"
],
"version": 3
}

View File

@@ -154,6 +154,66 @@ describe("addon resolution", function() {
});
});
it("should find @foo/babel-plugin when specified", function() {
process.chdir("foo-org-paths");
babel.transform("", {
filename: "filename.js",
babelrc: false,
plugins: ["@foo/babel-plugin"],
});
});
it("should find @foo/babel-preset when specified", function() {
process.chdir("foo-org-paths");
babel.transform("", {
filename: "filename.js",
babelrc: false,
presets: ["@foo/babel-preset"],
});
});
it("should find @foo/babel-plugin/index when specified", function() {
process.chdir("foo-org-paths");
babel.transform("", {
filename: "filename.js",
babelrc: false,
plugins: ["@foo/babel-plugin/index"],
});
});
it("should find @foo/babel-preset/index when specified", function() {
process.chdir("foo-org-paths");
babel.transform("", {
filename: "filename.js",
babelrc: false,
presets: ["@foo/babel-preset/index"],
});
});
it("should find @foo/babel-plugin when just scope given", function() {
process.chdir("foo-org-paths");
babel.transform("", {
filename: "filename.js",
babelrc: false,
plugins: ["@foo"],
});
});
it("should find @foo/babel-preset when just scope given", function() {
process.chdir("foo-org-paths");
babel.transform("", {
filename: "filename.js",
babelrc: false,
presets: ["@foo"],
});
});
it("should find relative path presets", function() {
process.chdir("relative-paths");

View File

@@ -1,78 +1,19 @@
# @babel/generator
> Turns a [Babylon AST](https://github.com/babel/babel/blob/master/packages/babylon/ast/spec.md) into code.
> Turns an AST into code.
See our website [@babel/generator](https://babeljs.io/docs/en/next/babel-generator.html) for more information or the [issues](https://github.com/babel/babel/issues?utf8=%E2%9C%93&q=is%3Aissue+label%3A%22pkg%3A%20generator%22+is%3Aopen) associated with this package.
## Install
Using npm:
```sh
npm install --save-dev @babel/generator
```
## Usage
or using yarn:
```js
import {parse} from 'babylon';
import generate from '@babel/generator';
const code = 'class Example {}';
const ast = parse(code);
const output = generate(ast, { /* options */ }, code);
```
## Options
Options for formatting output:
name | type | default | description
-----------------------|----------|-----------------|--------------------------------------------------------------------------
auxiliaryCommentBefore | string | | Optional string to add as a block comment at the start of the output file
auxiliaryCommentAfter | string | | Optional string to add as a block comment at the end of the output file
shouldPrintComment | function | `opts.comments` | Function that takes a comment (as a string) and returns `true` if the comment should be included in the output. By default, comments are included if `opts.comments` is `true` or if `opts.minifed` is `false` and the comment contains `@preserve` or `@license`
retainLines | boolean | `false` | Attempt to use the same line numbers in the output code as in the source code (helps preserve stack traces)
retainFunctionParens | boolean | `false` | Retain parens around function expressions (could be used to change engine parsing behavior)
comments | boolean | `true` | Should comments be included in output
compact | boolean or `'auto'` | `opts.minified` | Set to `true` to avoid adding whitespace for formatting
minified | boolean | `false` | Should the output be minified
concise | boolean | `false` | Set to `true` to reduce whitespace (but not as much as `opts.compact`)
filename | string | | Used in warning messages
jsonCompatibleStrings | boolean | `false` | Set to true to run `jsesc` with "json": true to print "\u00A9" vs. "©";
Options for source maps:
name | type | default | description
-----------------------|----------|-----------------|--------------------------------------------------------------------------
sourceMaps | boolean | `false` | Enable generating source maps
sourceRoot | string | | A root for all relative URLs in the source map
sourceFileName | string | | The filename for the source code (i.e. the code in the `code` argument). This will only be used if `code` is a string.
## AST from Multiple Sources
In most cases, Babel does a 1:1 transformation of input-file to output-file. However,
you may be dealing with AST constructed from multiple sources - JS files, templates, etc.
If this is the case, and you want the sourcemaps to reflect the correct sources, you'll need
to pass an object to `generate` as the `code` parameter. Keys
should be the source filenames, and values should be the source content.
Here's an example of what that might look like:
```js
import {parse} from 'babylon';
import generate from '@babel/generator';
const a = 'var a = 1;';
const b = 'var b = 2;';
const astA = parse(a, { sourceFilename: 'a.js' });
const astB = parse(b, { sourceFilename: 'b.js' });
const ast = {
type: 'Program',
body: [].concat(astA.program.body, astB.program.body)
};
const { code, map } = generate(ast, { sourceMaps: true }, {
'a.js': a,
'b.js': b
});
// Sourcemap will point to both a.js and b.js where appropriate.
```sh
yarn add @babel/generator --dev
```

View File

@@ -1,6 +1,6 @@
{
"name": "@babel/generator",
"version": "7.0.0-beta.47",
"version": "7.0.0-beta.52",
"description": "Turns an AST into code.",
"author": "Sebastian McKenzie <sebmck@gmail.com>",
"homepage": "https://babeljs.io/",
@@ -11,14 +11,14 @@
"lib"
],
"dependencies": {
"@babel/types": "7.0.0-beta.47",
"@babel/types": "7.0.0-beta.52",
"jsesc": "^2.5.1",
"lodash": "^4.17.5",
"source-map": "^0.5.0",
"trim-right": "^1.0.1"
},
"devDependencies": {
"@babel/helper-fixtures": "7.0.0-beta.47",
"babylon": "7.0.0-beta.47"
"@babel/helper-fixtures": "7.0.0-beta.52",
"@babel/parser": "7.0.0-beta.52"
}
}

View File

@@ -1,5 +1,5 @@
/*
Copies tests from babylon's TypeScript test suite to @babel/generator.
Copies tests from the @babel/parser's TypeScript test suite to @babel/generator.
*/
const {
copySync,
@@ -10,7 +10,10 @@ const {
} = require("fs-extra");
const { join } = require("path");
const testsFrom = join(__dirname, "../../babylon/test/fixtures/typescript");
const testsFrom = join(
__dirname,
"../../babel-parser/test/fixtures/typescript"
);
const testsTo = join(__dirname, "../test/fixtures/typescript");
emptyDirSync(testsTo);

View File

@@ -1,4 +1,10 @@
export function File(node: Object) {
if (node.program) {
// Print this here to ensure that Program node 'leadingComments' still
// get printed after the hashbang.
this.print(node.program.interpreter, node);
}
this.print(node.program, node);
}
@@ -44,4 +50,8 @@ export function Directive(node: Object) {
this.semicolon();
}
export function InterpreterDirective(node: Object) {
this.token(`#!${node.value}\n`);
}
export { StringLiteral as DirectiveLiteral } from "./types";

View File

@@ -2,8 +2,9 @@ import * as t from "@babel/types";
export function ClassDeclaration(node: Object, parent: Object) {
if (
!t.isExportDefaultDeclaration(parent) &&
!t.isExportNamedDeclaration(parent)
!this.format.decoratorsBeforeExport ||
(!t.isExportDefaultDeclaration(parent) &&
!t.isExportNamedDeclaration(parent))
) {
this.printJoin(node.decorators, node);
}

View File

@@ -67,6 +67,7 @@ export function NewExpression(node: Object, parent: Object) {
return;
}
this.print(node.typeArguments, node); // Flow
this.print(node.typeParameters, node); // TS
if (node.optional) {
@@ -91,7 +92,7 @@ export function Super() {
export function Decorator(node: Object) {
this.token("@");
this.print(node.callee, node);
this.print(node.expression, node);
this.newline();
}
@@ -125,6 +126,7 @@ export function OptionalMemberExpression(node: Object) {
export function OptionalCallExpression(node: Object) {
this.print(node.callee, node);
this.print(node.typeArguments, node); // Flow
this.print(node.typeParameters, node); // TS
if (node.optional) {
@@ -138,6 +140,7 @@ export function OptionalCallExpression(node: Object) {
export function CallExpression(node: Object) {
this.print(node.callee, node);
this.print(node.typeArguments, node); // Flow
this.print(node.typeParameters, node); // TS
this.token("(");
this.printList(node.arguments, node);

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