Compare commits
357 Commits
v7.0.0-alp
...
v7.0.0-bet
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1c13250807 | ||
|
|
8742012b5e | ||
|
|
4daf11528c | ||
|
|
c47258d68c | ||
|
|
c4f6a7a06f | ||
|
|
1341e4163b | ||
|
|
b6467a68ca | ||
|
|
5565e1b406 | ||
|
|
6560a29c36 | ||
|
|
4e612058c0 | ||
|
|
4e7961dcf8 | ||
|
|
777a9ae6e4 | ||
|
|
3a2b7fe3cd | ||
|
|
d6ba4d0a24 | ||
|
|
5df70e6a94 | ||
|
|
ca117e08cb | ||
|
|
2dd03e3ee9 | ||
|
|
4f441ff27e | ||
|
|
f7109658f9 | ||
|
|
f39811d271 | ||
|
|
fad9345c85 | ||
|
|
1797ac5015 | ||
|
|
76161e0a73 | ||
|
|
ab30fa54cb | ||
|
|
44f6ff5e85 | ||
|
|
6108bee4f9 | ||
|
|
0189b38702 | ||
|
|
b82b65a31e | ||
|
|
5e7fce3fe0 | ||
|
|
84580cc2d1 | ||
|
|
d70603ffa9 | ||
|
|
d79a7920a1 | ||
|
|
2846e06db1 | ||
|
|
beff7809ea | ||
|
|
0a4f1b0a6e | ||
|
|
75861fac87 | ||
|
|
b2b3d7944a | ||
|
|
827d84536a | ||
|
|
3e487f89ab | ||
|
|
40805894c5 | ||
|
|
95dd16aeeb | ||
|
|
ac6eda2709 | ||
|
|
960151c876 | ||
|
|
7795750862 | ||
|
|
2d8fdf3045 | ||
|
|
a70cda812c | ||
|
|
4b297907d1 | ||
|
|
48c114169f | ||
|
|
68786c4f0f | ||
|
|
1ef5871300 | ||
|
|
c3e8715010 | ||
|
|
d8b4073536 | ||
|
|
3c4f19a28d | ||
|
|
2db0c3ad1d | ||
|
|
4577bd1b7c | ||
|
|
93cf26abca | ||
|
|
62c22c7b5d | ||
|
|
63baaa7148 | ||
|
|
7e726a81e6 | ||
|
|
9e4e64dac9 | ||
|
|
3569cb9922 | ||
|
|
c6a094a9d2 | ||
|
|
cee4cde53e | ||
|
|
aa330999d0 | ||
|
|
5749276d7e | ||
|
|
7b30f77954 | ||
|
|
6ab3b4c0e3 | ||
|
|
70ab2e0620 | ||
|
|
0d16499fc0 | ||
|
|
77bbe20352 | ||
|
|
bd569433c4 | ||
|
|
fffa604023 | ||
|
|
e08ff8e650 | ||
|
|
b660f61b92 | ||
|
|
5fb282f73f | ||
|
|
7cc5580c71 | ||
|
|
2eaff3d01c | ||
|
|
b684699f79 | ||
|
|
f4716dc816 | ||
|
|
d375d80001 | ||
|
|
98824e7cb7 | ||
|
|
c28465e03e | ||
|
|
4ca686b7be | ||
|
|
b84f8e9234 | ||
|
|
9e51038ad9 | ||
|
|
777a8e2bb4 | ||
|
|
ad1f87cf07 | ||
|
|
a04c18af71 | ||
|
|
0538c3cd8c | ||
|
|
cd66657f34 | ||
|
|
9243c78ea2 | ||
|
|
218f191a59 | ||
|
|
3154c2c114 | ||
|
|
4fdd75695b | ||
|
|
9c91e35ce4 | ||
|
|
3a55e1326c | ||
|
|
370559c62f | ||
|
|
a74b307752 | ||
|
|
b41fe4efb1 | ||
|
|
68d2f8d161 | ||
|
|
1c1ce5a9e4 | ||
|
|
ab76cb6b53 | ||
|
|
009d7f0b76 | ||
|
|
f667f07d82 | ||
|
|
94f54da30b | ||
|
|
d85c642617 | ||
|
|
79f4956948 | ||
|
|
7f92e1d9dd | ||
|
|
e37a5eb5eb | ||
|
|
66ec5263a4 | ||
|
|
13d931c417 | ||
|
|
47a9ba3440 | ||
|
|
a1debae8f0 | ||
|
|
30c4d6b456 | ||
|
|
0e58007264 | ||
|
|
577173cc02 | ||
|
|
8c457e9283 | ||
|
|
2a83867436 | ||
|
|
9dd65c809f | ||
|
|
af5f34ace5 | ||
|
|
57da9bdbed | ||
|
|
d86ae2fb84 | ||
|
|
18084db7cf | ||
|
|
8e19a5b057 | ||
|
|
95882d4e5a | ||
|
|
99ab2b206c | ||
|
|
77cfa94682 | ||
|
|
79c6814d65 | ||
|
|
d479673074 | ||
|
|
6630ae9794 | ||
|
|
6bb1486405 | ||
|
|
75808a2d14 | ||
|
|
4e9a25e34a | ||
|
|
0f823beeb1 | ||
|
|
829c75a866 | ||
|
|
9d7c82d869 | ||
|
|
21eeed8a8c | ||
|
|
889f4e7791 | ||
|
|
c5e81516dd | ||
|
|
6d965c0926 | ||
|
|
2dba910b9e | ||
|
|
e32042f353 | ||
|
|
c1d07fd6db | ||
|
|
f83c83d49c | ||
|
|
605adc922d | ||
|
|
593cbc1d53 | ||
|
|
5c45753cd6 | ||
|
|
1563221171 | ||
|
|
b242e0d946 | ||
|
|
9322fd0458 | ||
|
|
f01438e9b1 | ||
|
|
ce5d1d0f59 | ||
|
|
7f1cd44d60 | ||
|
|
2841945095 | ||
|
|
76060bb2c7 | ||
|
|
84dfa659e7 | ||
|
|
e0b4543601 | ||
|
|
248743e6c5 | ||
|
|
9a1b8ea443 | ||
|
|
55aea26f13 | ||
|
|
fb9a752262 | ||
|
|
4a35243118 | ||
|
|
9fc910d8c0 | ||
|
|
51a293601b | ||
|
|
4d51052037 | ||
|
|
19c4dd2d8c | ||
|
|
2225892348 | ||
|
|
677160385c | ||
|
|
9b04cbbc4f | ||
|
|
4aca487b6d | ||
|
|
5afe40b095 | ||
|
|
b081f68e87 | ||
|
|
c9ed159a18 | ||
|
|
b9ed9919c1 | ||
|
|
04b4e414ad | ||
|
|
0b890ced19 | ||
|
|
c60bf9a897 | ||
|
|
245c78dcdc | ||
|
|
8a98141b60 | ||
|
|
78544417fc | ||
|
|
c6edce115c | ||
|
|
fe13ba8fc2 | ||
|
|
579499c66d | ||
|
|
827c70e015 | ||
|
|
8a5488e59f | ||
|
|
63204ae51e | ||
|
|
28ae47a174 | ||
|
|
aa684d1b0c | ||
|
|
1fdec955f8 | ||
|
|
213ad1ed7a | ||
|
|
797fb3c2e4 | ||
|
|
9d612e717e | ||
|
|
e919c6e6eb | ||
|
|
d82afb407e | ||
|
|
b858d7ce5e | ||
|
|
b83e0ec7b0 | ||
|
|
a0f0411abf | ||
|
|
8decefe8bc | ||
|
|
650cd43096 | ||
|
|
03f249430a | ||
|
|
8460b4c62f | ||
|
|
4710b8a5ba | ||
|
|
81e87b0838 | ||
|
|
465c087ac0 | ||
|
|
bc123ad02a | ||
|
|
e170e6d760 | ||
|
|
960e1708a1 | ||
|
|
2ce5f166d7 | ||
|
|
a7a9e7ae17 | ||
|
|
51ff4dd936 | ||
|
|
628061c501 | ||
|
|
003b8918c2 | ||
|
|
72183ff2e9 | ||
|
|
9ad660bbe1 | ||
|
|
58ec149c52 | ||
|
|
b3372a572d | ||
|
|
bc29145465 | ||
|
|
48c770e4bb | ||
|
|
3cf4cee40a | ||
|
|
ed0de70656 | ||
|
|
9a75916012 | ||
|
|
a4080dc095 | ||
|
|
4e50b2d9d9 | ||
|
|
e4b35f680d | ||
|
|
93cc22dae1 | ||
|
|
89d8f70fcd | ||
|
|
f363ec6b99 | ||
|
|
b3183b1198 | ||
|
|
892377ae57 | ||
|
|
95b3c8a16a | ||
|
|
12e39116f0 | ||
|
|
0005b9e4cf | ||
|
|
1fb3d5b0f6 | ||
|
|
bd9e1860d0 | ||
|
|
692e51609c | ||
|
|
bb5528b414 | ||
|
|
033bad3098 | ||
|
|
2cfd01aeb6 | ||
|
|
ddba7ba89f | ||
|
|
851d2cb6e0 | ||
|
|
a330cf2b09 | ||
|
|
b6b69c615a | ||
|
|
4fdff567c6 | ||
|
|
622672d397 | ||
|
|
64eafad472 | ||
|
|
1ea3b0601c | ||
|
|
5492fe130a | ||
|
|
8a4ab088e4 | ||
|
|
ba671d0a66 | ||
|
|
4595729cbb | ||
|
|
3b28bd2cb1 | ||
|
|
5387d9f903 | ||
|
|
fea3a72838 | ||
|
|
05726a976e | ||
|
|
070662e381 | ||
|
|
cdca54aed3 | ||
|
|
4081f3e23e | ||
|
|
1b29ab1289 | ||
|
|
cce83a0cea | ||
|
|
f1303aa54c | ||
|
|
dd82d7a653 | ||
|
|
ac33b1be27 | ||
|
|
ccd314cba7 | ||
|
|
82f37841f5 | ||
|
|
36ab72f095 | ||
|
|
bc013e6d34 | ||
|
|
0c8fdc381d | ||
|
|
9b05b0df5c | ||
|
|
119d5c5871 | ||
|
|
0740e61131 | ||
|
|
97d0ab78cb | ||
|
|
f537fc7da7 | ||
|
|
462825b15a | ||
|
|
9e91ac54d3 | ||
|
|
54d9732d0b | ||
|
|
d92309f0db | ||
|
|
faa6c9f708 | ||
|
|
6cc2f5dc78 | ||
|
|
a62cb9281e | ||
|
|
ef87acc389 | ||
|
|
1f22ac353a | ||
|
|
0e5f597ee6 | ||
|
|
899634d20b | ||
|
|
b048bff77d | ||
|
|
9ce797dd34 | ||
|
|
acdd3637bc | ||
|
|
85b6b4b1b2 | ||
|
|
5fe4803562 | ||
|
|
30ee87159d | ||
|
|
2a496890ff | ||
|
|
3fae121460 | ||
|
|
750b03a22f | ||
|
|
98487b5a15 | ||
|
|
a9d8040c0f | ||
|
|
3faca62a77 | ||
|
|
cc6959e1fa | ||
|
|
6bd3bf4d2f | ||
|
|
ed15443dba | ||
|
|
64ff5a080d | ||
|
|
72259ca5d3 | ||
|
|
00f58b9bfa | ||
|
|
5cc1cbf3bc | ||
|
|
8df5514083 | ||
|
|
123dce5fcd | ||
|
|
783d85ee4b | ||
|
|
b0524427c1 | ||
|
|
53e3f0dbdc | ||
|
|
c4fd05c0c2 | ||
|
|
1e55653ac1 | ||
|
|
272209ace5 | ||
|
|
7e739f954d | ||
|
|
bf9b434736 | ||
|
|
819056e94a | ||
|
|
c5bad22767 | ||
|
|
68ed633175 | ||
|
|
489cf90d23 | ||
|
|
0230dc5067 | ||
|
|
dcbb6c5ce5 | ||
|
|
b296759852 | ||
|
|
51f3ab45c4 | ||
|
|
5b261849e0 | ||
|
|
58c686378d | ||
|
|
9a92933589 | ||
|
|
5f866f2d92 | ||
|
|
0667160b11 | ||
|
|
3570ba7c28 | ||
|
|
60adcd68a0 | ||
|
|
412180e203 | ||
|
|
a1a795321a | ||
|
|
11b7db05fb | ||
|
|
ca435b6d48 | ||
|
|
982aba38e4 | ||
|
|
c1b3740707 | ||
|
|
e9bc213b14 | ||
|
|
e2c2d7d742 | ||
|
|
2cb4d08d19 | ||
|
|
149acc40bd | ||
|
|
d40cb31685 | ||
|
|
f8da5e3457 | ||
|
|
fd3a2c285a | ||
|
|
3534bc872d | ||
|
|
66f8546107 | ||
|
|
9b4c33d44e | ||
|
|
60df9f3cad | ||
|
|
f2f226b4f2 | ||
|
|
ddfb6f2c44 | ||
|
|
70354013f1 | ||
|
|
c42e027602 | ||
|
|
18d6ba9947 | ||
|
|
c82b084927 | ||
|
|
45b41740d8 | ||
|
|
b608e28aa7 | ||
|
|
06f67e1ad3 | ||
|
|
b5bb89b30a | ||
|
|
0c2e3b1045 | ||
|
|
9b410be61c | ||
|
|
f81d7496b1 |
@@ -1,3 +1,4 @@
|
||||
# Ensure babel-register won't compile fixtures, or try to recompile compiled code.
|
||||
packages/*/test/fixtures
|
||||
packages/*/lib
|
||||
packages/babel-standalone/babel.js
|
||||
|
||||
28
.babelrc.js
28
.babelrc.js
@@ -6,12 +6,28 @@ let envOpts = {
|
||||
|
||||
module.exports = {
|
||||
comments: false,
|
||||
plugins: [
|
||||
// temp until next release
|
||||
function() {
|
||||
return {
|
||||
visitor: {
|
||||
"Function": function(path) {
|
||||
const node = path.node;
|
||||
for (let i = 0; i < node.params.length; i++) {
|
||||
const param = node.params[i];
|
||||
if (param.type === "AssignmentPattern") {
|
||||
param.left.optional = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
],
|
||||
presets: [
|
||||
[
|
||||
"env", envOpts
|
||||
],
|
||||
["env", envOpts],
|
||||
"stage-0",
|
||||
"flow",
|
||||
"flow"
|
||||
],
|
||||
env: {
|
||||
cov: {
|
||||
@@ -21,9 +37,9 @@ module.exports = {
|
||||
}
|
||||
};
|
||||
|
||||
if (process.env.BABEL_ENV === 'development') {
|
||||
if (process.env.BABEL_ENV === "development") {
|
||||
envOpts.targets = {
|
||||
node: "current"
|
||||
};
|
||||
envOpts.debug = true;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -7,3 +7,9 @@ packages/*/lib
|
||||
packages/*/dist
|
||||
packages/*/test/fixtures
|
||||
packages/*/test/tmp
|
||||
packages/babel-standalone/babel.js
|
||||
packages/babel-standalone/babel.min.js
|
||||
|
||||
# Prettier tries to insert trailing commas in function calls, which Node.js
|
||||
# doesn't natively support. This causes an error when loading the Gulp tasks.
|
||||
packages/babel-standalone/src/gulpTasks.js
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
{
|
||||
"extends": "babel",
|
||||
"plugins": [
|
||||
"prettier"
|
||||
],
|
||||
"rules": {
|
||||
"comma-dangle": ["error", "always-multiline"],
|
||||
"curly": ["error", "multi-line"],
|
||||
"func-call-spacing": "error",
|
||||
"key-spacing": "error",
|
||||
"no-multi-spaces": "error"
|
||||
"prettier/prettier": ["error", { "trailingComma": "es5" }]
|
||||
},
|
||||
"env": {
|
||||
"node": true,
|
||||
|
||||
@@ -13,6 +13,5 @@ lib/types.js
|
||||
lib/third-party-libs.js.flow
|
||||
|
||||
[options]
|
||||
strip_root=true
|
||||
suppress_comment= \\(.\\|\n\\)*\\$FlowFixMe
|
||||
suppress_comment= \\(.\\|\n\\)*\\$FlowIssue
|
||||
|
||||
13
.github/PULL_REQUEST_TEMPLATE.md
vendored
13
.github/PULL_REQUEST_TEMPLATE.md
vendored
@@ -2,20 +2,19 @@
|
||||
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
|
||||
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. It should be underlined in the preview if done correctly.
|
||||
-->
|
||||
|
||||
| Q | A <!--(yes/no) -->
|
||||
| Q | A <!--(can use an emoji 👍 ) -->
|
||||
| ------------------------ | ---
|
||||
| Fixed Issues | `Fixes #1, Fixes #2` <!-- rm the quotes to link the issues -->
|
||||
| Patch: Bug Fix? |
|
||||
| Major: Breaking Change? |
|
||||
| Minor: New Feature? |
|
||||
| Deprecations? |
|
||||
| Spec Compliancy? |
|
||||
| Tests Added/Pass? |
|
||||
| Fixed Tickets | `Fixes #1, Fixes #2` <!-- rm the quotes to link the issues -->
|
||||
| Spec Compliancy? |
|
||||
| License | MIT
|
||||
| Doc PR | <!-- if yes, add `[skip ci]` to your commit message to skip CI builds -->
|
||||
| Dependency Changes |
|
||||
| Doc PR | <!-- if yes, can add `[skip ci]` to your commit message to skip CI builds -->
|
||||
| Any Dependency Changes? |
|
||||
|
||||
<!-- Describe your changes below in as much detail as possible -->
|
||||
|
||||
5
.gitignore
vendored
5
.gitignore
vendored
@@ -10,6 +10,7 @@
|
||||
/coverage
|
||||
dist
|
||||
/.package.json
|
||||
package-lock.json
|
||||
/packages/babel-runtime/core-js/**/*.js
|
||||
!/packages/babel-runtime/core-js/map.js
|
||||
/packages/babel-runtime/helpers/*.js
|
||||
@@ -21,6 +22,10 @@ dist
|
||||
/packages/babel-runtime/helpers/es6/*.js
|
||||
!/packages/babel-runtime/helpers/es6/toArray.js
|
||||
/packages/babel-register/test/.babel
|
||||
/packages/babel-cli/test/tmp
|
||||
/packages/babel-node/test/tmp
|
||||
/packages/*/lib
|
||||
.nyc_output
|
||||
/babel.sublime-workspace
|
||||
packages/babel-standalone/babel.js
|
||||
packages/babel-standalone/babel.min.js
|
||||
|
||||
12
.travis.yml
12
.travis.yml
@@ -7,14 +7,22 @@ cache:
|
||||
directories:
|
||||
- node_modules
|
||||
node_js:
|
||||
- '7'
|
||||
- '8'
|
||||
- '6'
|
||||
- '4'
|
||||
|
||||
env:
|
||||
- JOB=test
|
||||
global:
|
||||
- PATH=$HOME/.yarn/bin:$PATH
|
||||
- JOB=test
|
||||
|
||||
before_install:
|
||||
- curl -o- -L https://yarnpkg.com/install.sh | bash -s -- --version 0.28.1
|
||||
|
||||
script:
|
||||
# Babel doesn't build correctly with npm v2 (which comes bundled with Node v4)
|
||||
# so we manually upgrade to a known working npm version.
|
||||
- npm install --global npm@4
|
||||
- 'if [ "$JOB" = "test" ]; then make test-ci; fi'
|
||||
- 'if [ "$JOB" = "lint" ]; then make lint && make flow; fi'
|
||||
|
||||
|
||||
137
CHANGELOG.md
137
CHANGELOG.md
@@ -13,6 +13,93 @@ _Note: Gaps between patch versions are faulty, broken or test releases._
|
||||
|
||||
See [CHANGELOG - 6to5](CHANGELOG-6to5.md) for the pre-4.0.0 version changelog.
|
||||
|
||||
## 6.26.0 (2017-08-16)
|
||||
|
||||
> Backports for some folks (also other's when we accidently merged PRs from both 6.x/master)
|
||||
> Lesson learned: just use `master` and backport on another branch.
|
||||
|
||||
#### :eyeglasses: Spec Compliancy
|
||||
* `babel-core`, `babel-generator`, `babel-plugin-transform-flow-comments`, `babel-plugin-transform-flow-strip-types`, `babel-traverse`, `babel-types`
|
||||
* [#6081](https://github.com/babel/babel/pull/6081) Flow opaque type 6.x backport. ([@jbrown215](https://github.com/jbrown215))
|
||||
|
||||
#### :rocket: New Feature
|
||||
* `babel-cli`
|
||||
* [#5796](https://github.com/babel/babel/pull/5796) Allow --inspect-brk option to be used with babel-node [6.x backport]. ([@noinkling](https://github.com/noinkling))
|
||||
|
||||
#### :bug: Bug Fix
|
||||
* `babel-plugin-transform-es2015-modules-commonjs`
|
||||
* [#5811](https://github.com/babel/babel/pull/5811) Fix 5768. ([@joshwnj](https://github.com/joshwnj))
|
||||
* [#5469](https://github.com/babel/babel/pull/5469) Fix commonjs exports with destructuring.. ([@yavorsky](https://github.com/yavorsky))
|
||||
* `babel-types`
|
||||
* [#5693](https://github.com/babel/babel/pull/5693) Hoist toSequenceExpression's convert helper. ([@jridgewell](https://github.com/jridgewell))
|
||||
|
||||
#### :memo: Documentation
|
||||
* `babel-plugin-transform-class-properties`
|
||||
* [#6005](https://github.com/babel/babel/pull/6005) FIX access to the prototype of an instance. ([@shuaibird](https://github.com/shuaibird))
|
||||
* `babel-plugin-transform-runtime`
|
||||
* [#5857](https://github.com/babel/babel/pull/5857) Fix typos in README.md. ([@danny-andrews](https://github.com/danny-andrews))
|
||||
* `babel-plugin-transform-regenerator`
|
||||
* [#5852](https://github.com/babel/babel/pull/5852) Fix babel-plugin-transform-regenerator README. ([@k15a](https://github.com/k15a))
|
||||
* Other
|
||||
* [#5788](https://github.com/babel/babel/pull/5788) Add a section on troubleshooting [skip ci]. ([@peey](https://github.com/peey))
|
||||
* [#5755](https://github.com/babel/babel/pull/5755) Fix broken tables in README.md. ([@u9lyfish](https://github.com/u9lyfish))
|
||||
* `babel-generator`, `babel-plugin-transform-es2015-arrow-functions`, `babel-plugin-transform-es2015-modules-commonjs`, `babel-plugin-transform-es2015-spread`, `babel-plugin-transform-runtime`, `babel-register`
|
||||
* [#5613](https://github.com/babel/babel/pull/5613) Backport doc changes. ([@xtuc](https://github.com/xtuc))
|
||||
|
||||
#### :house: Internal
|
||||
* `babel-traverse`
|
||||
* [#5965](https://github.com/babel/babel/pull/5965) Remove unused functions from renamer.js.. ([@mcav](https://github.com/mcav))
|
||||
* [#5363](https://github.com/babel/babel/pull/5363) Increase the code coverage for traverse evaluation. ([@ssuman](https://github.com/ssuman))
|
||||
* Other
|
||||
* [#5938](https://github.com/babel/babel/pull/5938) Remove codecov node package and use bash uploader. ([@existentialism](https://github.com/existentialism))
|
||||
|
||||
#### Committers: 19
|
||||
- Artem Yavorsky ([yavorsky](https://github.com/yavorsky))
|
||||
- Brian Ng ([existentialism](https://github.com/existentialism))
|
||||
- Danny Andrews ([danny-andrews](https://github.com/danny-andrews))
|
||||
- Henry Zhu ([hzoo](https://github.com/hzoo))
|
||||
- Jeffrey Wear ([wearhere](https://github.com/wearhere))
|
||||
- Jordan Brown ([jbrown215](https://github.com/jbrown215))
|
||||
- Josh Johnston ([joshwnj](https://github.com/joshwnj))
|
||||
- Justin Ridgewell ([jridgewell](https://github.com/jridgewell))
|
||||
- Konstantin Pschera ([k15a](https://github.com/k15a))
|
||||
- Malcolm ([noinkling](https://github.com/noinkling))
|
||||
- Marcus Cavanaugh ([mcav](https://github.com/mcav))
|
||||
- Peeyush Kushwaha ([peey](https://github.com/peey))
|
||||
- Philipp Friedenberger ([MrSpider](https://github.com/MrSpider))
|
||||
- Samuel Reed ([STRML](https://github.com/STRML))
|
||||
- Shuaibird Hwang ([shuaibird](https://github.com/shuaibird))
|
||||
- Suman ([ssuman](https://github.com/ssuman))
|
||||
- Sven SAULEAU ([xtuc](https://github.com/xtuc))
|
||||
- jonathan schatz ([modosc](https://github.com/modosc))
|
||||
- u9lyfish@gmail.com ([u9lyfish](https://github.com/u9lyfish))
|
||||
|
||||
## 6.25.0 (2017-06-08)
|
||||
|
||||
Just backporting a few things.
|
||||
|
||||
#### :rocket: New Feature
|
||||
* `babel-plugin-transform-react-display-name`
|
||||
* [#5780](https://github.com/babel/babel/pull/5780) Backport support for createReactClass with transform-react-display-name. ([@kentor](https://github.com/kentor))
|
||||
* [#5554](https://github.com/babel/babel/pull/5554) Updated transform-react-display-name for createReactClass addon. ([@bvaughn](https://github.com/bvaughn))
|
||||
* `babel-generator`, `babel-plugin-transform-flow-strip-types`, `babel-types`
|
||||
* [#5653](https://github.com/babel/babel/pull/5653) Port flow object spread from #418 to 6.x. ([@kittens](https://github.com/kittens))
|
||||
|
||||
#### :bug: Bug Fix
|
||||
* `babel-types`
|
||||
* [#5770](https://github.com/babel/babel/pull/5770) Backport array & object pattern fixes to 6.x. ([@citycide](https://github.com/citycide))
|
||||
|
||||
#### :nail_care: Polish
|
||||
* `babel-traverse`
|
||||
* [#5615](https://github.com/babel/babel/pull/5615) Update deprecation warning on flow bindings. ([@kassens](https://github.com/kassens))
|
||||
|
||||
#### Committers: 5
|
||||
- Bo Lingen ([citycide](https://github.com/citycide))
|
||||
- Brian Vaughn ([bvaughn](https://github.com/bvaughn))
|
||||
- Jan Kassens ([kassens](https://github.com/kassens))
|
||||
- Kenneth Chung ([kentor](https://github.com/kentor))
|
||||
- Sebastian McKenzie ([kittens](https://github.com/kittens))
|
||||
|
||||
## 6.24.0 (2017-03-13)
|
||||
|
||||
A quick release for 2 features:
|
||||
@@ -263,7 +350,7 @@ New/Expected Behavior
|
||||
|
||||
```js
|
||||
const _ref = foo(); // should only be called once
|
||||
const { x } = _ref;
|
||||
const { x } = _ref;
|
||||
const y = _objectWithoutProperties(_ref, ["x"]);
|
||||
```
|
||||
|
||||
@@ -279,7 +366,7 @@ function fn({a = 1, ...b} = {}) {
|
||||
return {a, b};
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
* `babel-plugin-transform-es2015-destructuring`
|
||||
* [#5093](https://github.com/babel/babel/pull/5093) Ensure array is always copied during destructure. ([@existentialism](https://github.com/existentialism))
|
||||
|
||||
@@ -293,7 +380,7 @@ const arr = [1, 2, 3]
|
||||
assign(arr, 1, 42)
|
||||
console.log(arr) // [1, 2, 3]
|
||||
```
|
||||
|
||||
|
||||
* `babel-plugin-transform-es2015-function-name`
|
||||
* [#5008](https://github.com/babel/babel/pull/5008) Don't try to visit ArrowFunctionExpression, they cannot be named. ([@Kovensky](https://github.com/Kovensky))
|
||||
|
||||
@@ -308,9 +395,9 @@ Output
|
||||
|
||||
```js
|
||||
export const x = ({ x }) => x;
|
||||
export const y = function y() {};
|
||||
export const y = function y() {};
|
||||
```
|
||||
|
||||
|
||||
* `babel-types`
|
||||
* [#5068](https://github.com/babel/babel/pull/5068) Fix getBindingIdentifiers in babel-types. ([@rtsao](https://github.com/rtsao))
|
||||
* `babel-cli`
|
||||
@@ -460,7 +547,7 @@ Will still error with `Spread children are not supported.`
|
||||
```js
|
||||
<div>{...this.props.children}</div>;
|
||||
```
|
||||
|
||||
|
||||
* `babel-plugin-transform-es2015-block-scoping`, `babel-plugin-transform-react-constant-elements`, `babel-traverse`
|
||||
* [#4940](https://github.com/babel/babel/pull/4940) Fix React constant element bugs. ([@appden](https://github.com/appden))
|
||||
|
||||
@@ -469,7 +556,7 @@ When multiple declarators are present in a declaration, we want to insert the co
|
||||
```js
|
||||
function render() {
|
||||
const bar = "bar", renderFoo = () => <foo bar={bar} baz={baz} />, baz = "baz";
|
||||
|
||||
|
||||
return renderFoo();
|
||||
}
|
||||
```
|
||||
@@ -480,12 +567,12 @@ When block scoped variables caused the block to be wrapped in a closure, the var
|
||||
function render(flag) {
|
||||
if (flag) {
|
||||
let bar = "bar";
|
||||
|
||||
|
||||
[].map(() => bar);
|
||||
|
||||
|
||||
return <foo bar={bar} />;
|
||||
}
|
||||
|
||||
|
||||
return null;
|
||||
}
|
||||
```
|
||||
@@ -526,7 +613,7 @@ for (let a of b) {
|
||||
* [#4999](https://github.com/babel/babel/pull/4999) babel-helper-transform-fixture-test-runner: pass require as a global. ([@hzoo](https://github.com/hzoo))
|
||||
|
||||
Allows running `require()` in exec.js tests like for [babel/babel-preset-env#95](https://github.com/babel/babel-preset-env/pull/95)
|
||||
|
||||
|
||||
* Other
|
||||
* [#5005](https://github.com/babel/babel/pull/5005) internal: don't run watch with the test env (skip building with code …. ([@hzoo](https://github.com/hzoo))
|
||||
|
||||
@@ -648,8 +735,8 @@ try {
|
||||
return x;
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
```
|
||||
|
||||
* `babel-helper-remap-async-to-generator`, `babel-plugin-transform-async-generator-functions`, `babel-plugin-transform-async-to-generator`
|
||||
* [#4901](https://github.com/babel/babel/pull/4901) Only base async fn arity on non-default/non-rest params - Closes [#4891](https://github.com/babel/babel/issues/4891). ([@loganfsmyth](https://github.com/loganfsmyth))
|
||||
|
||||
@@ -660,7 +747,7 @@ console.log(foo.length) // 0
|
||||
const asyncFoo = async (...args) => { }
|
||||
console.log(asyncFoo.length) // 0
|
||||
```
|
||||
|
||||
|
||||
* `babel-generator`, `babel-types`
|
||||
* [#4945](https://github.com/babel/babel/pull/4945) Add `babel-generator` support for `Import`. ([@TheLarkInn](https://github.com/TheLarkInn))
|
||||
|
||||
@@ -669,14 +756,14 @@ console.log(asyncFoo.length) // 0
|
||||
```js
|
||||
import("module.js");
|
||||
```
|
||||
|
||||
|
||||
* `babel-plugin-transform-object-rest-spread`
|
||||
* [#4883](https://github.com/babel/babel/pull/4883) Fix for object-rest with parameters destructuring nested rest. ([@christophehurpeau](https://github.com/christophehurpeau))
|
||||
|
||||
```js
|
||||
function a5({a3, b2: { ba1, ...ba2 }, ...c3}) {}
|
||||
```
|
||||
|
||||
```
|
||||
|
||||
* `babel-traverse`
|
||||
* [#4875](https://github.com/babel/babel/pull/4875) Fix `path.evaluate` for references before declarations. ([@boopathi](https://github.com/boopathi))
|
||||
|
||||
@@ -981,7 +1068,7 @@ function render(_ref) {
|
||||
- Scott Stern ([sstern6](https://github.com/sstern6))
|
||||
- Shine Wang ([shinew](https://github.com/shinew))
|
||||
- lion ([lion-man44](https://github.com/lion-man44))
|
||||
|
||||
|
||||
## v6.18.2 (2016-11-01)
|
||||
|
||||
Weird publishing issue with v6.18.1, same release.
|
||||
@@ -1666,7 +1753,7 @@ export default {
|
||||
#### :bug: Bug Fix
|
||||
* `babel-helpers`, `babel-plugin-transform-es2015-typeof-symbol`
|
||||
* [#3686](https://github.com/babel/babel/pull/3686) Fix `typeof Symbol.prototype`. ([@brainlock](https://github.com/brainlock))
|
||||
|
||||
|
||||
```js
|
||||
// `typeof Symbol.prototype` should be 'object'
|
||||
typeof Symbol.prototype === 'object'
|
||||
@@ -1675,7 +1762,7 @@ typeof Symbol.prototype === 'object'
|
||||
* `babel-cli`
|
||||
* [#3456](https://github.com/babel/babel/pull/3456) Use the real sourcemap API and handle input sourcemaps - Fixes [#7259](https://github.com/babel/babel/issues/7259). ([@loganfsmyth](https://github.com/loganfsmyth))
|
||||
* [#4507](https://github.com/babel/babel/pull/4507) Only set options in cli if different from default. ([@danez](https://github.com/danez))
|
||||
|
||||
|
||||
Fix an issue with defaults not being overidden. This was causing options like `comments: false` not to work correctly.
|
||||
|
||||
* [#4508](https://github.com/babel/babel/pull/4508) Support custom ports for V8 --inspect. ([@andykant](https://github.com/andykant))
|
||||
@@ -1730,7 +1817,7 @@ We noticed that we can not make this optimizations if there are function calls o
|
||||
// was tranforming to
|
||||
x = a();
|
||||
y = obj.x;
|
||||
// now transforms to
|
||||
// now transforms to
|
||||
var _ref = [a(), obj.x];
|
||||
x = _ref[0];
|
||||
y = _ref[1];
|
||||
@@ -1796,7 +1883,7 @@ Cleanup tests, remove various unused dependencies, do not run CI with only readm
|
||||
#### Commiters: 20
|
||||
|
||||
First PRs!
|
||||
- Alberto Piai ([brainlock](https://github.com/brainlock))
|
||||
- Alberto Piai ([brainlock](https://github.com/brainlock))
|
||||
- Andy Kant ([andykant](https://github.com/andykant))
|
||||
- Basil Hosmer ([bhosmer](https://github.com/bhosmer))
|
||||
- Bo Borgerson ([gigabo](https://github.com/gigabo))
|
||||
@@ -1879,7 +1966,7 @@ npm install babel-preset-latest --save-dev
|
||||
{ "presets": [
|
||||
["latest", {
|
||||
"es2015": {
|
||||
"modules": false
|
||||
"modules": false
|
||||
}
|
||||
}]
|
||||
] }
|
||||
@@ -2117,7 +2204,7 @@ Can be `false` to not transform modules, or one of `["amd", "umd", "systemjs", "
|
||||
|
||||
## v6.11.5 (2016-07-23)
|
||||
|
||||
Thanks to Rob Eisenberg ([EisenbergEffect](https://github.com/EisenbergEffect)), Keyan Zhang ([keyanzhang](https://github.com/keyanzhang)), Rolf Timmermans ([rolftimmermans](https://github.com/rolftimmermans)), Thomas Grainger ([graingert](https://github.com/graingert)),
|
||||
Thanks to Rob Eisenberg ([EisenbergEffect](https://github.com/EisenbergEffect)), Keyan Zhang ([keyanzhang](https://github.com/keyanzhang)), Rolf Timmermans ([rolftimmermans](https://github.com/rolftimmermans)), Thomas Grainger ([graingert](https://github.com/graingert)),
|
||||
|
||||
we have few fixes: fix `babel-register` file paths on error, infer class name for classes with class properties, fix `export *` to account for previously compiled modules.
|
||||
|
||||
@@ -2165,7 +2252,7 @@ In this release among other things are some more optimizations for babel-generat
|
||||
|
||||
## v6.11.3 (2016-07-13)
|
||||
|
||||
The main fix is @loganfsmyth's changes of some parts in babel-generator in [#3565](https://github.com/babel/babel/pull/3565) to fix issues with exponential code generation times in certain cases.
|
||||
The main fix is @loganfsmyth's changes of some parts in babel-generator in [#3565](https://github.com/babel/babel/pull/3565) to fix issues with exponential code generation times in certain cases.
|
||||
|
||||
Items: the size of the array being generated
|
||||
Time: The time in ms to generate the code
|
||||
|
||||
@@ -31,6 +31,8 @@ Contributions are always welcome, no matter how large or small.
|
||||
- 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
|
||||
- When you feel ready to jump into the Babel source code, a good place to start is to look for issues tagged with [help-wanted](https://github.com/babel/babel/issues?q=is%3Aissue+is%3Aopen+label%3A%22help+wanted%22) and/or [beginner-friendly](https://github.com/babel/babel/issues?q=is%3Aissue+is%3Aopen+label%3A%22beginner-friendly%22).
|
||||
- Follow along with what we are working on by joining our Slack, following our annoucements on [Twitter](https://twitter.com/babeljs), and reading (or participating!) in our [meeting notes](https://github.com/babel/notes).
|
||||
- Check out our [website](http://babeljs.io/) and the [repo](https://github.com/babel/website)
|
||||
|
||||
## Chat
|
||||
|
||||
@@ -40,11 +42,9 @@ Feel free to check out the `#discussion`/`#development` channels on our [Slack](
|
||||
|
||||
**Note:** Versions `< 5.1.10` can't be built.
|
||||
|
||||
Babel is built for Node.js 4 and up but we develop using Node.js 6. Make sure you are on npm 3.
|
||||
Babel is built for Node 4 and up but we develop using Node 8 and yarn. You can check this with `node -v`.
|
||||
|
||||
You can check this with `node -v` and `npm -v`.
|
||||
|
||||
In addition, make sure that Yarn is installed.
|
||||
Make sure that Yarn is installed with version >= `0.28.0`.
|
||||
Installation instructions can be found here: https://yarnpkg.com/en/docs/install.
|
||||
|
||||
### Setup
|
||||
@@ -114,12 +114,25 @@ To run tests for a specific package in [packages](https://github.com/babel/babel
|
||||
$ TEST_ONLY=babel-cli make test
|
||||
```
|
||||
|
||||
`TEST_ONLY` will also match substrings of the package name:
|
||||
|
||||
```sh
|
||||
# Run tests for the babel-plugin-transform-es2015-classes package.
|
||||
$ TEST_ONLY=es2015-class make test
|
||||
```
|
||||
|
||||
Use the `TEST_GREP` variable to run a subset of tests by name:
|
||||
|
||||
```sh
|
||||
$ TEST_GREP=transformation make test
|
||||
```
|
||||
|
||||
Substitute spaces for hyphens and forward slashes when targeting specific test names:
|
||||
|
||||
```sh
|
||||
$ TEST_GREP="arrow functions destructuring parameters" make test
|
||||
```
|
||||
|
||||
To enable the Node.js debugger added in v6.3.0, set the `TEST_DEBUG` environment variable:
|
||||
|
||||
```sh
|
||||
@@ -138,15 +151,15 @@ $ ./scripts/test-cov.sh
|
||||
|
||||
#### Troubleshooting Tests
|
||||
|
||||
In case you're not able to reproduce an error on CI locally, it may be due to
|
||||
In case you're not able to reproduce an error on CI locally, it may be due to
|
||||
|
||||
- Node Version: Travis CI runs the tests against all major node versions. If your tests use JavaScript features unsupported by lower versions of node, then use [minNodeVersion option](#writing-tests) in options.json.
|
||||
- Timeout: Check the CI log and if the only errors are timeout errors and you are sure that it's not related to the changes you made, ask someone in the slack channel to trigger rebuild on the CI build and it might be resolved
|
||||
|
||||
|
||||
In case you're locally getting errors which are not on the CI, it may be due to
|
||||
|
||||
- Updates in Dependencies: Make sure you run `make bootstrap` before you run `make build` or `make watch` before you run the tests.
|
||||
|
||||
|
||||
### Writing tests
|
||||
|
||||
Most packages in [`/packages`](https://github.com/babel/babel/tree/master/packages) have a `test` folder, however some tests might be in other packages or in [`/packages/babel-core`](https://github.com/babel/babel/tree/master/packages/babel-core/test/fixtures).
|
||||
@@ -261,7 +274,7 @@ To start the debugging in Chrome DevTools, open the given URL.
|
||||
The debugger starts at the first executed line of code, which is Mocha's first line by default.
|
||||
Click _Resume script execution_ <img src="https://i.imgur.com/TmYBn9d.png" alt="Resume script execution button." width="16"> to jump to the set breakpoint.
|
||||
Note that the code shown in Chrome DevTools is compiled code and therefore differs.
|
||||
|
||||
|
||||
## Internals
|
||||
- AST spec ([babylon/ast/spec.md](https://github.com/babel/babylon/blob/master/ast/spec.md))
|
||||
- Versioning ([doc/design/versioning.md](https://github.com/babel/babel/blob/master/doc/design/versioning.md)
|
||||
|
||||
53
Gulpfile.js
53
Gulpfile.js
@@ -21,32 +21,41 @@ function swapSrcWithLib(srcPath) {
|
||||
|
||||
gulp.task("default", ["build"]);
|
||||
|
||||
gulp.task("build", function () {
|
||||
return gulp.src(scripts, { base: base })
|
||||
.pipe(plumber({
|
||||
errorHandler: function (err) {
|
||||
gutil.log(err.stack);
|
||||
},
|
||||
}))
|
||||
.pipe(newer({
|
||||
dest: base,
|
||||
map: swapSrcWithLib,
|
||||
}))
|
||||
.pipe(through.obj(function (file, enc, callback) {
|
||||
gutil.log("Compiling", "'" + chalk.cyan(file.relative) + "'...");
|
||||
callback(null, file);
|
||||
}))
|
||||
gulp.task("build", function() {
|
||||
return gulp
|
||||
.src(scripts, { base: base })
|
||||
.pipe(
|
||||
plumber({
|
||||
errorHandler: function(err) {
|
||||
gutil.log(err.stack);
|
||||
},
|
||||
})
|
||||
)
|
||||
.pipe(
|
||||
newer({
|
||||
dest: base,
|
||||
map: swapSrcWithLib,
|
||||
})
|
||||
)
|
||||
.pipe(
|
||||
through.obj(function(file, enc, callback) {
|
||||
gutil.log("Compiling", "'" + chalk.cyan(file.relative) + "'...");
|
||||
callback(null, file);
|
||||
})
|
||||
)
|
||||
.pipe(babel())
|
||||
.pipe(through.obj(function (file, enc, callback) {
|
||||
// Passing 'file.relative' because newer() above uses a relative path and this keeps it consistent.
|
||||
file.path = path.resolve(file.base, swapSrcWithLib(file.relative));
|
||||
callback(null, file);
|
||||
}))
|
||||
.pipe(
|
||||
through.obj(function(file, enc, callback) {
|
||||
// Passing 'file.relative' because newer() above uses a relative path and this keeps it consistent.
|
||||
file.path = path.resolve(file.base, swapSrcWithLib(file.relative));
|
||||
callback(null, file);
|
||||
})
|
||||
)
|
||||
.pipe(gulp.dest(base));
|
||||
});
|
||||
|
||||
gulp.task("watch", ["build"], function () {
|
||||
watch(scripts, { debounceDelay: 200 }, function () {
|
||||
gulp.task("watch", ["build"], function() {
|
||||
watch(scripts, { debounceDelay: 200 }, function() {
|
||||
gulp.start("build");
|
||||
});
|
||||
});
|
||||
|
||||
23
Makefile
23
Makefile
@@ -2,10 +2,20 @@ MAKEFLAGS = -j1
|
||||
|
||||
export NODE_ENV = test
|
||||
|
||||
# Fix color output until TravisCI fixes https://github.com/travis-ci/travis-ci/issues/7967
|
||||
export FORCE_COLOR = true
|
||||
|
||||
.PHONY: build build-dist watch lint fix clean test-clean test-only test test-ci publish bootstrap
|
||||
|
||||
build: clean
|
||||
rm -rf packages/*/lib
|
||||
./node_modules/.bin/gulp build
|
||||
ifneq ($(BABEL_ENV), "cov")
|
||||
make build-standalone
|
||||
endif
|
||||
|
||||
build-standalone:
|
||||
./node_modules/.bin/gulp build-babel-standalone --cwd=packages/babel-standalone/
|
||||
|
||||
build-dist: build
|
||||
cd packages/babel-polyfill; \
|
||||
@@ -19,13 +29,13 @@ watch: clean
|
||||
BABEL_ENV=development ./node_modules/.bin/gulp watch
|
||||
|
||||
lint:
|
||||
./node_modules/.bin/eslint scripts packages *.js --format=codeframe
|
||||
./node_modules/.bin/eslint scripts packages *.js --format=codeframe --rulesdir="./eslint_rules"
|
||||
|
||||
flow:
|
||||
./node_modules/.bin/flow check
|
||||
./node_modules/.bin/flow check --strip-root
|
||||
|
||||
fix:
|
||||
./node_modules/.bin/eslint scripts packages *.js --format=codeframe --fix
|
||||
./node_modules/.bin/eslint scripts packages *.js --format=codeframe --fix --rulesdir="./eslint_rules"
|
||||
|
||||
clean: test-clean
|
||||
rm -rf packages/babel-polyfill/browser*
|
||||
@@ -43,6 +53,8 @@ clean-all:
|
||||
rm -rf packages/*/lib
|
||||
rm -rf node_modules
|
||||
rm -rf packages/*/node_modules
|
||||
rm -rf package-lock.json
|
||||
rm -rf packages/*/package-lock.json
|
||||
make clean
|
||||
|
||||
test-only:
|
||||
@@ -55,10 +67,11 @@ test-ci:
|
||||
make bootstrap
|
||||
make test-only
|
||||
|
||||
test-ci-coverage: SHELL:=/bin/bash
|
||||
test-ci-coverage:
|
||||
BABEL_ENV=cov make bootstrap
|
||||
./scripts/test-cov.sh
|
||||
./node_modules/.bin/codecov -f coverage/coverage-final.json
|
||||
bash <(curl -s https://codecov.io/bash) -f coverage/coverage-final.json
|
||||
|
||||
publish:
|
||||
git pull --rebase
|
||||
@@ -67,7 +80,7 @@ publish:
|
||||
make test
|
||||
# not using lerna independent mode atm, so only update packages that have changed since we use ^
|
||||
# --only-explicit-updates
|
||||
./node_modules/.bin/lerna publish --npm-tag=next --exact --skip-temp-tag
|
||||
./node_modules/.bin/lerna publish --force-publish=* --npm-tag=next --exact --skip-temp-tag
|
||||
make clean
|
||||
|
||||
bootstrap:
|
||||
|
||||
@@ -77,7 +77,7 @@ https://phabricator.babeljs.io/T2168 mostly corresponds to https://github.com/ba
|
||||
|
||||
## Want to report an issue with [babeljs.io](https://babeljs.io) (the website)?
|
||||
|
||||
For documentation and website issues please visit the [babel/babel.github.io](https://github.com/babel/babel.github.io) repo.
|
||||
For documentation and website issues please visit the [babel/website](https://github.com/babel/website) repo.
|
||||
|
||||
## Want to contribute to Babel?
|
||||
|
||||
@@ -86,6 +86,7 @@ Check out our [CONTRIBUTING.md](https://github.com/babel/babel/blob/master/CONTR
|
||||
You can also start by checking out the issues with the [help-wanted](https://github.com/babel/babel/issues?q=is%3Aissue+is%3Aopen+label%3A%22help+wanted%22) label.
|
||||
|
||||
Our discussions/notes/roadmap: [babel/notes](https://github.com/babel/notes)
|
||||
Our progress on TC39 proposals: [babel/proposals](https://github.com/babel/proposals)
|
||||
|
||||
## Packages
|
||||
|
||||
|
||||
16
circle.yml
16
circle.yml
@@ -1,11 +1,17 @@
|
||||
general:
|
||||
artifacts:
|
||||
- "packages/babel-standalone/babel.js"
|
||||
- "packages/babel-standalone/babel.min.js"
|
||||
|
||||
machine:
|
||||
node:
|
||||
version:
|
||||
6
|
||||
8
|
||||
|
||||
dependencies:
|
||||
pre:
|
||||
- curl -o- -L https://yarnpkg.com/install.sh | bash
|
||||
# Version number can be removed once 0.28.x or higher is released as stable
|
||||
- curl -o- -L https://yarnpkg.com/install.sh | bash -s -- --version 0.28.4
|
||||
cache_directories:
|
||||
- ~/.yarn-cache
|
||||
override:
|
||||
@@ -14,3 +20,9 @@ dependencies:
|
||||
test:
|
||||
override:
|
||||
- make test-ci-coverage
|
||||
# Builds babel-standalone with the regular Babel config
|
||||
- make build
|
||||
# test-ci-coverage doesn't test babel-standalone, as trying to gather coverage
|
||||
# data for a JS file that's several megabytes large is bound to fail. Here,
|
||||
# we just run the babel-standalone test separately.
|
||||
- ./node_modules/mocha/bin/_mocha packages/babel-standalone/test/ --opts test/mocha.opts
|
||||
|
||||
@@ -21,7 +21,6 @@ This is quite taboo but let's look at the pros and cons:
|
||||
|
||||
* Codebase looks more intimidating.
|
||||
* Repo is bigger in size.
|
||||
* Lower ranking in [npms](https://npms.io/) results. At least until [npms-io/npms-analyzer#83](https://github.com/npms-io/npms-analyzer/issues/83) is fixed.
|
||||
* ???
|
||||
|
||||
## This is dumb! Nobody in open source does this!
|
||||
|
||||
46
eslint_rules/no-undefined-identifier.js
Normal file
46
eslint_rules/no-undefined-identifier.js
Normal file
@@ -0,0 +1,46 @@
|
||||
"use strict";
|
||||
|
||||
function argumentsIsUndefinedString(argumentsArray) {
|
||||
return (
|
||||
argumentsArray.length === 1 &&
|
||||
argumentsArray[0].type === "Literal" &&
|
||||
argumentsArray[0].value === "undefined"
|
||||
);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
meta: {
|
||||
schema: [],
|
||||
},
|
||||
create: function(context) {
|
||||
if (context.getFilename().indexOf("packages/babel-plugin-") === -1) {
|
||||
return {};
|
||||
}
|
||||
|
||||
return {
|
||||
CallExpression: function(node) {
|
||||
const callee = node.callee;
|
||||
|
||||
if (
|
||||
callee.type === "MemberExpression" &&
|
||||
argumentsIsUndefinedString(node.arguments)
|
||||
) {
|
||||
const object = callee.object,
|
||||
property = callee.property;
|
||||
|
||||
if (
|
||||
object.type === "Identifier" &&
|
||||
object.name === "t" &&
|
||||
property.type === "Identifier" &&
|
||||
property.name === "identifier"
|
||||
) {
|
||||
context.report(
|
||||
node,
|
||||
"Use path.scope.buildUndefinedNode() to create an undefined identifier directly."
|
||||
);
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
16
lerna.json
16
lerna.json
@@ -1,16 +1,16 @@
|
||||
{
|
||||
"lerna": "2.0.0-rc.4",
|
||||
"version": "7.0.0-alpha.11",
|
||||
"version": "7.0.0-beta.0",
|
||||
"changelog": {
|
||||
"repo": "babel/babel",
|
||||
"labels": {
|
||||
"tag: spec compliancy": ":eyeglasses: Spec Compliancy",
|
||||
"tag: breaking change": ":boom: Breaking Change",
|
||||
"tag: new feature": ":rocket: New Feature",
|
||||
"tag: bug fix": ":bug: Bug Fix",
|
||||
"tag: polish": ":nail_care: Polish",
|
||||
"tag: documentation": ":memo: Documentation",
|
||||
"tag: internal": ":house: Internal"
|
||||
"Tag: Spec Compliancy": ":eyeglasses: Spec Compliancy",
|
||||
"Tag: Breaking Change": ":boom: Breaking Change",
|
||||
"Tag: New Feature": ":rocket: New Feature",
|
||||
"Tag: Bug Fix": ":bug: Bug Fix",
|
||||
"Tag: Polish": ":nail_care: Polish",
|
||||
"Tag: Docs": ":memo: Documentation",
|
||||
"Tag: Internal": ":house: Internal"
|
||||
}
|
||||
},
|
||||
"cacheDir": ".changelog",
|
||||
|
||||
790
lib/types.js
790
lib/types.js
File diff suppressed because it is too large
Load Diff
62
package.json
62
package.json
@@ -3,59 +3,71 @@
|
||||
"private": true,
|
||||
"license": "MIT",
|
||||
"scripts": {
|
||||
"test": "make test",
|
||||
"build": "make build",
|
||||
"fix": "make fix",
|
||||
"lint": "make lint",
|
||||
"fix": "make fix"
|
||||
"precommit": "lint-staged",
|
||||
"test": "make test"
|
||||
},
|
||||
"devDependencies": {
|
||||
"async": "^1.5.0",
|
||||
"babel-cli": "7.0.0-alpha.9",
|
||||
"babel-core": "7.0.0-alpha.9",
|
||||
"babel-eslint": "^7.0.0",
|
||||
"babel-plugin-istanbul": "^2.0.1",
|
||||
"babel-preset-env": "2.0.0-alpha.7",
|
||||
"babel-preset-flow": "7.0.0-alpha.9",
|
||||
"babel-preset-stage-0": "7.0.0-alpha.9",
|
||||
"babel-register": "7.0.0-alpha.9",
|
||||
"babel-cli": "7.0.0-alpha.18",
|
||||
"babel-core": "7.0.0-alpha.18",
|
||||
"babel-eslint": "8.0.0-alpha.15",
|
||||
"babel-plugin-istanbul": "^4.1.4",
|
||||
"babel-preset-env": "2.0.0-alpha.18",
|
||||
"babel-preset-flow": "7.0.0-alpha.18",
|
||||
"babel-preset-stage-0": "7.0.0-alpha.18",
|
||||
"babel-register": "7.0.0-alpha.18",
|
||||
"babylon": "7.0.0-beta.22",
|
||||
"browserify": "^13.1.1",
|
||||
"bundle-collapser": "^1.2.1",
|
||||
"chai": "^3.5.0",
|
||||
"chalk": "1.1.1",
|
||||
"codecov": "^1.0.1",
|
||||
"chai": "^4.1.0",
|
||||
"chalk": "^2.0.0",
|
||||
"derequire": "^2.0.2",
|
||||
"eslint": "^3.9.0",
|
||||
"eslint-config-babel": "^6.0.0",
|
||||
"eslint": "^4.5.0",
|
||||
"eslint-config-babel": "^7.0.2",
|
||||
"eslint-plugin-flowtype": "^2.20.0",
|
||||
"flow-bin": "^0.41.0",
|
||||
"eslint-plugin-prettier": "^2.2.0",
|
||||
"flow-bin": "^0.53.1",
|
||||
"gulp": "^3.9.0",
|
||||
"gulp-babel": "babel/gulp-babel#b7-alpha",
|
||||
"gulp-babel": "^7.0.0",
|
||||
"gulp-newer": "^1.0.0",
|
||||
"gulp-plumber": "^1.0.1",
|
||||
"gulp-util": "^3.0.7",
|
||||
"gulp-watch": "^4.3.5",
|
||||
"lerna": "2.0.0-rc.4",
|
||||
"lerna-changelog": "^0.2.0",
|
||||
"husky": "^0.14.3",
|
||||
"lerna": "2.0.0",
|
||||
"lerna-changelog": "^0.5.0",
|
||||
"lint-staged": "^4.0.4",
|
||||
"lodash": "^4.2.0",
|
||||
"mocha": "^3.0.0",
|
||||
"nyc": "^10.0.0",
|
||||
"output-file-sync": "^1.1.1",
|
||||
"nyc": "^11.0.3",
|
||||
"output-file-sync": "^2.0.0",
|
||||
"prettier": "^1.6.1",
|
||||
"rimraf": "^2.4.3",
|
||||
"semver": "^5.0.0",
|
||||
"through2": "^2.0.0",
|
||||
"uglify-js": "^2.4.16"
|
||||
},
|
||||
"devEngines": {
|
||||
"node": ">= 4.x <= 7.x",
|
||||
"npm": "2.x || 3.x || 4.x"
|
||||
"engines": {
|
||||
"node": ">= 4.x <= 8.x",
|
||||
"npm": ">= 2.x <= 5.x",
|
||||
"yarn": ">=0.27.5 || >=1.0.0-20170811"
|
||||
},
|
||||
"nyc": {
|
||||
"all": true,
|
||||
"exclude": [
|
||||
"scripts/*.js",
|
||||
"packages/*/test/**"
|
||||
"packages/*/test/**",
|
||||
"packages/babel-standalone/**"
|
||||
],
|
||||
"sourceMap": false,
|
||||
"instrument": false
|
||||
},
|
||||
"lint-staged": {
|
||||
"*.js": [
|
||||
"eslint --format=codeframe --rulesdir='./eslint_rules'"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
6
packages/.eslintrc
Normal file
6
packages/.eslintrc
Normal file
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"rules": {
|
||||
"prettier/prettier": ["error", { "trailingComma": "all" }],
|
||||
"no-undefined-identifier": 2
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "babel-cli",
|
||||
"version": "7.0.0-alpha.11",
|
||||
"version": "7.0.0-beta.0",
|
||||
"description": "Babel command line.",
|
||||
"author": "Sebastian McKenzie <sebmck@gmail.com>",
|
||||
"homepage": "https://babeljs.io/",
|
||||
@@ -16,24 +16,24 @@
|
||||
"compiler"
|
||||
],
|
||||
"dependencies": {
|
||||
"babel-core": "7.0.0-alpha.11",
|
||||
"babel-polyfill": "7.0.0-alpha.9",
|
||||
"babel-register": "7.0.0-alpha.11",
|
||||
"babel-core": "7.0.0-beta.0",
|
||||
"babel-polyfill": "7.0.0-beta.0",
|
||||
"babel-register": "7.0.0-beta.0",
|
||||
"commander": "^2.8.1",
|
||||
"convert-source-map": "^1.1.0",
|
||||
"fs-readdir-recursive": "^1.0.0",
|
||||
"glob": "^7.0.0",
|
||||
"lodash": "^4.2.0",
|
||||
"output-file-sync": "^1.1.0",
|
||||
"output-file-sync": "^2.0.0",
|
||||
"slash": "^1.0.0",
|
||||
"source-map": "^0.5.0",
|
||||
"v8flags": "^2.0.10"
|
||||
"v8flags": "^3.0.0"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"chokidar": "^1.6.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"babel-helper-fixtures": "7.0.0-alpha.10"
|
||||
"babel-helper-fixtures": "7.0.0-beta.0"
|
||||
},
|
||||
"bin": {
|
||||
"babel-doctor": "./bin/babel-doctor.js",
|
||||
|
||||
@@ -24,9 +24,21 @@ function collect(value, previousValue): Array<string> {
|
||||
/* eslint-disable max-len */
|
||||
program.option("-e, --eval [script]", "Evaluate script");
|
||||
program.option("-p, --print [code]", "Evaluate script and print result");
|
||||
program.option("-o, --only [globs]", "A comma-separated list of glob patterns to compile", collect);
|
||||
program.option("-i, --ignore [globs]", "A comma-separated list of glob patterns to skip compiling", collect);
|
||||
program.option("-x, --extensions [extensions]", "List of extensions to hook into [.es6,.js,.es,.jsx,.mjs]", collect);
|
||||
program.option(
|
||||
"-o, --only [globs]",
|
||||
"A comma-separated list of glob patterns to compile",
|
||||
collect,
|
||||
);
|
||||
program.option(
|
||||
"-i, --ignore [globs]",
|
||||
"A comma-separated list of glob patterns to skip compiling",
|
||||
collect,
|
||||
);
|
||||
program.option(
|
||||
"-x, --extensions [extensions]",
|
||||
"List of extensions to hook into [.es6,.js,.es,.jsx,.mjs]",
|
||||
collect,
|
||||
);
|
||||
program.option("-w, --plugins [string]", "", collect);
|
||||
program.option("-b, --presets [string]", "", collect);
|
||||
/* eslint-enable max-len */
|
||||
@@ -55,23 +67,28 @@ const replPlugin = ({ types: t }) => ({
|
||||
|
||||
VariableDeclaration(path) {
|
||||
if (path.node.kind !== "var") {
|
||||
throw path.buildCodeFrameError("Only `var` variables are supported in the REPL");
|
||||
throw path.buildCodeFrameError(
|
||||
"Only `var` variables are supported in the REPL",
|
||||
);
|
||||
}
|
||||
},
|
||||
|
||||
Program(path) {
|
||||
if (path.get("body").some((child) => child.isExpressionStatement())) return;
|
||||
if (path.get("body").some(child => child.isExpressionStatement())) return;
|
||||
|
||||
// If the executed code doesn't evaluate to a value,
|
||||
// prevent implicit strict mode from printing 'use strict'.
|
||||
path.pushContainer("body", t.expressionStatement(t.identifier("undefined")));
|
||||
path.pushContainer(
|
||||
"body",
|
||||
t.expressionStatement(t.identifier("undefined")),
|
||||
);
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
//
|
||||
|
||||
const _eval = function (code, filename) {
|
||||
const _eval = function(code, filename) {
|
||||
code = code.trim();
|
||||
if (!code) return undefined;
|
||||
|
||||
@@ -113,7 +130,7 @@ if (program.eval || program.print) {
|
||||
|
||||
let i = 0;
|
||||
let ignoreNext = false;
|
||||
args.some(function (arg, i2) {
|
||||
args.some(function(arg, i2) {
|
||||
if (ignoreNext) {
|
||||
ignoreNext = false;
|
||||
return;
|
||||
@@ -133,7 +150,9 @@ if (program.eval || program.print) {
|
||||
|
||||
// make the filename absolute
|
||||
const filename = args[0];
|
||||
if (!path.isAbsolute(filename)) args[0] = path.join(process.cwd(), filename);
|
||||
if (!path.isAbsolute(filename)) {
|
||||
args[0] = path.join(process.cwd(), filename);
|
||||
}
|
||||
|
||||
// add back on node and concat the sliced args
|
||||
process.argv = ["node"].concat(args);
|
||||
|
||||
@@ -10,8 +10,16 @@ function collect(value, previousValue): Array<string> {
|
||||
return previousValue ? previousValue.concat(values) : values;
|
||||
}
|
||||
|
||||
commander.option("-l, --whitelist [whitelist]", "Whitelist of helpers to ONLY include", collect);
|
||||
commander.option("-t, --output-type [type]", "Type of output (global|umd|var)", "global");
|
||||
commander.option(
|
||||
"-l, --whitelist [whitelist]",
|
||||
"Whitelist of helpers to ONLY include",
|
||||
collect,
|
||||
);
|
||||
commander.option(
|
||||
"-t, --output-type [type]",
|
||||
"Type of output (global|umd|var)",
|
||||
"global",
|
||||
);
|
||||
|
||||
commander.usage("[options]");
|
||||
commander.parse(process.argv);
|
||||
|
||||
@@ -33,7 +33,7 @@ function getNormalizedV8Flag(arg) {
|
||||
return arg;
|
||||
}
|
||||
|
||||
getV8Flags(function (err, v8Flags) {
|
||||
getV8Flags(function(err, v8Flags) {
|
||||
babelArgs.forEach(function(arg) {
|
||||
const flag = arg.split("=")[0];
|
||||
|
||||
@@ -54,12 +54,19 @@ getV8Flags(function (err, v8Flags) {
|
||||
args.unshift("--expose-gc");
|
||||
break;
|
||||
|
||||
case "--expose-http2":
|
||||
args.unshift("--expose-http2");
|
||||
break;
|
||||
|
||||
case "--nolazy":
|
||||
args.unshift(flag);
|
||||
break;
|
||||
|
||||
default:
|
||||
if (v8Flags.indexOf(getNormalizedV8Flag(flag)) >= 0 || arg.indexOf("--trace") === 0) {
|
||||
if (
|
||||
v8Flags.indexOf(getNormalizedV8Flag(flag)) >= 0 ||
|
||||
arg.indexOf("--trace") === 0
|
||||
) {
|
||||
args.unshift(arg);
|
||||
} else {
|
||||
args.push(arg);
|
||||
@@ -80,9 +87,11 @@ getV8Flags(function (err, v8Flags) {
|
||||
if (err.code !== "MODULE_NOT_FOUND") throw err;
|
||||
|
||||
const child_process = require("child_process");
|
||||
const proc = child_process.spawn(process.argv[0], args, { stdio: "inherit" });
|
||||
proc.on("exit", function (code, signal) {
|
||||
process.on("exit", function () {
|
||||
const proc = child_process.spawn(process.argv[0], args, {
|
||||
stdio: "inherit",
|
||||
});
|
||||
proc.on("exit", function(code, signal) {
|
||||
process.on("exit", function() {
|
||||
if (signal) {
|
||||
process.kill(process.pid, signal);
|
||||
} else {
|
||||
@@ -90,5 +99,10 @@ getV8Flags(function (err, v8Flags) {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
process.on("SIGINT", () => {
|
||||
proc.kill("SIGINT");
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
@@ -6,19 +6,27 @@ import fs from "fs";
|
||||
|
||||
import * as util from "./util";
|
||||
|
||||
export default function (commander, filenames, opts) {
|
||||
function write(src, relative) {
|
||||
if (!util.isCompilableExtension(relative, commander.extensions)) return false;
|
||||
export default function(commander, filenames, opts) {
|
||||
function write(src, relative, base) {
|
||||
if (!util.isCompilableExtension(relative, commander.extensions)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// remove extension and then append back on .js
|
||||
relative = relative.replace(/\.(\w*?)$/, "") + ".js";
|
||||
relative = util.adjustRelative(relative, commander.keepFileExtension);
|
||||
|
||||
const dest = path.join(commander.outDir, relative);
|
||||
const dest = getDest(commander, relative, base);
|
||||
|
||||
const data = util.compile(src, defaults({
|
||||
sourceFileName: slash(path.relative(dest + "/..", src)),
|
||||
sourceMapTarget: path.basename(relative),
|
||||
}, opts));
|
||||
const data = util.compile(
|
||||
src,
|
||||
defaults(
|
||||
{
|
||||
sourceFileName: slash(path.relative(dest + "/..", src)),
|
||||
sourceMapTarget: path.basename(relative),
|
||||
},
|
||||
opts,
|
||||
),
|
||||
);
|
||||
|
||||
if (!data) return false;
|
||||
|
||||
@@ -37,11 +45,16 @@ export default function (commander, filenames, opts) {
|
||||
return true;
|
||||
}
|
||||
|
||||
function handleFile(src, filename) {
|
||||
const didWrite = write(src, filename);
|
||||
function getDest(commander, filename, base) {
|
||||
if (commander.relative) return path.join(base, commander.outDir, filename);
|
||||
return path.join(commander.outDir, filename);
|
||||
}
|
||||
|
||||
function handleFile(src, filename, base) {
|
||||
const didWrite = write(src, filename, base);
|
||||
|
||||
if (!didWrite && commander.copyFiles) {
|
||||
const dest = path.join(commander.outDir, filename);
|
||||
const dest = getDest(commander, filename, base);
|
||||
outputFileSync(dest, fs.readFileSync(src));
|
||||
util.chmod(src, dest);
|
||||
}
|
||||
@@ -55,12 +68,15 @@ export default function (commander, filenames, opts) {
|
||||
if (stat.isDirectory(filename)) {
|
||||
const dirname = filename;
|
||||
|
||||
util.readdir(dirname).forEach(function (filename) {
|
||||
if (commander.deleteDirOnStart) {
|
||||
util.deleteDir(commander.outDir);
|
||||
}
|
||||
util.readdir(dirname).forEach(function(filename) {
|
||||
const src = path.join(dirname, filename);
|
||||
handleFile(src, filename);
|
||||
handleFile(src, filename, dirname);
|
||||
});
|
||||
} else {
|
||||
write(filename, filename);
|
||||
write(filename, path.basename(filename), path.dirname(filename));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,7 +87,7 @@ export default function (commander, filenames, opts) {
|
||||
if (commander.watch) {
|
||||
const chokidar = util.requireChokidar();
|
||||
|
||||
filenames.forEach(function (dirname) {
|
||||
filenames.forEach(function(dirname) {
|
||||
const watcher = chokidar.watch(dirname, {
|
||||
persistent: true,
|
||||
ignoreInitial: true,
|
||||
@@ -81,8 +97,8 @@ export default function (commander, filenames, opts) {
|
||||
},
|
||||
});
|
||||
|
||||
["add", "change"].forEach(function (type) {
|
||||
watcher.on(type, function (filename) {
|
||||
["add", "change"].forEach(function(type) {
|
||||
watcher.on(type, function(filename) {
|
||||
const relative = path.relative(dirname, filename) || filename;
|
||||
try {
|
||||
handleFile(filename, relative);
|
||||
|
||||
@@ -7,14 +7,14 @@ import fs from "fs";
|
||||
|
||||
import * as util from "./util";
|
||||
|
||||
export default function (commander, filenames, opts) {
|
||||
export default function(commander, filenames, opts) {
|
||||
if (commander.sourceMaps === "inline") {
|
||||
opts.sourceMaps = true;
|
||||
}
|
||||
|
||||
let results = [];
|
||||
|
||||
const buildResult = function () {
|
||||
const buildResult = function() {
|
||||
const map = new sourceMap.SourceMapGenerator({
|
||||
file: path.basename(commander.outFile || "") || "stdout",
|
||||
sourceRoot: opts.sourceRoot,
|
||||
@@ -23,14 +23,14 @@ export default function (commander, filenames, opts) {
|
||||
let code = "";
|
||||
let offset = 0;
|
||||
|
||||
results.forEach(function (result) {
|
||||
results.forEach(function(result) {
|
||||
code += result.code + "\n";
|
||||
|
||||
if (result.map) {
|
||||
const consumer = new sourceMap.SourceMapConsumer(result.map);
|
||||
const sources = new Set();
|
||||
|
||||
consumer.eachMapping(function (mapping) {
|
||||
consumer.eachMapping(function(mapping) {
|
||||
if (mapping.source != null) sources.add(mapping.source);
|
||||
|
||||
map.addMapping({
|
||||
@@ -39,14 +39,17 @@ export default function (commander, filenames, opts) {
|
||||
column: mapping.generatedColumn,
|
||||
},
|
||||
source: mapping.source,
|
||||
original: mapping.source == null ? null : {
|
||||
line: mapping.originalLine,
|
||||
column: mapping.originalColumn,
|
||||
},
|
||||
original:
|
||||
mapping.source == null
|
||||
? null
|
||||
: {
|
||||
line: mapping.originalLine,
|
||||
column: mapping.originalColumn,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
sources.forEach((source) => {
|
||||
sources.forEach(source => {
|
||||
const content = consumer.sourceContentFor(source, true);
|
||||
if (content !== null) {
|
||||
map.setSourceContent(source, content);
|
||||
@@ -59,7 +62,10 @@ export default function (commander, filenames, opts) {
|
||||
|
||||
// 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)) {
|
||||
if (
|
||||
commander.sourceMaps === "inline" ||
|
||||
(!commander.outFile && commander.sourceMaps)
|
||||
) {
|
||||
code += "\n" + convertSourceMap.fromObject(map).toComment();
|
||||
}
|
||||
|
||||
@@ -69,7 +75,7 @@ export default function (commander, filenames, opts) {
|
||||
};
|
||||
};
|
||||
|
||||
const output = function () {
|
||||
const output = function() {
|
||||
const result = buildResult();
|
||||
|
||||
if (commander.outFile) {
|
||||
@@ -86,36 +92,45 @@ export default function (commander, filenames, opts) {
|
||||
}
|
||||
};
|
||||
|
||||
const stdin = function () {
|
||||
const stdin = function() {
|
||||
let code = "";
|
||||
|
||||
process.stdin.setEncoding("utf8");
|
||||
|
||||
process.stdin.on("readable", function () {
|
||||
process.stdin.on("readable", function() {
|
||||
const chunk = process.stdin.read();
|
||||
if (chunk !== null) code += chunk;
|
||||
});
|
||||
|
||||
process.stdin.on("end", function () {
|
||||
results.push(util.transform(commander.filename, code, defaults({
|
||||
sourceFileName: "stdin",
|
||||
}, opts)));
|
||||
process.stdin.on("end", function() {
|
||||
results.push(
|
||||
util.transform(
|
||||
commander.filename,
|
||||
code,
|
||||
defaults(
|
||||
{
|
||||
sourceFileName: "stdin",
|
||||
},
|
||||
opts,
|
||||
),
|
||||
),
|
||||
);
|
||||
output();
|
||||
});
|
||||
};
|
||||
|
||||
const walk = function () {
|
||||
const walk = function() {
|
||||
const _filenames = [];
|
||||
results = [];
|
||||
|
||||
filenames.forEach(function (filename) {
|
||||
filenames.forEach(function(filename) {
|
||||
if (!fs.existsSync(filename)) return;
|
||||
|
||||
const stat = fs.statSync(filename);
|
||||
if (stat.isDirectory()) {
|
||||
const dirname = filename;
|
||||
|
||||
util.readdirFilter(filename).forEach(function (filename) {
|
||||
util.readdirFilter(filename).forEach(function(filename) {
|
||||
_filenames.push(path.join(dirname, filename));
|
||||
});
|
||||
} else {
|
||||
@@ -123,16 +138,25 @@ export default function (commander, filenames, opts) {
|
||||
}
|
||||
});
|
||||
|
||||
_filenames.forEach(function (filename) {
|
||||
_filenames.forEach(function(filename) {
|
||||
let sourceFilename = filename;
|
||||
if (commander.outFile) {
|
||||
sourceFilename = path.relative(path.dirname(commander.outFile), sourceFilename);
|
||||
sourceFilename = path.relative(
|
||||
path.dirname(commander.outFile),
|
||||
sourceFilename,
|
||||
);
|
||||
}
|
||||
sourceFilename = slash(sourceFilename);
|
||||
|
||||
const data = util.compile(filename, defaults({
|
||||
sourceFileName: sourceFilename,
|
||||
}, opts));
|
||||
const data = util.compile(
|
||||
filename,
|
||||
defaults(
|
||||
{
|
||||
sourceFileName: sourceFilename,
|
||||
},
|
||||
opts,
|
||||
),
|
||||
);
|
||||
|
||||
if (!data) return;
|
||||
|
||||
@@ -142,33 +166,36 @@ export default function (commander, filenames, opts) {
|
||||
output();
|
||||
};
|
||||
|
||||
const files = function () {
|
||||
|
||||
const files = function() {
|
||||
if (!commander.skipInitialBuild) {
|
||||
walk();
|
||||
}
|
||||
|
||||
if (commander.watch) {
|
||||
const chokidar = util.requireChokidar();
|
||||
chokidar.watch(filenames, {
|
||||
persistent: true,
|
||||
ignoreInitial: true,
|
||||
awaitWriteFinish: {
|
||||
stabilityThreshold: 50,
|
||||
pollInterval: 10,
|
||||
},
|
||||
}).on("all", function (type, filename) {
|
||||
if (!util.isCompilableExtension(filename, commander.extensions)) return;
|
||||
|
||||
if (type === "add" || type === "change") {
|
||||
util.log(type + " " + filename);
|
||||
try {
|
||||
walk();
|
||||
} catch (err) {
|
||||
console.error(err.stack);
|
||||
chokidar
|
||||
.watch(filenames, {
|
||||
persistent: true,
|
||||
ignoreInitial: true,
|
||||
awaitWriteFinish: {
|
||||
stabilityThreshold: 50,
|
||||
pollInterval: 10,
|
||||
},
|
||||
})
|
||||
.on("all", function(type, filename) {
|
||||
if (!util.isCompilableExtension(filename, commander.extensions)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (type === "add" || type === "change") {
|
||||
util.log(type + " " + filename);
|
||||
try {
|
||||
walk();
|
||||
} catch (err) {
|
||||
console.error(err.stack);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -34,46 +34,131 @@ function collect(value, previousValue): Array<string> {
|
||||
|
||||
/* eslint-disable max-len */
|
||||
// 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(
|
||||
"-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");
|
||||
|
||||
// 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);
|
||||
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)");
|
||||
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(
|
||||
"--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");
|
||||
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");
|
||||
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(
|
||||
"--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");
|
||||
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(
|
||||
"-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("-D, --copy-files", "When compiling a directory copy over non-compilable files");
|
||||
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("-q, --quiet", "Don't log anything");
|
||||
commander.option(
|
||||
"--delete-dir-on-start",
|
||||
"Delete's the out directory before compilation",
|
||||
);
|
||||
/* eslint-enable max-len */
|
||||
|
||||
commander.version(pkg.version + " (babel-core " + version + ")");
|
||||
@@ -84,7 +169,7 @@ commander.parse(process.argv);
|
||||
|
||||
const errors = [];
|
||||
|
||||
let filenames = commander.args.reduce(function (globbed, input) {
|
||||
let filenames = commander.args.reduce(function(globbed, input) {
|
||||
let files = glob.sync(input);
|
||||
if (!files.length) files = [input];
|
||||
return globbed.concat(files);
|
||||
@@ -92,7 +177,7 @@ let filenames = commander.args.reduce(function (globbed, input) {
|
||||
|
||||
filenames = uniq(filenames);
|
||||
|
||||
filenames.forEach(function (filename) {
|
||||
filenames.forEach(function(filename) {
|
||||
if (!fs.existsSync(filename)) {
|
||||
errors.push(filename + " doesn't exist");
|
||||
}
|
||||
@@ -106,6 +191,10 @@ 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");
|
||||
@@ -119,6 +208,9 @@ if (commander.watch) {
|
||||
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 (errors.length) {
|
||||
console.error(errors.join(". "));
|
||||
@@ -128,6 +220,10 @@ if (errors.length) {
|
||||
//
|
||||
|
||||
const opts = commander.opts();
|
||||
//the configFile CLI option maps to the extends option in the node API
|
||||
if (opts.configFile) {
|
||||
opts.extends = opts.configFile;
|
||||
}
|
||||
|
||||
// Delete options that are specific to babel-cli and shouldn't be passed to babel-core.
|
||||
delete opts.version;
|
||||
@@ -138,6 +234,9 @@ delete opts.outFile;
|
||||
delete opts.outDir;
|
||||
delete opts.copyFiles;
|
||||
delete opts.quiet;
|
||||
delete opts.configFile;
|
||||
delete opts.deleteDirOnStart;
|
||||
delete opts.keepFileExtension;
|
||||
|
||||
// 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.
|
||||
|
||||
@@ -10,8 +10,8 @@ export function chmod(src, dest) {
|
||||
}
|
||||
|
||||
export function readdirFilter(filename) {
|
||||
return readdir(filename).filter(function (filename) {
|
||||
return babel.util.isCompilableExtension(filename);
|
||||
return readdir(filename).filter(function(filename) {
|
||||
return isCompilableExtension(filename);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -20,7 +20,10 @@ export { readdir };
|
||||
/**
|
||||
* Test if a filename ends with a compilable extension.
|
||||
*/
|
||||
export function isCompilableExtension(filename: string, altExts?: Array<string>): boolean {
|
||||
export function isCompilableExtension(
|
||||
filename: string,
|
||||
altExts?: Array<string>,
|
||||
): boolean {
|
||||
const exts = altExts || babel.DEFAULT_EXTENSIONS;
|
||||
const ext = path.extname(filename);
|
||||
return includes(exts, ext);
|
||||
@@ -55,6 +58,22 @@ export function compile(filename, opts) {
|
||||
}
|
||||
}
|
||||
|
||||
export function deleteDir(path) {
|
||||
if (fs.existsSync(path)) {
|
||||
fs.readdirSync(path).forEach(function(file) {
|
||||
const curPath = path + "/" + file;
|
||||
if (fs.lstatSync(curPath).isDirectory()) {
|
||||
// recurse
|
||||
deleteDir(curPath);
|
||||
} else {
|
||||
// delete file
|
||||
fs.unlinkSync(curPath);
|
||||
}
|
||||
});
|
||||
fs.rmdirSync(path);
|
||||
}
|
||||
}
|
||||
|
||||
function toErrorStack(err) {
|
||||
if (err._babel && err instanceof SyntaxError) {
|
||||
return `${err.name}: ${err.message}\n${err.codeFrame}`;
|
||||
@@ -63,7 +82,7 @@ function toErrorStack(err) {
|
||||
}
|
||||
}
|
||||
|
||||
process.on("uncaughtException", function (err) {
|
||||
process.on("uncaughtException", function(err) {
|
||||
console.error(toErrorStack(err));
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -74,8 +93,15 @@ export function requireChokidar() {
|
||||
} catch (err) {
|
||||
console.error(
|
||||
"The optional dependency chokidar failed to install and is required for " +
|
||||
"--watch. Chokidar is likely not supported on your platform."
|
||||
"--watch. Chokidar is likely not supported on your platform.",
|
||||
);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
export function adjustRelative(relative, keepFileExtension) {
|
||||
if (keepFileExtension) {
|
||||
return relative;
|
||||
}
|
||||
return relative.replace(/\.(\w*?)$/, "") + ".js";
|
||||
}
|
||||
|
||||
3
packages/babel-cli/test/.othername_babelrc
Normal file
3
packages/babel-cli/test/.othername_babelrc
Normal file
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"comments": false
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
{
|
||||
"args": ["--expose-debug-as=customDebug", "--eval", "console.log(customDebug.Debug.DebugEvent.Break)"],
|
||||
"stdout": "1"
|
||||
"args": ["--expose-gc-as=garbageCollector", "--eval", "console.log(typeof global.garbageCollector)"],
|
||||
"stdout": "function"
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
{
|
||||
"args": ["--expose_debug_as=customDebug", "--eval", "console.log(customDebug.Debug.DebugEvent.Break)"],
|
||||
"stdout": "1"
|
||||
"args": ["--expose_gc_as=garbageCollector", "--eval", "console.log(typeof global.garbageCollector)"],
|
||||
"stdout": "function"
|
||||
}
|
||||
|
||||
3
packages/babel-cli/test/fixtures/babel/--config-file babelrc nocomment/options.json
vendored
Normal file
3
packages/babel-cli/test/fixtures/babel/--config-file babelrc nocomment/options.json
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"args": ["--config-file", "../.othername_babelrc"]
|
||||
}
|
||||
7
packages/babel-cli/test/fixtures/babel/--config-file babelrc nocomment/stdin.txt
vendored
Normal file
7
packages/babel-cli/test/fixtures/babel/--config-file babelrc nocomment/stdin.txt
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
/*
|
||||
Test comment
|
||||
*/
|
||||
|
||||
arr.map(x => x * MULTIPLIER);
|
||||
|
||||
// END OF FILE
|
||||
5
packages/babel-cli/test/fixtures/babel/--config-file babelrc nocomment/stdout.txt
vendored
Normal file
5
packages/babel-cli/test/fixtures/babel/--config-file babelrc nocomment/stdout.txt
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
"use strict";
|
||||
|
||||
arr.map(function (x) {
|
||||
return x * MULTIPLIER;
|
||||
});
|
||||
1
packages/babel-cli/test/fixtures/babel/dir --out-dir --copy-files/in-files/src/bar.json
vendored
Normal file
1
packages/babel-cli/test/fixtures/babel/dir --out-dir --copy-files/in-files/src/bar.json
vendored
Normal file
@@ -0,0 +1 @@
|
||||
{}
|
||||
1
packages/babel-cli/test/fixtures/babel/dir --out-dir --copy-files/in-files/src/foo.js
vendored
Normal file
1
packages/babel-cli/test/fixtures/babel/dir --out-dir --copy-files/in-files/src/foo.js
vendored
Normal file
@@ -0,0 +1 @@
|
||||
arr.map(x => x * MULTIPLIER);
|
||||
3
packages/babel-cli/test/fixtures/babel/dir --out-dir --copy-files/options.json
vendored
Normal file
3
packages/babel-cli/test/fixtures/babel/dir --out-dir --copy-files/options.json
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"args": ["src", "--out-dir", "lib", "--copy-files"]
|
||||
}
|
||||
1
packages/babel-cli/test/fixtures/babel/dir --out-dir --copy-files/out-files/lib/bar.json
vendored
Normal file
1
packages/babel-cli/test/fixtures/babel/dir --out-dir --copy-files/out-files/lib/bar.json
vendored
Normal file
@@ -0,0 +1 @@
|
||||
{}
|
||||
5
packages/babel-cli/test/fixtures/babel/dir --out-dir --copy-files/out-files/lib/foo.js
vendored
Normal file
5
packages/babel-cli/test/fixtures/babel/dir --out-dir --copy-files/out-files/lib/foo.js
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
"use strict";
|
||||
|
||||
arr.map(function (x) {
|
||||
return x * MULTIPLIER;
|
||||
});
|
||||
1
packages/babel-cli/test/fixtures/babel/dir --out-dir --copy-files/stdout.txt
vendored
Normal file
1
packages/babel-cli/test/fixtures/babel/dir --out-dir --copy-files/stdout.txt
vendored
Normal file
@@ -0,0 +1 @@
|
||||
src/foo.js -> lib/foo.js
|
||||
@@ -0,0 +1 @@
|
||||
arr.map(x => x / DIVIDER);
|
||||
@@ -0,0 +1 @@
|
||||
arr.map(x => x * MULTIPLIER);
|
||||
3
packages/babel-cli/test/fixtures/babel/dir --out-dir --keep-file-extension/options.json
vendored
Normal file
3
packages/babel-cli/test/fixtures/babel/dir --out-dir --keep-file-extension/options.json
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"args": ["src", "--out-dir", "lib", "--keep-file-extension"]
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
"use strict";
|
||||
|
||||
arr.map(function (x) {
|
||||
return x / DIVIDER;
|
||||
});
|
||||
@@ -0,0 +1,5 @@
|
||||
"use strict";
|
||||
|
||||
arr.map(function (x) {
|
||||
return x * MULTIPLIER;
|
||||
});
|
||||
2
packages/babel-cli/test/fixtures/babel/dir --out-dir --keep-file-extension/stdout.txt
vendored
Normal file
2
packages/babel-cli/test/fixtures/babel/dir --out-dir --keep-file-extension/stdout.txt
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
src/bar.mjs -> lib/bar.mjs
|
||||
src/foo.js -> lib/foo.js
|
||||
@@ -0,0 +1,3 @@
|
||||
class Test1 {
|
||||
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
arr.map(x => x * MULTIPLIER);
|
||||
@@ -0,0 +1,3 @@
|
||||
class Test2 {
|
||||
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
arr.map(x => x / DIVIDER);
|
||||
3
packages/babel-cli/test/fixtures/babel/dir --out-dir --relative/options.json
vendored
Normal file
3
packages/babel-cli/test/fixtures/babel/dir --out-dir --relative/options.json
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"args": ["**/src", "--out-dir", "../lib", "--relative"]
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
"use strict";
|
||||
|
||||
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
|
||||
|
||||
var Test1 = function Test1() {
|
||||
_classCallCheck(this, Test1);
|
||||
};
|
||||
@@ -0,0 +1,5 @@
|
||||
"use strict";
|
||||
|
||||
arr.map(function (x) {
|
||||
return x * MULTIPLIER;
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
"use strict";
|
||||
|
||||
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
|
||||
|
||||
var Test2 = function Test2() {
|
||||
_classCallCheck(this, Test2);
|
||||
};
|
||||
@@ -0,0 +1,5 @@
|
||||
"use strict";
|
||||
|
||||
arr.map(function (x) {
|
||||
return x / DIVIDER;
|
||||
});
|
||||
4
packages/babel-cli/test/fixtures/babel/dir --out-dir --relative/stdout.txt
vendored
Normal file
4
packages/babel-cli/test/fixtures/babel/dir --out-dir --relative/stdout.txt
vendored
Normal file
@@ -0,0 +1,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
|
||||
4
packages/babel-cli/test/fixtures/babel/error --out-dir --out-file/options.json
vendored
Normal file
4
packages/babel-cli/test/fixtures/babel/error --out-dir --out-file/options.json
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"args": ["--out-dir", "lib"],
|
||||
"stderrContains": true
|
||||
}
|
||||
1
packages/babel-cli/test/fixtures/babel/error --out-dir --out-file/stderr.txt
vendored
Normal file
1
packages/babel-cli/test/fixtures/babel/error --out-dir --out-file/stderr.txt
vendored
Normal file
@@ -0,0 +1 @@
|
||||
filenames required for --out-dir
|
||||
4
packages/babel-cli/test/fixtures/babel/error --out-dir/options.json
vendored
Normal file
4
packages/babel-cli/test/fixtures/babel/error --out-dir/options.json
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"args": ["--out-dir", "lib", "--out-file", "foo.js"],
|
||||
"stderrContains": true
|
||||
}
|
||||
1
packages/babel-cli/test/fixtures/babel/error --out-dir/stderr.txt
vendored
Normal file
1
packages/babel-cli/test/fixtures/babel/error --out-dir/stderr.txt
vendored
Normal file
@@ -0,0 +1 @@
|
||||
cannot have --out-file and --out-dir
|
||||
4
packages/babel-cli/test/fixtures/babel/error --relative/options.json
vendored
Normal file
4
packages/babel-cli/test/fixtures/babel/error --relative/options.json
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"args": ["--relative"],
|
||||
"stderrContains": true
|
||||
}
|
||||
1
packages/babel-cli/test/fixtures/babel/error --relative/stderr.txt
vendored
Normal file
1
packages/babel-cli/test/fixtures/babel/error --relative/stderr.txt
vendored
Normal file
@@ -0,0 +1 @@
|
||||
output directory required for --relative
|
||||
4
packages/babel-cli/test/fixtures/babel/error --skip-initial-build/options.json
vendored
Normal file
4
packages/babel-cli/test/fixtures/babel/error --skip-initial-build/options.json
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"args": ["--skip-initial-build"],
|
||||
"stderrContains": true
|
||||
}
|
||||
1
packages/babel-cli/test/fixtures/babel/error --skip-initial-build/stderr.txt
vendored
Normal file
1
packages/babel-cli/test/fixtures/babel/error --skip-initial-build/stderr.txt
vendored
Normal file
@@ -0,0 +1 @@
|
||||
--skip-initial-build requires --watch
|
||||
4
packages/babel-cli/test/fixtures/babel/error --watch no filename/options.json
vendored
Normal file
4
packages/babel-cli/test/fixtures/babel/error --watch no filename/options.json
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"args": ["--watch"],
|
||||
"stderrContains": true
|
||||
}
|
||||
1
packages/babel-cli/test/fixtures/babel/error --watch no filename/stderr.txt
vendored
Normal file
1
packages/babel-cli/test/fixtures/babel/error --watch no filename/stderr.txt
vendored
Normal file
@@ -0,0 +1 @@
|
||||
--watch requires filenames
|
||||
4
packages/babel-cli/test/fixtures/babel/error --watch/options.json
vendored
Normal file
4
packages/babel-cli/test/fixtures/babel/error --watch/options.json
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"args": ["--watch"],
|
||||
"stderrContains": true
|
||||
}
|
||||
1
packages/babel-cli/test/fixtures/babel/error --watch/stderr.txt
vendored
Normal file
1
packages/babel-cli/test/fixtures/babel/error --watch/stderr.txt
vendored
Normal file
@@ -0,0 +1 @@
|
||||
--watch requires --out-file or --out-dir
|
||||
4
packages/babel-cli/test/fixtures/babel/error wrong filename/options.json
vendored
Normal file
4
packages/babel-cli/test/fixtures/babel/error wrong filename/options.json
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"args": ["foo.json"],
|
||||
"stderrContains": true
|
||||
}
|
||||
1
packages/babel-cli/test/fixtures/babel/error wrong filename/stderr.txt
vendored
Normal file
1
packages/babel-cli/test/fixtures/babel/error wrong filename/stderr.txt
vendored
Normal file
@@ -0,0 +1 @@
|
||||
foo.json doesn't exist
|
||||
1
packages/babel-cli/test/fixtures/babel/filename --out-dir --relative/in-files/src/foo.js
vendored
Normal file
1
packages/babel-cli/test/fixtures/babel/filename --out-dir --relative/in-files/src/foo.js
vendored
Normal file
@@ -0,0 +1 @@
|
||||
arr.map(x => x * MULTIPLIER);
|
||||
3
packages/babel-cli/test/fixtures/babel/filename --out-dir --relative/options.json
vendored
Normal file
3
packages/babel-cli/test/fixtures/babel/filename --out-dir --relative/options.json
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"args": ["src/foo.js", "--out-dir", "../lib", "--relative"]
|
||||
}
|
||||
5
packages/babel-cli/test/fixtures/babel/filename --out-dir --relative/out-files/lib/foo.js
vendored
Normal file
5
packages/babel-cli/test/fixtures/babel/filename --out-dir --relative/out-files/lib/foo.js
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
"use strict";
|
||||
|
||||
arr.map(function (x) {
|
||||
return x * MULTIPLIER;
|
||||
});
|
||||
1
packages/babel-cli/test/fixtures/babel/filename --out-dir --relative/stdout.txt
vendored
Normal file
1
packages/babel-cli/test/fixtures/babel/filename --out-dir --relative/stdout.txt
vendored
Normal file
@@ -0,0 +1 @@
|
||||
src/foo.js -> lib/foo.js
|
||||
1
packages/babel-cli/test/fixtures/babel/filename --out-dir/in-files/src/foo.js
vendored
Normal file
1
packages/babel-cli/test/fixtures/babel/filename --out-dir/in-files/src/foo.js
vendored
Normal file
@@ -0,0 +1 @@
|
||||
arr.map(x => x * MULTIPLIER);
|
||||
3
packages/babel-cli/test/fixtures/babel/filename --out-dir/options.json
vendored
Normal file
3
packages/babel-cli/test/fixtures/babel/filename --out-dir/options.json
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"args": ["src/foo.js", "--out-dir", "lib"]
|
||||
}
|
||||
5
packages/babel-cli/test/fixtures/babel/filename --out-dir/out-files/lib/foo.js
vendored
Normal file
5
packages/babel-cli/test/fixtures/babel/filename --out-dir/out-files/lib/foo.js
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
"use strict";
|
||||
|
||||
arr.map(function (x) {
|
||||
return x * MULTIPLIER;
|
||||
});
|
||||
1
packages/babel-cli/test/fixtures/babel/filename --out-dir/stdout.txt
vendored
Normal file
1
packages/babel-cli/test/fixtures/babel/filename --out-dir/stdout.txt
vendored
Normal file
@@ -0,0 +1 @@
|
||||
src/foo.js -> lib/foo.js
|
||||
@@ -3,9 +3,6 @@
|
||||
/*
|
||||
Test comment
|
||||
*/
|
||||
|
||||
arr.map(function (x) {
|
||||
return x * MULTIPLIER;
|
||||
});
|
||||
|
||||
// END OF FILE
|
||||
}); // END OF FILE
|
||||
|
||||
@@ -27,34 +27,39 @@ const pluginLocs = [
|
||||
path.join(__dirname, "/../../babel-plugin-transform-es2015-modules-commonjs"),
|
||||
].join(",");
|
||||
|
||||
const readDir = function (loc, filter) {
|
||||
const readDir = function(loc, filter) {
|
||||
const files = {};
|
||||
if (fs.existsSync(loc)) {
|
||||
readdir(loc, filter).forEach(function (filename) {
|
||||
readdir(loc, filter).forEach(function(filename) {
|
||||
files[filename] = helper.readFile(path.join(loc, filename));
|
||||
});
|
||||
}
|
||||
return files;
|
||||
};
|
||||
|
||||
const saveInFiles = function (files) {
|
||||
const saveInFiles = function(files) {
|
||||
// Place an empty .babelrc in each test so tests won't unexpectedly get to repo-level config.
|
||||
outputFileSync(".babelrc", "{}");
|
||||
|
||||
Object.keys(files).forEach(function (filename) {
|
||||
Object.keys(files).forEach(function(filename) {
|
||||
const content = files[filename];
|
||||
outputFileSync(filename, content);
|
||||
});
|
||||
};
|
||||
|
||||
const assertTest = function (stdout, stderr, opts) {
|
||||
const assertTest = function(stdout, stderr, opts) {
|
||||
const expectStderr = opts.stderr.trim();
|
||||
stderr = stderr.trim();
|
||||
|
||||
if (opts.stderr) {
|
||||
if (opts.stderrContains) {
|
||||
assert.ok(includes(stderr, expectStderr), "stderr " + JSON.stringify(stderr) +
|
||||
" didn't contain " + JSON.stringify(expectStderr));
|
||||
assert.ok(
|
||||
includes(stderr, expectStderr),
|
||||
"stderr " +
|
||||
JSON.stringify(stderr) +
|
||||
" didn't contain " +
|
||||
JSON.stringify(expectStderr),
|
||||
);
|
||||
} else {
|
||||
chai.expect(stderr).to.equal(expectStderr, "stderr didn't match");
|
||||
}
|
||||
@@ -68,8 +73,13 @@ const assertTest = function (stdout, stderr, opts) {
|
||||
|
||||
if (opts.stdout) {
|
||||
if (opts.stdoutContains) {
|
||||
assert.ok(includes(stdout, expectStdout), "stdout " + JSON.stringify(stdout) +
|
||||
" didn't contain " + JSON.stringify(expectStdout));
|
||||
assert.ok(
|
||||
includes(stdout, expectStdout),
|
||||
"stdout " +
|
||||
JSON.stringify(stdout) +
|
||||
" didn't contain " +
|
||||
JSON.stringify(expectStdout),
|
||||
);
|
||||
} else {
|
||||
chai.expect(stdout).to.equal(expectStdout, "stdout didn't match");
|
||||
}
|
||||
@@ -80,30 +90,34 @@ const assertTest = function (stdout, stderr, opts) {
|
||||
if (opts.outFiles) {
|
||||
const actualFiles = readDir(path.join(tmpLoc));
|
||||
|
||||
Object.keys(actualFiles).forEach(function (filename) {
|
||||
Object.keys(actualFiles).forEach(function(filename) {
|
||||
if (!opts.inFiles.hasOwnProperty(filename)) {
|
||||
const expect = opts.outFiles[filename];
|
||||
const actual = actualFiles[filename];
|
||||
|
||||
chai.expect(expect, "Output is missing: " + filename).to.not.be.undefined;
|
||||
chai.expect(expect, "Output is missing: " + filename).to.not.be
|
||||
.undefined;
|
||||
|
||||
if (expect) {
|
||||
chai.expect(actual).to.equal(expect, "Compiled output does not match: " + filename);
|
||||
chai
|
||||
.expect(actual)
|
||||
.to.equal(expect, "Compiled output does not match: " + filename);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Object.keys(opts.outFiles).forEach(function(filename) {
|
||||
chai.expect(actualFiles, "Extraneous file in output: " + filename)
|
||||
chai
|
||||
.expect(actualFiles, "Extraneous file in output: " + filename)
|
||||
.to.contain.key(filename);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const buildTest = function (binName, testName, opts) {
|
||||
const buildTest = function(binName, testName, opts) {
|
||||
const binLoc = path.join(__dirname, "../lib", binName);
|
||||
|
||||
return function (callback) {
|
||||
return function(callback) {
|
||||
clear();
|
||||
saveInFiles(opts.inFiles);
|
||||
|
||||
@@ -124,15 +138,15 @@ const buildTest = function (binName, testName, opts) {
|
||||
let stderr = "";
|
||||
let stdout = "";
|
||||
|
||||
spawn.stderr.on("data", function (chunk) {
|
||||
spawn.stderr.on("data", function(chunk) {
|
||||
stderr += chunk;
|
||||
});
|
||||
|
||||
spawn.stdout.on("data", function (chunk) {
|
||||
spawn.stdout.on("data", function(chunk) {
|
||||
stdout += chunk;
|
||||
});
|
||||
|
||||
spawn.on("close", function () {
|
||||
spawn.on("close", function() {
|
||||
let err;
|
||||
|
||||
try {
|
||||
@@ -142,7 +156,8 @@ const buildTest = function (binName, testName, opts) {
|
||||
}
|
||||
|
||||
if (err) {
|
||||
err.message = args.map((arg) => `"${ arg }"`).join(" ") + ": " + err.message;
|
||||
err.message =
|
||||
args.map(arg => `"${arg}"`).join(" ") + ": " + err.message;
|
||||
}
|
||||
|
||||
callback(err);
|
||||
@@ -155,19 +170,19 @@ const buildTest = function (binName, testName, opts) {
|
||||
};
|
||||
};
|
||||
|
||||
const clear = function () {
|
||||
const clear = function() {
|
||||
process.chdir(__dirname);
|
||||
if (fs.existsSync(tmpLoc)) rimraf.sync(tmpLoc);
|
||||
fs.mkdirSync(tmpLoc);
|
||||
process.chdir(tmpLoc);
|
||||
};
|
||||
|
||||
fs.readdirSync(fixtureLoc).forEach(function (binName) {
|
||||
fs.readdirSync(fixtureLoc).forEach(function(binName) {
|
||||
if (binName[0] === ".") return;
|
||||
|
||||
const suiteLoc = path.join(fixtureLoc, binName);
|
||||
describe("bin/" + binName, function () {
|
||||
fs.readdirSync(suiteLoc).forEach(function (testName) {
|
||||
describe("bin/" + binName, function() {
|
||||
fs.readdirSync(suiteLoc).forEach(function(testName) {
|
||||
if (testName[0] === ".") return;
|
||||
|
||||
const testLoc = path.join(suiteLoc, testName);
|
||||
@@ -179,7 +194,7 @@ fs.readdirSync(fixtureLoc).forEach(function (binName) {
|
||||
const optionsLoc = path.join(testLoc, "options.json");
|
||||
if (fs.existsSync(optionsLoc)) merge(opts, require(optionsLoc));
|
||||
|
||||
["stdout", "stdin", "stderr"].forEach(function (key) {
|
||||
["stdout", "stdin", "stderr"].forEach(function(key) {
|
||||
const loc = path.join(testLoc, key + ".txt");
|
||||
if (fs.existsSync(loc)) {
|
||||
opts[key] = helper.readFile(loc);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "babel-code-frame",
|
||||
"version": "7.0.0-alpha.11",
|
||||
"version": "7.0.0-beta.0",
|
||||
"description": "Generate errors that contain a code frame that point to source locations.",
|
||||
"author": "Sebastian McKenzie <sebmck@gmail.com>",
|
||||
"homepage": "https://babeljs.io/",
|
||||
@@ -8,8 +8,11 @@
|
||||
"repository": "https://github.com/babel/babel/tree/master/packages/babel-code-frame",
|
||||
"main": "lib/index.js",
|
||||
"dependencies": {
|
||||
"chalk": "^1.1.0",
|
||||
"chalk": "^2.0.0",
|
||||
"esutils": "^2.0.2",
|
||||
"js-tokens": "^3.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"strip-ansi": "^4.0.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,7 +51,7 @@ const JSX_TAG = /^[a-z][\w-]*$/i;
|
||||
* RegExp to test for the three types of brackets.
|
||||
*/
|
||||
|
||||
const BRACKET = /^[()\[\]{}]$/;
|
||||
const BRACKET = /^[()[\]{}]$/;
|
||||
|
||||
/**
|
||||
* Get the type of token, specifying punctuator type.
|
||||
@@ -90,11 +90,14 @@ function getTokenType(match) {
|
||||
*/
|
||||
|
||||
function highlight(defs: Object, text: string) {
|
||||
return text.replace(jsTokens, function (...args) {
|
||||
return text.replace(jsTokens, function(...args) {
|
||||
const type = getTokenType(args);
|
||||
const colorize = defs[type];
|
||||
if (colorize) {
|
||||
return args[0].split(NEWLINE).map((str) => colorize(str)).join("\n");
|
||||
return args[0]
|
||||
.split(NEWLINE)
|
||||
.map(str => colorize(str))
|
||||
.join("\n");
|
||||
} else {
|
||||
return args[0];
|
||||
}
|
||||
@@ -106,9 +109,15 @@ function highlight(defs: Object, text: string) {
|
||||
*/
|
||||
|
||||
function getMarkerLines(
|
||||
loc: NodeLocation, source: Array<string>, opts: Object
|
||||
loc: NodeLocation,
|
||||
source: Array<string>,
|
||||
opts: Object,
|
||||
): { start: number, end: number, markerLines: Object } {
|
||||
const startLoc: Location = Object.assign({}, { column: 0, line: -1 }, loc.start);
|
||||
const startLoc: Location = Object.assign(
|
||||
{},
|
||||
{ column: 0, line: -1 },
|
||||
loc.start,
|
||||
);
|
||||
const endLoc: Location = Object.assign({}, startLoc, loc.end);
|
||||
const linesAbove = opts.linesAbove || 2;
|
||||
const linesBelow = opts.linesBelow || 3;
|
||||
@@ -165,12 +174,13 @@ function getMarkerLines(
|
||||
return { start, end, markerLines };
|
||||
}
|
||||
|
||||
export function codeFrameColumns (
|
||||
export function codeFrameColumns(
|
||||
rawLines: string,
|
||||
loc: NodeLocation,
|
||||
opts: Object = {},
|
||||
): string {
|
||||
const highlighted = (opts.highlightCode && Chalk.supportsColor) || opts.forceColor;
|
||||
const highlighted =
|
||||
(opts.highlightCode && Chalk.supportsColor) || opts.forceColor;
|
||||
let chalk = Chalk;
|
||||
if (opts.forceColor) {
|
||||
chalk = new Chalk.constructor({ enabled: true });
|
||||
@@ -186,34 +196,39 @@ export function codeFrameColumns (
|
||||
|
||||
const numberMaxWidth = String(end).length;
|
||||
|
||||
const frame = lines.slice(start, end).map((line, index) => {
|
||||
const number = start + 1 + index;
|
||||
const paddedNumber = ` ${number}`.slice(-numberMaxWidth);
|
||||
const gutter = ` ${paddedNumber} | `;
|
||||
const hasMarker = markerLines[number];
|
||||
if (hasMarker) {
|
||||
let markerLine = "";
|
||||
if (Array.isArray(hasMarker)) {
|
||||
const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " ");
|
||||
const numberOfMarkers = hasMarker[1] || 1;
|
||||
const frame = lines
|
||||
.slice(start, end)
|
||||
.map((line, index) => {
|
||||
const number = start + 1 + index;
|
||||
const paddedNumber = ` ${number}`.slice(-numberMaxWidth);
|
||||
const gutter = ` ${paddedNumber} | `;
|
||||
const hasMarker = markerLines[number];
|
||||
if (hasMarker) {
|
||||
let markerLine = "";
|
||||
if (Array.isArray(hasMarker)) {
|
||||
const markerSpacing = line
|
||||
.slice(0, Math.max(hasMarker[0] - 1, 0))
|
||||
.replace(/[^\t]/g, " ");
|
||||
const numberOfMarkers = hasMarker[1] || 1;
|
||||
|
||||
markerLine = [
|
||||
"\n ",
|
||||
maybeHighlight(defs.gutter, gutter.replace(/\d/g, " ")),
|
||||
markerSpacing,
|
||||
maybeHighlight(defs.marker, "^").repeat(numberOfMarkers),
|
||||
markerLine = [
|
||||
"\n ",
|
||||
maybeHighlight(defs.gutter, gutter.replace(/\d/g, " ")),
|
||||
markerSpacing,
|
||||
maybeHighlight(defs.marker, "^").repeat(numberOfMarkers),
|
||||
].join("");
|
||||
}
|
||||
return [
|
||||
maybeHighlight(defs.marker, ">"),
|
||||
maybeHighlight(defs.gutter, gutter),
|
||||
line,
|
||||
markerLine,
|
||||
].join("");
|
||||
} else {
|
||||
return ` ${maybeHighlight(defs.gutter, gutter)}${line}`;
|
||||
}
|
||||
return [
|
||||
maybeHighlight(defs.marker, ">"),
|
||||
maybeHighlight(defs.gutter, gutter),
|
||||
line,
|
||||
markerLine,
|
||||
].join("");
|
||||
} else {
|
||||
return ` ${maybeHighlight(defs.gutter, gutter)}${line}`;
|
||||
}
|
||||
}).join("\n");
|
||||
})
|
||||
.join("\n");
|
||||
|
||||
if (highlighted) {
|
||||
return chalk.reset(frame);
|
||||
@@ -226,7 +241,7 @@ export function codeFrameColumns (
|
||||
* Create a code frame, adding line numbers, code highlighting, and pointing to a given position.
|
||||
*/
|
||||
|
||||
export default function (
|
||||
export default function(
|
||||
rawLines: string,
|
||||
lineNumber: number,
|
||||
colNumber: ?number,
|
||||
@@ -236,7 +251,7 @@ export default function (
|
||||
deprecationWarningShown = true;
|
||||
|
||||
const deprecationError = new Error(
|
||||
"Passing lineNumber and colNumber is deprecated to babel-code-frame. Please use `codeFrameColumns`."
|
||||
"Passing lineNumber and colNumber is deprecated to babel-code-frame. Please use `codeFrameColumns`.",
|
||||
);
|
||||
deprecationError.name = "DeprecationWarning";
|
||||
|
||||
@@ -249,7 +264,9 @@ export default function (
|
||||
|
||||
colNumber = Math.max(colNumber, 0);
|
||||
|
||||
const location: NodeLocation = { start: { column: colNumber, line: lineNumber } };
|
||||
const location: NodeLocation = {
|
||||
start: { column: colNumber, line: lineNumber },
|
||||
};
|
||||
|
||||
return codeFrameColumns(rawLines, location, opts);
|
||||
}
|
||||
|
||||
@@ -1,36 +1,31 @@
|
||||
import assert from "assert";
|
||||
import chalk from "chalk";
|
||||
import stripAnsi from "strip-ansi";
|
||||
import codeFrame, { codeFrameColumns } from "..";
|
||||
|
||||
describe("babel-code-frame", function () {
|
||||
it("basic usage", function () {
|
||||
const rawLines = [
|
||||
"class Foo {",
|
||||
" constructor()",
|
||||
"};",
|
||||
].join("\n");
|
||||
assert.equal(codeFrame(rawLines, 2, 16), [
|
||||
" 1 | class Foo {",
|
||||
"> 2 | constructor()",
|
||||
" | ^",
|
||||
" 3 | };",
|
||||
].join("\n"));
|
||||
describe("babel-code-frame", function() {
|
||||
it("basic usage", function() {
|
||||
const rawLines = ["class Foo {", " constructor()", "};"].join("\n");
|
||||
assert.equal(
|
||||
codeFrame(rawLines, 2, 16),
|
||||
[
|
||||
" 1 | class Foo {",
|
||||
"> 2 | constructor()",
|
||||
" | ^",
|
||||
" 3 | };",
|
||||
].join("\n"),
|
||||
);
|
||||
});
|
||||
|
||||
it("optional column number", function () {
|
||||
const rawLines = [
|
||||
"class Foo {",
|
||||
" constructor()",
|
||||
"};",
|
||||
].join("\n");
|
||||
assert.equal(codeFrame(rawLines, 2, null), [
|
||||
" 1 | class Foo {",
|
||||
"> 2 | constructor()",
|
||||
" 3 | };",
|
||||
].join("\n"));
|
||||
it("optional column number", function() {
|
||||
const rawLines = ["class Foo {", " constructor()", "};"].join("\n");
|
||||
assert.equal(
|
||||
codeFrame(rawLines, 2, null),
|
||||
[" 1 | class Foo {", "> 2 | constructor()", " 3 | };"].join("\n"),
|
||||
);
|
||||
});
|
||||
|
||||
it("maximum context lines and padding", function () {
|
||||
it("maximum context lines and padding", function() {
|
||||
const rawLines = [
|
||||
"/**",
|
||||
" * Sums two numbers.",
|
||||
@@ -44,18 +39,21 @@ describe("babel-code-frame", function () {
|
||||
" return a + b",
|
||||
"}",
|
||||
].join("\n");
|
||||
assert.equal(codeFrame(rawLines, 7, 2), [
|
||||
" 5 | * @param b Number",
|
||||
" 6 | * @returns Number",
|
||||
"> 7 | */",
|
||||
" | ^",
|
||||
" 8 | ",
|
||||
" 9 | function sum(a, b) {",
|
||||
" 10 | return a + b",
|
||||
].join("\n"));
|
||||
assert.equal(
|
||||
codeFrame(rawLines, 7, 2),
|
||||
[
|
||||
" 5 | * @param b Number",
|
||||
" 6 | * @returns Number",
|
||||
"> 7 | */",
|
||||
" | ^",
|
||||
" 8 | ",
|
||||
" 9 | function sum(a, b) {",
|
||||
" 10 | return a + b",
|
||||
].join("\n"),
|
||||
);
|
||||
});
|
||||
|
||||
it("no unnecessary padding due to one-off errors", function () {
|
||||
it("no unnecessary padding due to one-off errors", function() {
|
||||
const rawLines = [
|
||||
"/**",
|
||||
" * Sums two numbers.",
|
||||
@@ -69,43 +67,49 @@ describe("babel-code-frame", function () {
|
||||
" return a + b",
|
||||
"}",
|
||||
].join("\n");
|
||||
assert.equal(codeFrame(rawLines, 6, 2), [
|
||||
" 4 | * @param a Number",
|
||||
" 5 | * @param b Number",
|
||||
"> 6 | * @returns Number",
|
||||
" | ^",
|
||||
" 7 | */",
|
||||
" 8 | ",
|
||||
" 9 | function sum(a, b) {",
|
||||
].join("\n"));
|
||||
assert.equal(
|
||||
codeFrame(rawLines, 6, 2),
|
||||
[
|
||||
" 4 | * @param a Number",
|
||||
" 5 | * @param b Number",
|
||||
"> 6 | * @returns Number",
|
||||
" | ^",
|
||||
" 7 | */",
|
||||
" 8 | ",
|
||||
" 9 | function sum(a, b) {",
|
||||
].join("\n"),
|
||||
);
|
||||
});
|
||||
|
||||
it("tabs", function () {
|
||||
it("tabs", function() {
|
||||
const rawLines = [
|
||||
"\tclass Foo {",
|
||||
"\t \t\t constructor\t(\t)",
|
||||
"\t};",
|
||||
].join("\n");
|
||||
assert.equal(codeFrame(rawLines, 2, 25), [
|
||||
" 1 | \tclass Foo {",
|
||||
"> 2 | \t \t\t constructor\t(\t)",
|
||||
" | \t \t\t \t \t ^",
|
||||
" 3 | \t};",
|
||||
].join("\n"));
|
||||
assert.equal(
|
||||
codeFrame(rawLines, 2, 25),
|
||||
[
|
||||
" 1 | \tclass Foo {",
|
||||
"> 2 | \t \t\t constructor\t(\t)",
|
||||
" | \t \t\t \t \t ^",
|
||||
" 3 | \t};",
|
||||
].join("\n"),
|
||||
);
|
||||
});
|
||||
|
||||
it("opts.highlightCode", function () {
|
||||
it("opts.highlightCode", function() {
|
||||
const rawLines = "console.log('babel')";
|
||||
const result = codeFrame(rawLines, 1, 9, { highlightCode: true });
|
||||
const stripped = chalk.stripColor(result);
|
||||
const stripped = stripAnsi(result);
|
||||
assert.ok(result.length > stripped.length);
|
||||
assert.equal(stripped, [
|
||||
"> 1 | console.log('babel')",
|
||||
" | ^",
|
||||
].join("\n"));
|
||||
assert.equal(
|
||||
stripped,
|
||||
["> 1 | console.log('babel')", " | ^"].join("\n"),
|
||||
);
|
||||
});
|
||||
|
||||
it("opts.linesAbove", function () {
|
||||
it("opts.linesAbove", function() {
|
||||
const rawLines = [
|
||||
"/**",
|
||||
" * Sums two numbers.",
|
||||
@@ -119,17 +123,20 @@ describe("babel-code-frame", function () {
|
||||
" return a + b",
|
||||
"}",
|
||||
].join("\n");
|
||||
assert.equal(codeFrame(rawLines, 7, 2, { linesAbove: 1 }), [
|
||||
" 6 | * @returns Number",
|
||||
"> 7 | */",
|
||||
" | ^",
|
||||
" 8 | ",
|
||||
" 9 | function sum(a, b) {",
|
||||
" 10 | return a + b",
|
||||
].join("\n"));
|
||||
assert.equal(
|
||||
codeFrame(rawLines, 7, 2, { linesAbove: 1 }),
|
||||
[
|
||||
" 6 | * @returns Number",
|
||||
"> 7 | */",
|
||||
" | ^",
|
||||
" 8 | ",
|
||||
" 9 | function sum(a, b) {",
|
||||
" 10 | return a + b",
|
||||
].join("\n"),
|
||||
);
|
||||
});
|
||||
|
||||
it("opts.linesBelow", function () {
|
||||
it("opts.linesBelow", function() {
|
||||
const rawLines = [
|
||||
"/**",
|
||||
" * Sums two numbers.",
|
||||
@@ -143,16 +150,19 @@ describe("babel-code-frame", function () {
|
||||
" return a + b",
|
||||
"}",
|
||||
].join("\n");
|
||||
assert.equal(codeFrame(rawLines, 7, 2, { linesBelow: 1 }), [
|
||||
" 5 | * @param b Number",
|
||||
" 6 | * @returns Number",
|
||||
"> 7 | */",
|
||||
" | ^",
|
||||
" 8 | ",
|
||||
].join("\n"));
|
||||
assert.equal(
|
||||
codeFrame(rawLines, 7, 2, { linesBelow: 1 }),
|
||||
[
|
||||
" 5 | * @param b Number",
|
||||
" 6 | * @returns Number",
|
||||
"> 7 | */",
|
||||
" | ^",
|
||||
" 8 | ",
|
||||
].join("\n"),
|
||||
);
|
||||
});
|
||||
|
||||
it("opts.linesAbove and opts.linesBelow", function () {
|
||||
it("opts.linesAbove and opts.linesBelow", function() {
|
||||
const rawLines = [
|
||||
"/**",
|
||||
" * Sums two numbers.",
|
||||
@@ -166,78 +176,82 @@ describe("babel-code-frame", function () {
|
||||
" return a + b",
|
||||
"}",
|
||||
].join("\n");
|
||||
assert.equal(codeFrame(rawLines, 7, 2, { linesAbove: 1, linesBelow: 1 }), [
|
||||
" 6 | * @returns Number",
|
||||
"> 7 | */",
|
||||
" | ^",
|
||||
" 8 | ",
|
||||
].join("\n"));
|
||||
assert.equal(
|
||||
codeFrame(rawLines, 7, 2, { linesAbove: 1, linesBelow: 1 }),
|
||||
[" 6 | * @returns Number", "> 7 | */", " | ^", " 8 | "].join(
|
||||
"\n",
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it("opts.forceColor", function() {
|
||||
const marker = chalk.red.bold;
|
||||
const gutter = chalk.grey;
|
||||
|
||||
const rawLines = [
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
].join("\n");
|
||||
assert.equal(codeFrame(rawLines, 3, null, { linesAbove: 1, linesBelow: 1, forceColor: true }),
|
||||
chalk.reset([
|
||||
" " + gutter(" 2 | "),
|
||||
marker(">") + gutter(" 3 | "),
|
||||
" " + gutter(" 4 | "),
|
||||
].join("\n"))
|
||||
const rawLines = ["", "", "", ""].join("\n");
|
||||
assert.equal(
|
||||
codeFrame(rawLines, 3, null, {
|
||||
linesAbove: 1,
|
||||
linesBelow: 1,
|
||||
forceColor: true,
|
||||
}),
|
||||
chalk.reset(
|
||||
[
|
||||
" " + gutter(" 2 | "),
|
||||
marker(">") + gutter(" 3 | "),
|
||||
" " + gutter(" 4 | "),
|
||||
].join("\n"),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it("basic usage, new API", function () {
|
||||
const rawLines = [
|
||||
"class Foo {",
|
||||
" constructor()",
|
||||
"};",
|
||||
].join("\n");
|
||||
assert.equal(codeFrameColumns(rawLines, { start: { line: 2, column: 16 } }), [
|
||||
" 1 | class Foo {",
|
||||
"> 2 | constructor()",
|
||||
" | ^",
|
||||
" 3 | };",
|
||||
].join("\n"));
|
||||
it("basic usage, new API", function() {
|
||||
const rawLines = ["class Foo {", " constructor()", "};"].join("\n");
|
||||
assert.equal(
|
||||
codeFrameColumns(rawLines, { start: { line: 2, column: 16 } }),
|
||||
[
|
||||
" 1 | class Foo {",
|
||||
"> 2 | constructor()",
|
||||
" | ^",
|
||||
" 3 | };",
|
||||
].join("\n"),
|
||||
);
|
||||
});
|
||||
|
||||
it("mark multiple columns", function() {
|
||||
const rawLines = [
|
||||
"class Foo {",
|
||||
" constructor()",
|
||||
"};",
|
||||
].join("\n");
|
||||
const rawLines = ["class Foo {", " constructor()", "};"].join("\n");
|
||||
assert.equal(
|
||||
codeFrameColumns(rawLines, { start: { line: 2, column: 3 }, end: { line: 2, column: 16 } }), [
|
||||
codeFrameColumns(rawLines, {
|
||||
start: { line: 2, column: 3 },
|
||||
end: { line: 2, column: 16 },
|
||||
}),
|
||||
[
|
||||
" 1 | class Foo {",
|
||||
"> 2 | constructor()",
|
||||
" | ^^^^^^^^^^^^^",
|
||||
" 3 | };",
|
||||
].join("\n"));
|
||||
].join("\n"),
|
||||
);
|
||||
});
|
||||
|
||||
it("mark multiple columns across lines", function() {
|
||||
const rawLines = [
|
||||
"class Foo {",
|
||||
" constructor() {",
|
||||
" }",
|
||||
"};",
|
||||
].join("\n");
|
||||
const rawLines = ["class Foo {", " constructor() {", " }", "};"].join(
|
||||
"\n",
|
||||
);
|
||||
assert.equal(
|
||||
codeFrameColumns(rawLines, { start: { line: 2, column: 17 }, end: { line: 3, column: 3 } }), [
|
||||
codeFrameColumns(rawLines, {
|
||||
start: { line: 2, column: 17 },
|
||||
end: { line: 3, column: 3 },
|
||||
}),
|
||||
[
|
||||
" 1 | class Foo {",
|
||||
"> 2 | constructor() {",
|
||||
" | ^",
|
||||
"> 3 | }",
|
||||
" | ^^^",
|
||||
" 4 | };",
|
||||
].join("\n"));
|
||||
].join("\n"),
|
||||
);
|
||||
});
|
||||
|
||||
it("mark multiple columns across multiple lines", function() {
|
||||
@@ -249,7 +263,11 @@ describe("babel-code-frame", function () {
|
||||
"};",
|
||||
].join("\n");
|
||||
assert.equal(
|
||||
codeFrameColumns(rawLines, { start: { line: 2, column: 17 }, end: { line: 4, column: 3 } }), [
|
||||
codeFrameColumns(rawLines, {
|
||||
start: { line: 2, column: 17 },
|
||||
end: { line: 4, column: 3 },
|
||||
}),
|
||||
[
|
||||
" 1 | class Foo {",
|
||||
"> 2 | constructor() {",
|
||||
" | ^",
|
||||
@@ -258,7 +276,8 @@ describe("babel-code-frame", function () {
|
||||
"> 4 | }",
|
||||
" | ^^^",
|
||||
" 5 | };",
|
||||
].join("\n"));
|
||||
].join("\n"),
|
||||
);
|
||||
});
|
||||
|
||||
it("mark across multiple lines without columns", function() {
|
||||
@@ -270,12 +289,14 @@ describe("babel-code-frame", function () {
|
||||
"};",
|
||||
].join("\n");
|
||||
assert.equal(
|
||||
codeFrameColumns(rawLines, { start: { line: 2 }, end: { line: 4 } }), [
|
||||
codeFrameColumns(rawLines, { start: { line: 2 }, end: { line: 4 } }),
|
||||
[
|
||||
" 1 | class Foo {",
|
||||
"> 2 | constructor() {",
|
||||
"> 3 | console.log(arguments);",
|
||||
"> 4 | }",
|
||||
" 5 | };",
|
||||
].join("\n"));
|
||||
].join("\n"),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -5,11 +5,11 @@
|
||||
|
||||
```javascript
|
||||
var babel = require("babel-core");
|
||||
import { transform } from 'babel-core';
|
||||
import * as babel from 'babel-core';
|
||||
import { transform } from "babel-core";
|
||||
import * as babel from "babel-core";
|
||||
```
|
||||
|
||||
All transformations will use your local configuration files (.babelrc or in package.json). See [options](#options) to disable it.
|
||||
All transformations will use your local configuration files (`.babelrc` or in `package.json`). See [options](#options) to disable it.
|
||||
|
||||
## babel.transform(code: string, [options?](#options): Object)
|
||||
|
||||
@@ -62,7 +62,7 @@ babel.transformFileSync("filename.js", options).code;
|
||||
|
||||
## babel.transformFromAst(ast: Object, code?: string, [options?](#options): Object)
|
||||
|
||||
Given, an [AST](https://astexplorer.net/), transform it.
|
||||
Given an [AST](https://astexplorer.net/), transform it.
|
||||
|
||||
```js
|
||||
const sourceCode = "if (true) return;";
|
||||
@@ -87,35 +87,35 @@ Following is a table of the options you can use:
|
||||
| Option | Default | Description |
|
||||
| ------------------------ | -------------------- | ------------------------------- |
|
||||
| `ast` | `true` | 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. |
|
||||
| `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). |
|
||||
| `auxiliaryCommentAfter` | `null` | Attach a comment after all non-user injected code |
|
||||
| `auxiliaryCommentBefore` | `null` | Attach a comment before all non-user injected code |
|
||||
| `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) |
|
||||
| `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. |
|
||||
| `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 environment variable `BABEL_ENV` is set to `"production"`. If `BABEL_ENV` isn't set then `NODE_ENV` will be used, if it's not set then it defaults to `"development"` |
|
||||
| `extends` | `null` | A path to an `.babelrc` file to extend |
|
||||
| `filename` | `"unknown"` | Filename for use in errors etc. |
|
||||
| `filenameRelative` | `(filename)` | Filename relative to `sourceRoot`. |
|
||||
| `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. |
|
||||
| `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. |
|
||||
| `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. |
|
||||
| `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. |
|
||||
| `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. |
|
||||
| `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) |
|
||||
| `resolveModuleSource` | `null` | Resolve a module source ie. `import "SOURCE";` to a custom value. Called as `resolveModuleSource(source, filename)`. |
|
||||
| `shouldPrintComment` | `null` | An optional callback that controls whether a comment should be output or not. Called as `shouldPrintComment(commentContents)`. **NOTE:** This overrides the `comment` option when used. |
|
||||
| `sourceFileName` | `(filenameRelative)` | Set `sources[0]` on returned source map. |
|
||||
| `sourceMaps` | `false` | If truthy, adds a `map` property to returned output. If set to `"inline"`, a comment with a sourceMappingURL directive is added to the bottom of the returned code. If set to `"both"` then a `map` property is returned as well as a source map comment appended. **This does not emit sourcemap files by itself!** To have sourcemaps emitted using the CLI, you must pass it the `--source-maps` option. |
|
||||
| `sourceMapTarget` | `(filenameRelative)` | Set `file` on returned source map. |
|
||||
| `sourceRoot` | `(moduleRoot)` | The root from which all sources are relative. |
|
||||
| `sourceType` | `"module"` | Indicate the mode the code should be parsed in. Can be either "script" or "module". |
|
||||
| `resolveModuleSource` | `null` | Resolve a module source ie. `import "SOURCE";` to a custom value. Called as `resolveModuleSource(source, filename)` |
|
||||
| `shouldPrintComment` | `null` | An optional callback that controls whether a comment should be output or not. Called as `shouldPrintComment(commentContents)`. **NOTE:** This overrides the `comment` option when used |
|
||||
| `sourceFileName` | `(filenameRelative)` | Set `sources[0]` on returned source map |
|
||||
| `sourceMaps` | `false` | If truthy, adds a `map` property to returned output. If set to `"inline"`, a comment with a sourceMappingURL directive is added to the bottom of the returned code. If set to `"both"` then a `map` property is returned as well as a source map comment appended. **This does not emit sourcemap files by itself!** To have sourcemaps emitted using the CLI, you must pass it the `--source-maps` option |
|
||||
| `sourceMapTarget` | `(filenameRelative)` | Set `file` on returned source map |
|
||||
| `sourceRoot` | `(moduleRoot)` | The root from which all sources are relative |
|
||||
| `sourceType` | `"module"` | Indicate the mode the code should be parsed in. Can be either "script" or "module" |
|
||||
| `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)`.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "babel-core",
|
||||
"version": "7.0.0-alpha.11",
|
||||
"version": "7.0.0-beta.0",
|
||||
"description": "Babel compiler core.",
|
||||
"author": "Sebastian McKenzie <sebmck@gmail.com>",
|
||||
"homepage": "https://babeljs.io/",
|
||||
@@ -25,28 +25,24 @@
|
||||
"./lib/config/loading/files/index.js": "./lib/config/loading/files/index-browser.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"babel-code-frame": "7.0.0-alpha.11",
|
||||
"babel-generator": "7.0.0-alpha.11",
|
||||
"babel-helpers": "7.0.0-alpha.11",
|
||||
"babel-messages": "7.0.0-alpha.10",
|
||||
"babel-template": "7.0.0-alpha.11",
|
||||
"babel-traverse": "7.0.0-alpha.11",
|
||||
"babel-types": "7.0.0-alpha.11",
|
||||
"babylon": "7.0.0-beta.12",
|
||||
"babel-code-frame": "7.0.0-beta.0",
|
||||
"babel-generator": "7.0.0-beta.0",
|
||||
"babel-helpers": "7.0.0-beta.0",
|
||||
"babel-messages": "7.0.0-beta.0",
|
||||
"babel-template": "7.0.0-beta.0",
|
||||
"babel-traverse": "7.0.0-beta.0",
|
||||
"babel-types": "7.0.0-beta.0",
|
||||
"babylon": "7.0.0-beta.22",
|
||||
"convert-source-map": "^1.1.0",
|
||||
"debug": "^2.1.1",
|
||||
"debug": "^3.0.1",
|
||||
"json5": "^0.5.0",
|
||||
"lodash": "^4.2.0",
|
||||
"micromatch": "^2.3.11",
|
||||
"private": "^0.1.6",
|
||||
"resolve": "^1.3.2",
|
||||
"slash": "^1.0.0",
|
||||
"source-map": "^0.5.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"babel-helper-fixtures": "7.0.0-alpha.10",
|
||||
"babel-helper-transform-fixture-test-runner": "7.0.0-alpha.11",
|
||||
"babel-polyfill": "7.0.0-alpha.9",
|
||||
"babel-register": "7.0.0-alpha.11"
|
||||
"babel-helper-transform-fixture-test-runner": "7.0.0-beta.0",
|
||||
"babel-register": "7.0.0-beta.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,18 +3,21 @@
|
||||
import { getEnv } from "./helpers/environment";
|
||||
import path from "path";
|
||||
import micromatch from "micromatch";
|
||||
import buildDebug from "debug";
|
||||
|
||||
const debug = buildDebug("babel:config:config-chain");
|
||||
|
||||
import { findConfigs, loadConfig } from "./loading/files";
|
||||
|
||||
type ConfigItem = {
|
||||
type: "options"|"arguments",
|
||||
type: "options" | "arguments",
|
||||
options: {},
|
||||
dirname: string,
|
||||
alias: string,
|
||||
loc: string,
|
||||
};
|
||||
|
||||
export default function buildConfigChain(opts: {}): Array<ConfigItem>|null {
|
||||
export default function buildConfigChain(opts: {}): Array<ConfigItem> | null {
|
||||
if (typeof opts.filename !== "string" && opts.filename != null) {
|
||||
throw new Error(".filename must be a string, null, or undefined");
|
||||
}
|
||||
@@ -44,9 +47,9 @@ export default function buildConfigChain(opts: {}): Array<ConfigItem>|null {
|
||||
}
|
||||
|
||||
class ConfigChainBuilder {
|
||||
filename: string|null;
|
||||
filename: string | null;
|
||||
configs: Array<ConfigItem>;
|
||||
possibleDirs: null|Array<string>;
|
||||
possibleDirs: null | Array<string>;
|
||||
|
||||
constructor(filename) {
|
||||
this.configs = [];
|
||||
@@ -57,27 +60,43 @@ class ConfigChainBuilder {
|
||||
/**
|
||||
* Tests if a filename should be ignored based on "ignore" and "only" options.
|
||||
*/
|
||||
shouldIgnore(
|
||||
ignore: mixed,
|
||||
only: mixed,
|
||||
dirname: string,
|
||||
): boolean {
|
||||
shouldIgnore(ignore: mixed, only: mixed, dirname: string): boolean {
|
||||
if (!this.filename) return false;
|
||||
|
||||
if (ignore) {
|
||||
if (!Array.isArray(ignore)) {
|
||||
throw new Error(`.ignore should be an array, ${JSON.stringify(ignore)} given`);
|
||||
throw new Error(
|
||||
`.ignore should be an array, ${JSON.stringify(ignore)} given`,
|
||||
);
|
||||
}
|
||||
|
||||
if (this.matchesPatterns(ignore, dirname)) return true;
|
||||
if (this.matchesPatterns(ignore, dirname)) {
|
||||
debug(
|
||||
"Ignored %o because it matched one of %O from %o",
|
||||
this.filename,
|
||||
ignore,
|
||||
dirname,
|
||||
);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
if (only) {
|
||||
if (!Array.isArray(only)) {
|
||||
throw new Error(`.only should be an array, ${JSON.stringify(only)} given`);
|
||||
throw new Error(
|
||||
`.only should be an array, ${JSON.stringify(only)} given`,
|
||||
);
|
||||
}
|
||||
|
||||
if (!this.matchesPatterns(only, dirname)) return true;
|
||||
if (!this.matchesPatterns(only, dirname)) {
|
||||
debug(
|
||||
"Ignored %o because it failed to match one of %O from %o",
|
||||
this.filename,
|
||||
only,
|
||||
dirname,
|
||||
);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
@@ -89,21 +108,27 @@ class ConfigChainBuilder {
|
||||
*/
|
||||
matchesPatterns(patterns: Array<mixed>, dirname: string) {
|
||||
const filename = this.filename;
|
||||
if (!filename) throw new Error("Assertion failure: .filename should always exist here");
|
||||
if (!filename) {
|
||||
throw new Error("Assertion failure: .filename should always exist here");
|
||||
}
|
||||
|
||||
const res = [];
|
||||
const strings = [];
|
||||
const fns = [];
|
||||
|
||||
patterns.forEach((pattern) => {
|
||||
patterns.forEach(pattern => {
|
||||
if (typeof pattern === "string") strings.push(pattern);
|
||||
else if (typeof pattern === "function") fns.push(pattern);
|
||||
else if (pattern instanceof RegExp) res.push(pattern);
|
||||
else throw new Error("Patterns must be a string, function, or regular expression");
|
||||
else {
|
||||
throw new Error(
|
||||
"Patterns must be a string, function, or regular expression",
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
if (res.some((re) => re.test(filename))) return true;
|
||||
if (fns.some((fn) => fn(filename))) return true;
|
||||
if (res.some(re => re.test(filename))) return true;
|
||||
if (fns.some(fn => fn(filename))) return true;
|
||||
|
||||
if (strings.length > 0) {
|
||||
let possibleDirs = this.possibleDirs;
|
||||
@@ -123,7 +148,7 @@ class ConfigChainBuilder {
|
||||
}
|
||||
}
|
||||
|
||||
const absolutePatterns = strings.map((pattern) => {
|
||||
const absolutePatterns = strings.map(pattern => {
|
||||
// Preserve the "!" prefix so that micromatch can use it for negation.
|
||||
const negate = pattern[0] === "!";
|
||||
if (negate) pattern = pattern.slice(1);
|
||||
@@ -131,7 +156,9 @@ class ConfigChainBuilder {
|
||||
return (negate ? "!" : "") + path.resolve(dirname, pattern);
|
||||
});
|
||||
|
||||
if (micromatch(possibleDirs, absolutePatterns, { nocase: true }).length > 0) {
|
||||
if (
|
||||
micromatch(possibleDirs, absolutePatterns, { nocase: true }).length > 0
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -150,16 +177,16 @@ class ConfigChainBuilder {
|
||||
});
|
||||
}
|
||||
|
||||
mergeConfig({
|
||||
type,
|
||||
options: rawOpts,
|
||||
alias,
|
||||
dirname,
|
||||
}) {
|
||||
mergeConfig({ type, options: rawOpts, alias, dirname }) {
|
||||
// Bail out ASAP if this file is ignored so that we run as little logic as possible on ignored files.
|
||||
if (this.filename && this.shouldIgnore(rawOpts.ignore || null, rawOpts.only || null, dirname)) {
|
||||
if (
|
||||
this.filename &&
|
||||
this.shouldIgnore(rawOpts.ignore || null, rawOpts.only || null, dirname)
|
||||
) {
|
||||
// TODO(logan): This is a really cross way to bail out. Avoid this in rewrite.
|
||||
throw Object.assign((new Error("This file has been ignored."): any), { code: "BABEL_IGNORED_FILE" });
|
||||
throw Object.assign((new Error("This file has been ignored."): any), {
|
||||
code: "BABEL_IGNORED_FILE",
|
||||
});
|
||||
}
|
||||
|
||||
const options = Object.assign({}, rawOpts);
|
||||
@@ -168,13 +195,19 @@ class ConfigChainBuilder {
|
||||
|
||||
const envKey = getEnv();
|
||||
|
||||
if (rawOpts.env != null && (typeof rawOpts.env !== "object" || Array.isArray(rawOpts.env))) {
|
||||
if (
|
||||
rawOpts.env != null &&
|
||||
(typeof rawOpts.env !== "object" || Array.isArray(rawOpts.env))
|
||||
) {
|
||||
throw new Error(".env block must be an object, null, or undefined");
|
||||
}
|
||||
|
||||
const envOpts = rawOpts.env && rawOpts.env[envKey];
|
||||
|
||||
if (envOpts != null && (typeof envOpts !== "object" || Array.isArray(envOpts))) {
|
||||
if (
|
||||
envOpts != null &&
|
||||
(typeof envOpts !== "object" || Array.isArray(envOpts))
|
||||
) {
|
||||
throw new Error(".env[...] block must be an object, null, or undefined");
|
||||
}
|
||||
|
||||
@@ -196,11 +229,13 @@ class ConfigChainBuilder {
|
||||
});
|
||||
|
||||
if (rawOpts.extends) {
|
||||
if (typeof rawOpts.extends !== "string") throw new Error(".extends must be a string");
|
||||
if (typeof rawOpts.extends !== "string") {
|
||||
throw new Error(".extends must be a string");
|
||||
}
|
||||
|
||||
const extendsConfig = loadConfig(rawOpts.extends, dirname);
|
||||
|
||||
const existingConfig = this.configs.some((config) => {
|
||||
const existingConfig = this.configs.some(config => {
|
||||
return config.alias === extendsConfig.filepath;
|
||||
});
|
||||
if (!existingConfig) {
|
||||
@@ -214,4 +249,3 @@ class ConfigChainBuilder {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ type CacheConfiguratorObj = {
|
||||
invalidate: <T>(handler: () => T) => T,
|
||||
};
|
||||
|
||||
type CacheEntry<ResultT> = Array<[ ResultT, () => boolean ]>;
|
||||
type CacheEntry<ResultT> = Array<[ResultT, () => boolean]>;
|
||||
|
||||
/**
|
||||
* Given a function with a single argument, cache its results based on its argument and how it
|
||||
@@ -22,7 +22,7 @@ type CacheEntry<ResultT> = Array<[ ResultT, () => boolean ]>;
|
||||
export function makeStrongCache<ArgT, ResultT>(
|
||||
handler: (ArgT, CacheConfigurator) => ResultT,
|
||||
autoPermacache?: boolean,
|
||||
): (ArgT) => ResultT {
|
||||
): ArgT => ResultT {
|
||||
return makeCachedFunction(new Map(), handler, autoPermacache);
|
||||
}
|
||||
|
||||
@@ -34,22 +34,24 @@ export function makeStrongCache<ArgT, ResultT>(
|
||||
export function makeWeakCache<ArgT: {}, ResultT>(
|
||||
handler: (ArgT, CacheConfigurator) => ResultT,
|
||||
autoPermacache?: boolean,
|
||||
): (ArgT) => ResultT {
|
||||
): ArgT => ResultT {
|
||||
return makeCachedFunction(new WeakMap(), handler, autoPermacache);
|
||||
}
|
||||
|
||||
type CacheMap<ArgT, ResultT> = Map<ArgT, CacheEntry<ResultT>>|WeakMap<ArgT, CacheEntry<ResultT>>;
|
||||
type CacheMap<ArgT, ResultT> =
|
||||
| Map<ArgT, CacheEntry<ResultT>>
|
||||
| WeakMap<ArgT, CacheEntry<ResultT>>;
|
||||
|
||||
function makeCachedFunction<ArgT, ResultT, Cache: CacheMap<ArgT, ResultT>>(
|
||||
callCache: Cache,
|
||||
handler: (ArgT, CacheConfigurator) => ResultT,
|
||||
autoPermacache: boolean = true,
|
||||
): (ArgT) => ResultT {
|
||||
): ArgT => ResultT {
|
||||
return function cachedFunction(arg) {
|
||||
let cachedValue: CacheEntry<ResultT>|void = callCache.get(arg);
|
||||
let cachedValue: CacheEntry<ResultT> | void = callCache.get(arg);
|
||||
|
||||
if (cachedValue) {
|
||||
for (const [ value, valid ] of cachedValue) {
|
||||
for (const [value, valid] of cachedValue) {
|
||||
if (valid()) return value;
|
||||
}
|
||||
}
|
||||
@@ -64,55 +66,53 @@ function makeCachedFunction<ArgT, ResultT, Cache: CacheMap<ArgT, ResultT>>(
|
||||
|
||||
if (!result.configured) {
|
||||
// eslint-disable-next-line max-len
|
||||
throw new Error([
|
||||
"Caching was left unconfigured. Babel's plugins, presets, and .babelrc.js files can be configured",
|
||||
"for various types of caching, using the first param of their handler functions:",
|
||||
"",
|
||||
"module.exports = function(api) {",
|
||||
" // The API exposes the following:",
|
||||
"",
|
||||
" // Cache the returned value forever and don't call this function again.",
|
||||
" api.cache(true);",
|
||||
"",
|
||||
" // Don't cache at all. Not recommended because it will be very slow.",
|
||||
" api.cache(false);",
|
||||
"",
|
||||
" // Cached based on the value of some function. If this function returns a value different from",
|
||||
" // a previously-encountered value, the plugins will re-evaluate.",
|
||||
" var env = api.cache(() => process.env.NODE_ENV);",
|
||||
"",
|
||||
" // If testing for a specific env, we recommend specifics to avoid instantiating a plugin for",
|
||||
" // any possible NODE_ENV value that might come up during plugin execution.",
|
||||
" var isProd = api.cache(() => process.env.NODE_ENV === \"production\");",
|
||||
"",
|
||||
" // .cache(fn) will perform a linear search though instances to find the matching plugin based",
|
||||
" // based on previous instantiated plugins. If you want to recreate the plugin and discard the",
|
||||
" // previous instance whenever something changes, you may use:",
|
||||
" var isProd = api.cache.invalidate(() => process.env.NODE_ENV === \"production\");",
|
||||
"",
|
||||
" // Note, we also expose the following more-verbose versions of the above examples:",
|
||||
" api.cache.forever(); // api.cache(true)",
|
||||
" api.cache.never(); // api.cache(false)",
|
||||
" api.cache.using(fn); // api.cache(fn)",
|
||||
"",
|
||||
" // Return the value that will be cached.",
|
||||
" return { };",
|
||||
"};",
|
||||
].join("\n"));
|
||||
throw new Error(
|
||||
[
|
||||
"Caching was left unconfigured. Babel's plugins, presets, and .babelrc.js files can be configured",
|
||||
"for various types of caching, using the first param of their handler functions:",
|
||||
"",
|
||||
"module.exports = function(api) {",
|
||||
" // The API exposes the following:",
|
||||
"",
|
||||
" // Cache the returned value forever and don't call this function again.",
|
||||
" api.cache(true);",
|
||||
"",
|
||||
" // Don't cache at all. Not recommended because it will be very slow.",
|
||||
" api.cache(false);",
|
||||
"",
|
||||
" // Cached based on the value of some function. If this function returns a value different from",
|
||||
" // a previously-encountered value, the plugins will re-evaluate.",
|
||||
" var env = api.cache(() => process.env.NODE_ENV);",
|
||||
"",
|
||||
" // If testing for a specific env, we recommend specifics to avoid instantiating a plugin for",
|
||||
" // any possible NODE_ENV value that might come up during plugin execution.",
|
||||
' var isProd = api.cache(() => process.env.NODE_ENV === "production");',
|
||||
"",
|
||||
" // .cache(fn) will perform a linear search though instances to find the matching plugin based",
|
||||
" // based on previous instantiated plugins. If you want to recreate the plugin and discard the",
|
||||
" // previous instance whenever something changes, you may use:",
|
||||
' var isProd = api.cache.invalidate(() => process.env.NODE_ENV === "production");',
|
||||
"",
|
||||
" // Note, we also expose the following more-verbose versions of the above examples:",
|
||||
" api.cache.forever(); // api.cache(true)",
|
||||
" api.cache.never(); // api.cache(false)",
|
||||
" api.cache.using(fn); // api.cache(fn)",
|
||||
"",
|
||||
" // Return the value that will be cached.",
|
||||
" return { };",
|
||||
"};",
|
||||
].join("\n"),
|
||||
);
|
||||
}
|
||||
|
||||
if (!result.never) {
|
||||
if (result.forever) {
|
||||
cachedValue = [
|
||||
[value, () => true],
|
||||
];
|
||||
cachedValue = [[value, () => true]];
|
||||
} else if (result.invalidate) {
|
||||
cachedValue = [
|
||||
[value, result.valid],
|
||||
];
|
||||
cachedValue = [[value, result.valid]];
|
||||
} else {
|
||||
cachedValue = cachedValue || [];
|
||||
cachedValue.push([ value, result.valid ]);
|
||||
cachedValue.push([value, result.valid]);
|
||||
}
|
||||
callCache.set(arg, cachedValue);
|
||||
}
|
||||
@@ -121,7 +121,11 @@ function makeCachedFunction<ArgT, ResultT, Cache: CacheMap<ArgT, ResultT>>(
|
||||
};
|
||||
}
|
||||
|
||||
function makeCacheConfig(): { cache: CacheConfigurator, result: *, deactivate: () => void } {
|
||||
function makeCacheConfig(): {
|
||||
cache: CacheConfigurator,
|
||||
result: *,
|
||||
deactivate: () => void,
|
||||
} {
|
||||
const pairs = [];
|
||||
|
||||
const result = {
|
||||
@@ -137,51 +141,80 @@ function makeCacheConfig(): { cache: CacheConfigurator, result: *, deactivate: (
|
||||
active = false;
|
||||
};
|
||||
|
||||
const cache: CacheConfigurator = Object.assign((function cacheFn(val) {
|
||||
if (typeof val === "boolean") {
|
||||
if (val) cache.forever();
|
||||
else cache.never();
|
||||
return;
|
||||
}
|
||||
|
||||
return cache.using(val);
|
||||
}: any), ({
|
||||
forever() {
|
||||
if (!active) throw new Error("Cannot change caching after evaluation has completed.");
|
||||
if (result.never) throw new Error("Caching has already been configured with .never()");
|
||||
result.forever = true;
|
||||
result.configured = true;
|
||||
},
|
||||
never() {
|
||||
if (!active) throw new Error("Cannot change caching after evaluation has completed.");
|
||||
if (result.forever) throw new Error("Caching has already been configured with .forever()");
|
||||
result.never = true;
|
||||
result.configured = true;
|
||||
},
|
||||
using<T>(handler: () => T): T {
|
||||
if (!active) throw new Error("Cannot change caching after evaluation has completed.");
|
||||
if (result.never || result.forever) {
|
||||
throw new Error("Caching has already been configured with .never or .forever()");
|
||||
const cache: CacheConfigurator = Object.assign(
|
||||
(function cacheFn(val) {
|
||||
if (typeof val === "boolean") {
|
||||
if (val) cache.forever();
|
||||
else cache.never();
|
||||
return;
|
||||
}
|
||||
result.configured = true;
|
||||
|
||||
const key = handler();
|
||||
pairs.push([ key, handler ]);
|
||||
return key;
|
||||
},
|
||||
invalidate<T>(handler: () => T): T {
|
||||
if (!active) throw new Error("Cannot change caching after evaluation has completed.");
|
||||
if (result.never || result.forever) {
|
||||
throw new Error("Caching has already been configured with .never or .forever()");
|
||||
}
|
||||
result.invalidate = true;
|
||||
result.configured = true;
|
||||
return cache.using(val);
|
||||
}: any),
|
||||
({
|
||||
forever() {
|
||||
if (!active) {
|
||||
throw new Error(
|
||||
"Cannot change caching after evaluation has completed.",
|
||||
);
|
||||
}
|
||||
if (result.never) {
|
||||
throw new Error("Caching has already been configured with .never()");
|
||||
}
|
||||
result.forever = true;
|
||||
result.configured = true;
|
||||
},
|
||||
never() {
|
||||
if (!active) {
|
||||
throw new Error(
|
||||
"Cannot change caching after evaluation has completed.",
|
||||
);
|
||||
}
|
||||
if (result.forever) {
|
||||
throw new Error(
|
||||
"Caching has already been configured with .forever()",
|
||||
);
|
||||
}
|
||||
result.never = true;
|
||||
result.configured = true;
|
||||
},
|
||||
using<T>(handler: () => T): T {
|
||||
if (!active) {
|
||||
throw new Error(
|
||||
"Cannot change caching after evaluation has completed.",
|
||||
);
|
||||
}
|
||||
if (result.never || result.forever) {
|
||||
throw new Error(
|
||||
"Caching has already been configured with .never or .forever()",
|
||||
);
|
||||
}
|
||||
result.configured = true;
|
||||
|
||||
const key = handler();
|
||||
pairs.push([ key, handler ]);
|
||||
return key;
|
||||
},
|
||||
}: CacheConfiguratorObj));
|
||||
const key = handler();
|
||||
pairs.push([key, handler]);
|
||||
return key;
|
||||
},
|
||||
invalidate<T>(handler: () => T): T {
|
||||
if (!active) {
|
||||
throw new Error(
|
||||
"Cannot change caching after evaluation has completed.",
|
||||
);
|
||||
}
|
||||
if (result.never || result.forever) {
|
||||
throw new Error(
|
||||
"Caching has already been configured with .never or .forever()",
|
||||
);
|
||||
}
|
||||
result.invalidate = true;
|
||||
result.configured = true;
|
||||
|
||||
const key = handler();
|
||||
pairs.push([key, handler]);
|
||||
return key;
|
||||
},
|
||||
}: CacheConfiguratorObj),
|
||||
);
|
||||
|
||||
return { cache, result, deactivate };
|
||||
}
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
// @flow
|
||||
|
||||
export function getEnv(defaultValue: string = "development"): string {
|
||||
return process.env.BABEL_ENV
|
||||
|| process.env.NODE_ENV
|
||||
|| defaultValue;
|
||||
return process.env.BABEL_ENV || process.env.NODE_ENV || defaultValue;
|
||||
}
|
||||
|
||||
@@ -5,13 +5,13 @@ import manageOptions from "./option-manager";
|
||||
|
||||
export type ResolvedConfig = {
|
||||
options: Object,
|
||||
passes: Array<Array<[ Plugin, ?{} ]>>,
|
||||
passes: Array<Array<[Plugin, ?{}]>>,
|
||||
};
|
||||
|
||||
/**
|
||||
* Standard API for loading Babel configuration data. Not for public consumption.
|
||||
*/
|
||||
export default function loadConfig(opts: mixed): ResolvedConfig|null {
|
||||
export default function loadConfig(opts: mixed): ResolvedConfig | null {
|
||||
if (opts != null && typeof opts !== "object") {
|
||||
throw new Error("Babel options must be an object, null, or undefined");
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
// @flow
|
||||
|
||||
import buildDebug from "debug";
|
||||
import path from "path";
|
||||
import fs from "fs";
|
||||
import json5 from "json5";
|
||||
@@ -7,6 +8,8 @@ import resolve from "resolve";
|
||||
import { getEnv } from "../../helpers/environment";
|
||||
import { makeStrongCache } from "../../caching";
|
||||
|
||||
const debug = buildDebug("babel:config:loading:files:configuration");
|
||||
|
||||
type ConfigFile = {
|
||||
filepath: string,
|
||||
dirname: string,
|
||||
@@ -31,6 +34,7 @@ export function findConfigs(dirname: string): Array<ConfigFile> {
|
||||
const ignore = readIgnoreConfig(ignoreLoc);
|
||||
|
||||
if (ignore) {
|
||||
debug("Found ignore %o from %o.", ignore.filepath, dirname);
|
||||
confs.push(ignore);
|
||||
foundIgnore = true;
|
||||
}
|
||||
@@ -41,19 +45,23 @@ export function findConfigs(dirname: string): Array<ConfigFile> {
|
||||
BABELRC_FILENAME,
|
||||
BABELRC_JS_FILENAME,
|
||||
PACKAGE_FILENAME,
|
||||
].reduce((previousConfig: ConfigFile|null, name) => {
|
||||
].reduce((previousConfig: ConfigFile | null, name) => {
|
||||
const filepath = path.join(loc, name);
|
||||
const config = readConfig(filepath);
|
||||
|
||||
if (config && previousConfig) {
|
||||
throw new Error(`Multiple configuration files found. Please remove one:\n- ${
|
||||
path.basename(previousConfig.filepath)}\n- ${name}\nfrom ${loc}`);
|
||||
throw new Error(
|
||||
`Multiple configuration files found. Please remove one:\n- ${path.basename(
|
||||
previousConfig.filepath,
|
||||
)}\n- ${name}\nfrom ${loc}`,
|
||||
);
|
||||
}
|
||||
|
||||
return config || previousConfig;
|
||||
}, null);
|
||||
|
||||
if (conf) {
|
||||
debug("Found configuration %o from %o.", conf.filepath, dirname);
|
||||
confs.push(conf);
|
||||
foundConfig = true;
|
||||
}
|
||||
@@ -73,8 +81,11 @@ export function loadConfig(name: string, dirname: string): ConfigFile {
|
||||
const filepath = resolve.sync(name, { basedir: dirname });
|
||||
|
||||
const conf = readConfig(filepath);
|
||||
if (!conf) throw new Error(`Config file ${filepath} contains no configuration data`);
|
||||
if (!conf) {
|
||||
throw new Error(`Config file ${filepath} contains no configuration data`);
|
||||
}
|
||||
|
||||
debug("Loaded config %o from $o.", name, dirname);
|
||||
return conf;
|
||||
}
|
||||
|
||||
@@ -83,23 +94,47 @@ export function loadConfig(name: string, dirname: string): ConfigFile {
|
||||
* throw if there are parsing errors while loading a config.
|
||||
*/
|
||||
function readConfig(filepath) {
|
||||
return (path.extname(filepath) === ".js") ? readConfigJS(filepath) : readConfigFile(filepath);
|
||||
return path.extname(filepath) === ".js"
|
||||
? readConfigJS(filepath)
|
||||
: readConfigFile(filepath);
|
||||
}
|
||||
|
||||
const LOADING_CONFIGS = new Set();
|
||||
const readConfigJS = makeStrongCache((filepath, cache) => {
|
||||
if (!fs.existsSync(filepath)) {
|
||||
cache.forever();
|
||||
return null;
|
||||
}
|
||||
|
||||
// The `require()` call below can make this code reentrant if a require hook like babel-register has been
|
||||
// loaded into the system. That would cause Babel to attempt to compile the `.babelrc.js` file as it loads
|
||||
// below. To cover this case, we auto-ignore re-entrant config processing.
|
||||
if (LOADING_CONFIGS.has(filepath)) {
|
||||
cache.never();
|
||||
|
||||
debug("Auto-ignoring usage of config %o.", filepath);
|
||||
return {
|
||||
filepath,
|
||||
dirname: path.dirname(filepath),
|
||||
options: {},
|
||||
};
|
||||
}
|
||||
|
||||
let options;
|
||||
try {
|
||||
LOADING_CONFIGS.add(filepath);
|
||||
|
||||
// $FlowIssue
|
||||
const configModule = (require(filepath): mixed);
|
||||
options = configModule && configModule.__esModule ? (configModule.default || undefined) : configModule;
|
||||
options =
|
||||
configModule && configModule.__esModule
|
||||
? configModule.default || undefined
|
||||
: configModule;
|
||||
} catch (err) {
|
||||
err.message = `${filepath}: Error while loading config - ${err.message}`;
|
||||
throw err;
|
||||
} finally {
|
||||
LOADING_CONFIGS.delete(filepath);
|
||||
}
|
||||
|
||||
if (typeof options === "function") {
|
||||
@@ -113,7 +148,9 @@ const readConfigJS = makeStrongCache((filepath, cache) => {
|
||||
}
|
||||
|
||||
if (!options || typeof options !== "object" || Array.isArray(options)) {
|
||||
throw new Error(`${filepath}: Configuration should be an exported JavaScript object.`);
|
||||
throw new Error(
|
||||
`${filepath}: Configuration should be an exported JavaScript object.`,
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -144,8 +181,12 @@ const readConfigFile = makeStaticFileCache((filepath, content) => {
|
||||
if (!options) throw new Error(`${filepath}: No config detected`);
|
||||
}
|
||||
|
||||
if (typeof options !== "object") throw new Error(`${filepath}: Config returned typeof ${typeof options}`);
|
||||
if (Array.isArray(options)) throw new Error(`${filepath}: Expected config object but found array`);
|
||||
if (typeof options !== "object") {
|
||||
throw new Error(`${filepath}: Config returned typeof ${typeof options}`);
|
||||
}
|
||||
if (Array.isArray(options)) {
|
||||
throw new Error(`${filepath}: Expected config object but found array`);
|
||||
}
|
||||
|
||||
return {
|
||||
filepath,
|
||||
@@ -157,8 +198,8 @@ const readConfigFile = makeStaticFileCache((filepath, content) => {
|
||||
const readIgnoreConfig = makeStaticFileCache((filepath, content) => {
|
||||
const ignore = content
|
||||
.split("\n")
|
||||
.map((line) => line.replace(/#(.*?)$/, "").trim())
|
||||
.filter((line) => !!line);
|
||||
.map(line => line.replace(/#(.*?)$/, "").trim())
|
||||
.filter(line => !!line);
|
||||
|
||||
return {
|
||||
filepath,
|
||||
@@ -167,7 +208,7 @@ const readIgnoreConfig = makeStaticFileCache((filepath, content) => {
|
||||
};
|
||||
});
|
||||
|
||||
function makeStaticFileCache<T>(fn: (string, string) => T): (string) => T|null {
|
||||
function makeStaticFileCache<T>(fn: (string, string) => T): string => T | null {
|
||||
return makeStrongCache((filepath, cache) => {
|
||||
if (cache.invalidate(() => fileMtime(filepath)) === null) {
|
||||
cache.forever();
|
||||
@@ -178,7 +219,7 @@ function makeStaticFileCache<T>(fn: (string, string) => T): (string) => T|null {
|
||||
});
|
||||
}
|
||||
|
||||
function fileMtime(filepath: string): number|null {
|
||||
function fileMtime(filepath: string): number | null {
|
||||
try {
|
||||
return +fs.statSync(filepath).mtime;
|
||||
} catch (e) {
|
||||
|
||||
@@ -16,27 +16,47 @@ export function loadConfig(name: string, dirname: string): ConfigFile {
|
||||
}
|
||||
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
export function resolvePlugin(name: string, dirname: string): string|null {
|
||||
export function resolvePlugin(name: string, dirname: string): string | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
export function resolvePreset(name: string, dirname: string): string|null {
|
||||
export function resolvePreset(name: string, dirname: string): string | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
export function loadPlugin(name: string, dirname: string): { filepath: string, value: mixed } {
|
||||
throw new Error(`Cannot load plugin ${name} relative to ${dirname} in a browser`);
|
||||
export function loadPlugin(
|
||||
name: string,
|
||||
dirname: string,
|
||||
): { filepath: string, value: mixed } {
|
||||
throw new Error(
|
||||
`Cannot load plugin ${name} relative to ${dirname} in a browser`,
|
||||
);
|
||||
}
|
||||
|
||||
export function loadPreset(name: string, dirname: string): { filepath: string, value: mixed } {
|
||||
throw new Error(`Cannot load preset ${name} relative to ${dirname} in a browser`);
|
||||
export function loadPreset(
|
||||
name: string,
|
||||
dirname: string,
|
||||
): { filepath: string, value: mixed } {
|
||||
throw new Error(
|
||||
`Cannot load preset ${name} relative to ${dirname} in a browser`,
|
||||
);
|
||||
}
|
||||
|
||||
export function loadParser(name: string, dirname: string): { filepath: string, value: Function } {
|
||||
throw new Error(`Cannot load parser ${name} relative to ${dirname} in a browser`);
|
||||
export function loadParser(
|
||||
name: string,
|
||||
dirname: string,
|
||||
): { filepath: string, value: Function } {
|
||||
throw new Error(
|
||||
`Cannot load parser ${name} relative to ${dirname} in a browser`,
|
||||
);
|
||||
}
|
||||
|
||||
export function loadGenerator(name: string, dirname: string): { filepath: string, value: Function } {
|
||||
throw new Error(`Cannot load generator ${name} relative to ${dirname} in a browser`);
|
||||
export function loadGenerator(
|
||||
name: string,
|
||||
dirname: string,
|
||||
): { filepath: string, value: Function } {
|
||||
throw new Error(
|
||||
`Cannot load generator ${name} relative to ${dirname} in a browser`,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ import typeof * as indexType from "./index";
|
||||
|
||||
// Kind of gross, but essentially asserting that the exports of this module are the same as the
|
||||
// exports of index-browser, since this file may be replaced at bundle time with index-browser.
|
||||
((({}: any) : $Exact<indexBrowserType>): $Exact<indexType>);
|
||||
((({}: any): $Exact<indexBrowserType>): $Exact<indexType>);
|
||||
|
||||
export * from "./configuration";
|
||||
export * from "./plugins";
|
||||
|
||||
@@ -4,99 +4,148 @@
|
||||
* This file handles all logic for converting string-based configuration references into loaded objects.
|
||||
*/
|
||||
|
||||
import buildDebug from "debug";
|
||||
import resolve from "resolve";
|
||||
import path from "path";
|
||||
|
||||
const EXACT_RE = /^module:/;
|
||||
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 debug = buildDebug("babel:config:loading:files:plugins");
|
||||
|
||||
export function resolvePlugin(name: string, dirname: string): string|null {
|
||||
const EXACT_RE = /^module:/;
|
||||
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-|[^/]+\/)/;
|
||||
|
||||
export function resolvePlugin(name: string, dirname: string): string | null {
|
||||
return resolveStandardizedName("plugin", name, dirname);
|
||||
}
|
||||
|
||||
export function resolvePreset(name: string, dirname: string): string|null {
|
||||
export function resolvePreset(name: string, dirname: string): string | null {
|
||||
return resolveStandardizedName("preset", name, dirname);
|
||||
}
|
||||
|
||||
export function loadPlugin(name: string, dirname: string): { filepath: string, value: mixed } {
|
||||
export function loadPlugin(
|
||||
name: string,
|
||||
dirname: string,
|
||||
): { filepath: string, value: mixed } {
|
||||
const filepath = resolvePlugin(name, dirname);
|
||||
if (!filepath) throw new Error(`Plugin ${name} not found relative to ${dirname}`);
|
||||
if (!filepath) {
|
||||
throw new Error(`Plugin ${name} not found relative to ${dirname}`);
|
||||
}
|
||||
|
||||
return {
|
||||
filepath,
|
||||
value: requireModule(filepath),
|
||||
};
|
||||
const value = requireModule("plugin", filepath);
|
||||
debug("Loaded plugin %o from %o.", name, dirname);
|
||||
|
||||
return { filepath, value };
|
||||
}
|
||||
|
||||
export function loadPreset(name: string, dirname: string): { filepath: string, value: mixed } {
|
||||
export function loadPreset(
|
||||
name: string,
|
||||
dirname: string,
|
||||
): { filepath: string, value: mixed } {
|
||||
const filepath = resolvePreset(name, dirname);
|
||||
if (!filepath) throw new Error(`Preset ${name} not found relative to ${dirname}`);
|
||||
if (!filepath) {
|
||||
throw new Error(`Preset ${name} not found relative to ${dirname}`);
|
||||
}
|
||||
|
||||
return {
|
||||
filepath,
|
||||
value: requireModule(filepath),
|
||||
};
|
||||
const value = requireModule("preset", filepath);
|
||||
|
||||
debug("Loaded preset %o from %o.", name, dirname);
|
||||
|
||||
return { filepath, value };
|
||||
}
|
||||
|
||||
export function loadParser(name: string, dirname: string): { filepath: string, value: Function } {
|
||||
export function loadParser(
|
||||
name: string,
|
||||
dirname: string,
|
||||
): { filepath: string, value: Function } {
|
||||
const filepath = resolve.sync(name, { basedir: dirname });
|
||||
|
||||
const mod = requireModule(filepath);
|
||||
const mod = requireModule("parser", filepath);
|
||||
|
||||
if (!mod) {
|
||||
throw new Error(`Parser ${name} relative to ${dirname} does not export an object`);
|
||||
throw new Error(
|
||||
`Parser ${name} relative to ${dirname} does not export an object`,
|
||||
);
|
||||
}
|
||||
if (typeof mod.parse !== "function") {
|
||||
throw new Error(`Parser ${name} relative to ${dirname} does not export a .parse function`);
|
||||
throw new Error(
|
||||
`Parser ${name} relative to ${dirname} does not export a .parse function`,
|
||||
);
|
||||
}
|
||||
const value = mod.parse;
|
||||
|
||||
debug("Loaded parser %o from %o.", name, dirname);
|
||||
|
||||
return {
|
||||
filepath,
|
||||
value: mod.parse,
|
||||
value,
|
||||
};
|
||||
}
|
||||
|
||||
export function loadGenerator(name: string, dirname: string): { filepath: string, value: Function } {
|
||||
export function loadGenerator(
|
||||
name: string,
|
||||
dirname: string,
|
||||
): { filepath: string, value: Function } {
|
||||
const filepath = resolve.sync(name, { basedir: dirname });
|
||||
|
||||
const mod = requireModule(filepath);
|
||||
const mod = requireModule("generator", filepath);
|
||||
|
||||
if (!mod) {
|
||||
throw new Error(`Generator ${name} relative to ${dirname} does not export an object`);
|
||||
throw new Error(
|
||||
`Generator ${name} relative to ${dirname} does not export an object`,
|
||||
);
|
||||
}
|
||||
if (typeof mod.print !== "function") {
|
||||
throw new Error(`Generator ${name} relative to ${dirname} does not export a .print function`);
|
||||
throw new Error(
|
||||
`Generator ${name} relative to ${dirname} does not export a .print function`,
|
||||
);
|
||||
}
|
||||
const value = mod.print;
|
||||
|
||||
debug("Loaded generator %o from %o.", name, dirname);
|
||||
|
||||
return {
|
||||
filepath,
|
||||
value: mod.print,
|
||||
value,
|
||||
};
|
||||
}
|
||||
|
||||
function standardizeName(type: "plugin"|"preset", name: string) {
|
||||
function standardizeName(type: "plugin" | "preset", name: string) {
|
||||
// Let absolute and relative paths through.
|
||||
if (path.isAbsolute(name)) return name;
|
||||
|
||||
const isPreset = type === "preset";
|
||||
|
||||
return name
|
||||
// foo -> babel-preset-foo
|
||||
.replace(isPreset ? BABEL_PRESET_PREFIX_RE : BABEL_PLUGIN_PREFIX_RE, `babel-${type}-`)
|
||||
// @babel/es2015 -> @babel/preset-es2015
|
||||
.replace(isPreset ? BABEL_PRESET_ORG_RE : BABEL_PLUGIN_ORG_RE, `$1${type}-`)
|
||||
// @foo/mypreset -> @foo/babel-preset-mypreset
|
||||
.replace(isPreset ? OTHER_PRESET_ORG_RE : OTHER_PLUGIN_ORG_RE, `$1babel-${type}-`)
|
||||
// module:mypreset -> mypreset
|
||||
.replace(EXACT_RE, "");
|
||||
return (
|
||||
name
|
||||
// foo -> babel-preset-foo
|
||||
.replace(
|
||||
isPreset ? BABEL_PRESET_PREFIX_RE : BABEL_PLUGIN_PREFIX_RE,
|
||||
`babel-${type}-`,
|
||||
)
|
||||
// @babel/es2015 -> @babel/preset-es2015
|
||||
.replace(
|
||||
isPreset ? BABEL_PRESET_ORG_RE : BABEL_PLUGIN_ORG_RE,
|
||||
`$1${type}-`,
|
||||
)
|
||||
// @foo/mypreset -> @foo/babel-preset-mypreset
|
||||
.replace(
|
||||
isPreset ? OTHER_PRESET_ORG_RE : OTHER_PLUGIN_ORG_RE,
|
||||
`$1babel-${type}-`,
|
||||
)
|
||||
// module:mypreset -> mypreset
|
||||
.replace(EXACT_RE, "")
|
||||
);
|
||||
}
|
||||
|
||||
function resolveStandardizedName(type: "plugin"|"preset", name: string, dirname: string = process.cwd()) {
|
||||
function resolveStandardizedName(
|
||||
type: "plugin" | "preset",
|
||||
name: string,
|
||||
dirname: string = process.cwd(),
|
||||
) {
|
||||
const standardizedName = standardizeName(type, name);
|
||||
|
||||
try {
|
||||
@@ -109,7 +158,7 @@ function resolveStandardizedName(type: "plugin"|"preset", name: string, dirname:
|
||||
try {
|
||||
resolve.sync(name, { basedir: dirname });
|
||||
resolvedOriginal = true;
|
||||
} catch (e2) { }
|
||||
} catch (e2) {}
|
||||
|
||||
if (resolvedOriginal) {
|
||||
// eslint-disable-next-line max-len
|
||||
@@ -119,9 +168,11 @@ function resolveStandardizedName(type: "plugin"|"preset", name: string, dirname:
|
||||
|
||||
let resolvedBabel = false;
|
||||
try {
|
||||
resolve.sync(standardizeName(type, "@babel/" + name), { basedir: dirname });
|
||||
resolve.sync(standardizeName(type, "@babel/" + name), {
|
||||
basedir: dirname,
|
||||
});
|
||||
resolvedBabel = true;
|
||||
} catch (e2) { }
|
||||
} catch (e2) {}
|
||||
|
||||
if (resolvedBabel) {
|
||||
// eslint-disable-next-line max-len
|
||||
@@ -133,7 +184,7 @@ function resolveStandardizedName(type: "plugin"|"preset", name: string, dirname:
|
||||
try {
|
||||
resolve.sync(standardizeName(oppositeType, name), { basedir: dirname });
|
||||
resolvedOppositeType = true;
|
||||
} catch (e2) { }
|
||||
} catch (e2) {}
|
||||
|
||||
if (resolvedOppositeType) {
|
||||
// eslint-disable-next-line max-len
|
||||
@@ -144,7 +195,20 @@ function resolveStandardizedName(type: "plugin"|"preset", name: string, dirname:
|
||||
}
|
||||
}
|
||||
|
||||
function requireModule(name: string): mixed {
|
||||
// $FlowIssue
|
||||
return require(name);
|
||||
const LOADING_MODULES = new Set();
|
||||
function requireModule(type: string, name: string): mixed {
|
||||
if (LOADING_MODULES.has(name)) {
|
||||
throw new Error(
|
||||
// eslint-disable-next-line max-len
|
||||
`Reentrant ${type} detected trying to load "${name}". This module is not ignored and is trying to load itself while compiling itself, leading to a dependency cycle. We recommend adding it to your "ignore" list in your babelrc, or to a .babelignore.`,
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
LOADING_MODULES.add(name);
|
||||
// $FlowIssue
|
||||
return require(name);
|
||||
} finally {
|
||||
LOADING_MODULES.delete(name);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
// @flow
|
||||
|
||||
import * as context from "../index";
|
||||
import Plugin from "./plugin";
|
||||
import * as messages from "babel-messages";
|
||||
@@ -11,17 +9,23 @@ import path from "path";
|
||||
import traverse from "babel-traverse";
|
||||
import clone from "lodash/clone";
|
||||
|
||||
import { loadPlugin, loadPreset, loadParser, loadGenerator } from "./loading/files";
|
||||
import {
|
||||
loadPlugin,
|
||||
loadPreset,
|
||||
loadParser,
|
||||
loadGenerator,
|
||||
} from "./loading/files";
|
||||
|
||||
type MergeOptions = {
|
||||
+type: "arguments"|"options"|"preset",
|
||||
+type: "arguments" | "options" | "preset",
|
||||
options: {},
|
||||
alias: string,
|
||||
loc: string,
|
||||
dirname: string
|
||||
dirname: string,
|
||||
};
|
||||
|
||||
const optionNames = new Set([
|
||||
"relative",
|
||||
"filename",
|
||||
"filenameRelative",
|
||||
"inputSourceMap",
|
||||
@@ -74,8 +78,8 @@ const ALLOWED_PLUGIN_KEYS = new Set([
|
||||
|
||||
export default function manageOptions(opts: {}): {
|
||||
options: Object,
|
||||
passes: Array<Array<[ Plugin, ?{} ]>>,
|
||||
}|null {
|
||||
passes: Array<Array<[Plugin, ?{}]>>,
|
||||
} | null {
|
||||
return new OptionManager().init(opts);
|
||||
}
|
||||
|
||||
@@ -100,9 +104,12 @@ class OptionManager {
|
||||
mergeOptions(config: MergeOptions, pass?: Array<[Plugin, ?{}]>) {
|
||||
const result = loadConfig(config);
|
||||
|
||||
const plugins = result.plugins.map((descriptor) => loadPluginDescriptor(descriptor));
|
||||
const presets = result.presets.map((descriptor) => loadPresetDescriptor(descriptor));
|
||||
|
||||
const plugins = result.plugins.map(descriptor =>
|
||||
loadPluginDescriptor(descriptor),
|
||||
);
|
||||
const presets = result.presets.map(descriptor =>
|
||||
loadPresetDescriptor(descriptor),
|
||||
);
|
||||
|
||||
if (
|
||||
config.options.passPerPreset != null &&
|
||||
@@ -148,7 +155,8 @@ class OptionManager {
|
||||
// There are a few case where thrown errors will try to annotate themselves multiple times, so
|
||||
// to keep things simple we just bail out if re-wrapping the message.
|
||||
if (!/^\[BABEL\]/.test(e.message)) {
|
||||
const filename = typeof opts.filename === "string" ? opts.filename : null;
|
||||
const filename =
|
||||
typeof opts.filename === "string" ? opts.filename : null;
|
||||
e.message = `[BABEL] ${filename || "unknown"}: ${e.message}`;
|
||||
}
|
||||
|
||||
@@ -160,9 +168,10 @@ class OptionManager {
|
||||
// Tack the passes onto the object itself so that, if this object is passed back to Babel a second time,
|
||||
// it will be in the right structure to not change behavior.
|
||||
opts.plugins = this.passes[0];
|
||||
opts.presets = this.passes.slice(1)
|
||||
.filter((plugins) => plugins.length > 0)
|
||||
.map((plugins) => ({ plugins }));
|
||||
opts.presets = this.passes
|
||||
.slice(1)
|
||||
.filter(plugins => plugins.length > 0)
|
||||
.map(plugins => ({ plugins }));
|
||||
|
||||
if (opts.inputSourceMap) {
|
||||
opts.sourceMaps = true;
|
||||
@@ -199,7 +208,7 @@ class OptionManager {
|
||||
}
|
||||
|
||||
type BasicDescriptor = {
|
||||
value: {}|Function,
|
||||
value: {} | Function,
|
||||
options: ?{},
|
||||
dirname: string,
|
||||
alias: string,
|
||||
@@ -209,19 +218,28 @@ type BasicDescriptor = {
|
||||
/**
|
||||
* Load and validate the given config into a set of options, plugins, and presets.
|
||||
*/
|
||||
function loadConfig(config): {
|
||||
function loadConfig(
|
||||
config,
|
||||
): {
|
||||
options: {},
|
||||
plugins: Array<BasicDescriptor>,
|
||||
presets: Array<BasicDescriptor>,
|
||||
} {
|
||||
const options = normalizeOptions(config);
|
||||
|
||||
if (config.options.plugins != null && !Array.isArray(config.options.plugins)) {
|
||||
if (
|
||||
config.options.plugins != null &&
|
||||
!Array.isArray(config.options.plugins)
|
||||
) {
|
||||
throw new Error(".plugins should be an array, null, or undefined");
|
||||
}
|
||||
|
||||
const plugins = (config.options.plugins || []).map((plugin, index) => {
|
||||
const { filepath, value, options } = normalizePair(plugin, loadPlugin, config.dirname);
|
||||
const { filepath, value, options } = normalizePair(
|
||||
plugin,
|
||||
loadPlugin,
|
||||
config.dirname,
|
||||
);
|
||||
|
||||
return {
|
||||
alias: filepath || `${config.loc}$${index}`,
|
||||
@@ -232,12 +250,19 @@ function loadConfig(config): {
|
||||
};
|
||||
});
|
||||
|
||||
if (config.options.presets != null && !Array.isArray(config.options.presets)) {
|
||||
if (
|
||||
config.options.presets != null &&
|
||||
!Array.isArray(config.options.presets)
|
||||
) {
|
||||
throw new Error(".presets should be an array, null, or undefined");
|
||||
}
|
||||
|
||||
const presets = (config.options.presets || []).map((preset, index) => {
|
||||
const { filepath, value, options } = normalizePair(preset, loadPreset, config.dirname);
|
||||
const { filepath, value, options } = normalizePair(
|
||||
preset,
|
||||
loadPreset,
|
||||
config.dirname,
|
||||
);
|
||||
|
||||
return {
|
||||
alias: filepath || `${config.loc}$${index}`,
|
||||
@@ -255,7 +280,9 @@ function loadConfig(config): {
|
||||
* Load a generic plugin/preset from the given descriptor loaded from the config object.
|
||||
*/
|
||||
function loadDescriptor(descriptor, skipOptions) {
|
||||
if (typeof descriptor.value !== "function") return { value: descriptor.value, descriptor };
|
||||
if (typeof descriptor.value !== "function") {
|
||||
return { value: descriptor.value, descriptor };
|
||||
}
|
||||
|
||||
const { value, options } = descriptor;
|
||||
let item;
|
||||
@@ -266,7 +293,9 @@ function loadDescriptor(descriptor, skipOptions) {
|
||||
item = value(context, options, { dirname: descriptor.dirname });
|
||||
}
|
||||
} catch (e) {
|
||||
if (descriptor.alias) e.message += ` (While processing: ${JSON.stringify(descriptor.alias)})`;
|
||||
if (descriptor.alias) {
|
||||
e.message += ` (While processing: ${JSON.stringify(descriptor.alias)})`;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
|
||||
@@ -282,26 +311,37 @@ function loadDescriptor(descriptor, skipOptions) {
|
||||
*/
|
||||
const PLUGIN_CACHE = new WeakMap();
|
||||
function loadPluginDescriptor(descriptor) {
|
||||
if (descriptor.value instanceof Plugin) return [ descriptor.value, descriptor.options ];
|
||||
if (descriptor.value instanceof Plugin) {
|
||||
return [descriptor.value, descriptor.options];
|
||||
}
|
||||
|
||||
let result = PLUGIN_CACHE.get(descriptor.value);
|
||||
if (!result) {
|
||||
result = instantiatePlugin(loadDescriptor(descriptor, true /* skipOptions */));
|
||||
result = instantiatePlugin(
|
||||
loadDescriptor(descriptor, true /* skipOptions */),
|
||||
);
|
||||
PLUGIN_CACHE.set(descriptor.value, result);
|
||||
}
|
||||
|
||||
return [ result, descriptor.options];
|
||||
return [result, descriptor.options];
|
||||
}
|
||||
|
||||
function instantiatePlugin({ value: pluginObj, descriptor }) {
|
||||
Object.keys(pluginObj).forEach((key) => {
|
||||
Object.keys(pluginObj).forEach(key => {
|
||||
if (!ALLOWED_PLUGIN_KEYS.has(key)) {
|
||||
throw new Error(messages.get("pluginInvalidProperty", descriptor.alias, key));
|
||||
throw new Error(
|
||||
messages.get("pluginInvalidProperty", descriptor.alias, key),
|
||||
);
|
||||
}
|
||||
});
|
||||
if (pluginObj.visitor && (pluginObj.visitor.enter || pluginObj.visitor.exit)) {
|
||||
throw new Error("Plugins aren't allowed to specify catch-all enter/exit handlers. " +
|
||||
"Please target individual nodes.");
|
||||
if (
|
||||
pluginObj.visitor &&
|
||||
(pluginObj.visitor.enter || pluginObj.visitor.exit)
|
||||
) {
|
||||
throw new Error(
|
||||
"Plugins aren't allowed to specify catch-all enter/exit handlers. " +
|
||||
"Please target individual nodes.",
|
||||
);
|
||||
}
|
||||
|
||||
const plugin = Object.assign({}, pluginObj, {
|
||||
@@ -325,8 +365,14 @@ function instantiatePlugin({ value: pluginObj, descriptor }) {
|
||||
|
||||
plugin.pre = chain(inherits.pre, plugin.pre);
|
||||
plugin.post = chain(inherits.post, plugin.post);
|
||||
plugin.manipulateOptions = chain(inherits.manipulateOptions, plugin.manipulateOptions);
|
||||
plugin.visitor = traverse.visitors.merge([inherits.visitor, plugin.visitor]);
|
||||
plugin.manipulateOptions = chain(
|
||||
inherits.manipulateOptions,
|
||||
plugin.manipulateOptions,
|
||||
);
|
||||
plugin.visitor = traverse.visitors.merge([
|
||||
inherits.visitor,
|
||||
plugin.visitor,
|
||||
]);
|
||||
}
|
||||
|
||||
return new Plugin(plugin, descriptor.alias);
|
||||
@@ -371,10 +417,18 @@ function normalizeOptions(config) {
|
||||
}
|
||||
|
||||
if (type === "preset") {
|
||||
if (options.only !== undefined) throw new Error(`${alias}.only is not supported in a preset`);
|
||||
if (options.ignore !== undefined) throw new Error(`${alias}.ignore is not supported in a preset`);
|
||||
if (options.extends !== undefined) throw new Error(`${alias}.extends is not supported in a preset`);
|
||||
if (options.env !== undefined) throw new Error(`${alias}.env is not supported in a preset`);
|
||||
if (options.only !== undefined) {
|
||||
throw new Error(`${alias}.only is not supported in a preset`);
|
||||
}
|
||||
if (options.ignore !== undefined) {
|
||||
throw new Error(`${alias}.ignore is not supported in a preset`);
|
||||
}
|
||||
if (options.extends !== undefined) {
|
||||
throw new Error(`${alias}.extends is not supported in a preset`);
|
||||
}
|
||||
if (options.env !== undefined) {
|
||||
throw new Error(`${alias}.env is not supported in a preset`);
|
||||
}
|
||||
}
|
||||
|
||||
if (options.sourceMap !== undefined) {
|
||||
@@ -390,7 +444,10 @@ function normalizeOptions(config) {
|
||||
// check for an unknown option
|
||||
if (!optionNames.has(key)) {
|
||||
if (removed[key]) {
|
||||
throw new ReferenceError(`Using removed Babel 5 option: ${alias}.${key} - ${removed[key].message}`);
|
||||
throw new ReferenceError(
|
||||
`Using removed Babel 5 option: ${alias}.${key} - ${removed[key]
|
||||
.message}`,
|
||||
);
|
||||
} else {
|
||||
// eslint-disable-next-line max-len
|
||||
const unknownOptErr = `Unknown option: ${alias}.${key}. Check out http://babeljs.io/docs/usage/options/ for more information about options.`;
|
||||
@@ -402,12 +459,21 @@ function normalizeOptions(config) {
|
||||
|
||||
if (options.parserOpts && typeof options.parserOpts.parser === "string") {
|
||||
options.parserOpts = Object.assign({}, options.parserOpts);
|
||||
options.parserOpts.parser = loadParser(options.parserOpts.parser, config.dirname).value;
|
||||
options.parserOpts.parser = loadParser(
|
||||
options.parserOpts.parser,
|
||||
config.dirname,
|
||||
).value;
|
||||
}
|
||||
|
||||
if (options.generatorOpts && typeof options.generatorOpts.generator === "string") {
|
||||
if (
|
||||
options.generatorOpts &&
|
||||
typeof options.generatorOpts.generator === "string"
|
||||
) {
|
||||
options.generatorOpts = Object.assign({}, options.generatorOpts);
|
||||
options.generatorOpts.generator = loadGenerator(options.generatorOpts.generator, config.dirname).value;
|
||||
options.generatorOpts.generator = loadGenerator(
|
||||
options.generatorOpts.generator,
|
||||
config.dirname,
|
||||
).value;
|
||||
}
|
||||
|
||||
delete options.passPerPreset;
|
||||
@@ -420,16 +486,22 @@ function normalizeOptions(config) {
|
||||
/**
|
||||
* Given a plugin/preset item, resolve it into a standard format.
|
||||
*/
|
||||
function normalizePair(pair: mixed, resolver, dirname): {
|
||||
filepath: string|null,
|
||||
value: {}|Function,
|
||||
function normalizePair(
|
||||
pair: mixed,
|
||||
resolver,
|
||||
dirname,
|
||||
): {
|
||||
filepath: string | null,
|
||||
value: {} | Function,
|
||||
options: ?{},
|
||||
} {
|
||||
let options;
|
||||
let value = pair;
|
||||
if (Array.isArray(pair)) {
|
||||
if (pair.length > 2) {
|
||||
throw new Error(`Unexpected extra options ${JSON.stringify(pair.slice(2))}.`);
|
||||
throw new Error(
|
||||
`Unexpected extra options ${JSON.stringify(pair.slice(2))}.`,
|
||||
);
|
||||
}
|
||||
|
||||
[value, options] = pair;
|
||||
@@ -437,10 +509,7 @@ function normalizePair(pair: mixed, resolver, dirname): {
|
||||
|
||||
let filepath = null;
|
||||
if (typeof value === "string") {
|
||||
({
|
||||
filepath,
|
||||
value,
|
||||
} = resolver(value, dirname));
|
||||
({ filepath, value } = resolver(value, dirname));
|
||||
}
|
||||
|
||||
if (!value) {
|
||||
@@ -456,11 +525,15 @@ function normalizePair(pair: mixed, resolver, dirname): {
|
||||
}
|
||||
|
||||
if (typeof value !== "object" && typeof value !== "function") {
|
||||
throw new Error(`Unsupported format: ${typeof value}. Expected an object or a function.`);
|
||||
throw new Error(
|
||||
`Unsupported format: ${typeof value}. Expected an object or a function.`,
|
||||
);
|
||||
}
|
||||
|
||||
if (options != null && typeof options !== "object") {
|
||||
throw new Error("Plugin/Preset options must be an object, null, or undefined");
|
||||
throw new Error(
|
||||
"Plugin/Preset options must be an object, null, or undefined",
|
||||
);
|
||||
}
|
||||
|
||||
return { filepath, value, options };
|
||||
|
||||
@@ -5,8 +5,13 @@ export default class Plugin {
|
||||
if (plugin.name != null && typeof plugin.name !== "string") {
|
||||
throw new Error("Plugin .name must be a string, null, or undefined");
|
||||
}
|
||||
if (plugin.manipulateOptions != null && typeof plugin.manipulateOptions !== "function") {
|
||||
throw new Error("Plugin .manipulateOptions must be a function, null, or undefined");
|
||||
if (
|
||||
plugin.manipulateOptions != null &&
|
||||
typeof plugin.manipulateOptions !== "function"
|
||||
) {
|
||||
throw new Error(
|
||||
"Plugin .manipulateOptions must be a function, null, or undefined",
|
||||
);
|
||||
}
|
||||
if (plugin.post != null && typeof plugin.post !== "function") {
|
||||
throw new Error("Plugin .post must be a function, null, or undefined");
|
||||
|
||||
@@ -2,52 +2,58 @@
|
||||
/* eslint max-len: "off" */
|
||||
|
||||
export default {
|
||||
"auxiliaryComment": {
|
||||
"message": "Use `auxiliaryCommentBefore` or `auxiliaryCommentAfter`",
|
||||
auxiliaryComment: {
|
||||
message: "Use `auxiliaryCommentBefore` or `auxiliaryCommentAfter`",
|
||||
},
|
||||
"blacklist": {
|
||||
"message": "Put the specific transforms you want in the `plugins` option",
|
||||
blacklist: {
|
||||
message: "Put the specific transforms you want in the `plugins` option",
|
||||
},
|
||||
"breakConfig": {
|
||||
"message": "This is not a necessary option in Babel 6",
|
||||
breakConfig: {
|
||||
message: "This is not a necessary option in Babel 6",
|
||||
},
|
||||
"experimental": {
|
||||
"message": "Put the specific transforms you want in the `plugins` option",
|
||||
experimental: {
|
||||
message: "Put the specific transforms you want in the `plugins` option",
|
||||
},
|
||||
"externalHelpers": {
|
||||
"message": "Use the `external-helpers` plugin instead. Check out http://babeljs.io/docs/plugins/external-helpers/",
|
||||
externalHelpers: {
|
||||
message:
|
||||
"Use the `external-helpers` plugin instead. Check out http://babeljs.io/docs/plugins/external-helpers/",
|
||||
},
|
||||
"extra": {
|
||||
"message": "",
|
||||
extra: {
|
||||
message: "",
|
||||
},
|
||||
"jsxPragma": {
|
||||
"message": "use the `pragma` option in the `react-jsx` plugin . Check out http://babeljs.io/docs/plugins/transform-react-jsx/",
|
||||
jsxPragma: {
|
||||
message:
|
||||
"use the `pragma` option in the `react-jsx` plugin . Check out http://babeljs.io/docs/plugins/transform-react-jsx/",
|
||||
},
|
||||
// "keepModuleIdExtensions": {
|
||||
// "message": ""
|
||||
// },
|
||||
"loose": {
|
||||
"message": "Specify the `loose` option for the relevant plugin you are using or use a preset that sets the option.",
|
||||
loose: {
|
||||
message:
|
||||
"Specify the `loose` option for the relevant plugin you are using or use a preset that sets the option.",
|
||||
},
|
||||
"metadataUsedHelpers": {
|
||||
"message": "Not required anymore as this is enabled by default",
|
||||
metadataUsedHelpers: {
|
||||
message: "Not required anymore as this is enabled by default",
|
||||
},
|
||||
"modules": {
|
||||
"message": "Use the corresponding module transform plugin in the `plugins` option. Check out http://babeljs.io/docs/plugins/#modules",
|
||||
modules: {
|
||||
message:
|
||||
"Use the corresponding module transform plugin in the `plugins` option. Check out http://babeljs.io/docs/plugins/#modules",
|
||||
},
|
||||
"nonStandard": {
|
||||
"message": "Use the `react-jsx` and `flow-strip-types` plugins to support JSX and Flow. Also check out the react preset http://babeljs.io/docs/plugins/preset-react/",
|
||||
nonStandard: {
|
||||
message:
|
||||
"Use the `react-jsx` and `flow-strip-types` plugins to support JSX and Flow. Also check out the react preset http://babeljs.io/docs/plugins/preset-react/",
|
||||
},
|
||||
"optional": {
|
||||
"message": "Put the specific transforms you want in the `plugins` option",
|
||||
optional: {
|
||||
message: "Put the specific transforms you want in the `plugins` option",
|
||||
},
|
||||
"sourceMapName": {
|
||||
"message": "Use the `sourceMapTarget` option",
|
||||
sourceMapName: {
|
||||
message: "Use the `sourceMapTarget` option",
|
||||
},
|
||||
"stage": {
|
||||
"message": "Check out the corresponding stage-x presets http://babeljs.io/docs/plugins/#presets",
|
||||
stage: {
|
||||
message:
|
||||
"Check out the corresponding stage-x presets http://babeljs.io/docs/plugins/#presets",
|
||||
},
|
||||
"whitelist": {
|
||||
"message": "Put the specific transforms you want in the `plugins` option",
|
||||
whitelist: {
|
||||
message: "Put the specific transforms you want in the `plugins` option",
|
||||
},
|
||||
};
|
||||
|
||||
@@ -12,7 +12,7 @@ export template from "babel-template";
|
||||
|
||||
import loadConfig from "./config";
|
||||
|
||||
export function loadOptions(opts): Object|null {
|
||||
export function loadOptions(opts): Object | null {
|
||||
const config = loadConfig(opts);
|
||||
|
||||
return config ? config.options : null;
|
||||
@@ -41,4 +41,10 @@ export {
|
||||
* Recommended set of compilable extensions. Not used in babel-core directly, but meant as
|
||||
* as an easy source for tooling making use of babel-core.
|
||||
*/
|
||||
export const DEFAULT_EXTENSIONS = Object.freeze([".js", ".jsx", ".es6", ".es", ".mjs"]);
|
||||
export const DEFAULT_EXTENSIONS = Object.freeze([
|
||||
".js",
|
||||
".jsx",
|
||||
".es6",
|
||||
".es",
|
||||
".mjs",
|
||||
]);
|
||||
|
||||
@@ -4,6 +4,8 @@ import * as messages from "babel-messages";
|
||||
import template from "babel-template";
|
||||
import * as t from "babel-types";
|
||||
|
||||
const keywordHelpers = ["typeof", "extends", "instanceof"];
|
||||
|
||||
const buildUmdWrapper = template(`
|
||||
(function (root, factory) {
|
||||
if (typeof define === "function" && define.amd) {
|
||||
@@ -20,28 +22,80 @@ const buildUmdWrapper = template(`
|
||||
|
||||
function buildGlobal(namespace, builder) {
|
||||
const body = [];
|
||||
const container = t.functionExpression(null, [t.identifier("global")], t.blockStatement(body));
|
||||
const container = t.functionExpression(
|
||||
null,
|
||||
[t.identifier("global")],
|
||||
t.blockStatement(body),
|
||||
);
|
||||
const tree = t.program([
|
||||
t.expressionStatement(t.callExpression(container, [helpers.get("selfGlobal")]))]);
|
||||
|
||||
body.push(t.variableDeclaration("var", [
|
||||
t.variableDeclarator(
|
||||
namespace,
|
||||
t.assignmentExpression("=", t.memberExpression(t.identifier("global"), namespace),
|
||||
t.objectExpression([]))
|
||||
t.expressionStatement(
|
||||
t.callExpression(container, [helpers.get("selfGlobal")]),
|
||||
),
|
||||
]));
|
||||
]);
|
||||
|
||||
body.push(
|
||||
t.variableDeclaration("var", [
|
||||
t.variableDeclarator(
|
||||
namespace,
|
||||
t.assignmentExpression(
|
||||
"=",
|
||||
t.memberExpression(t.identifier("global"), namespace),
|
||||
t.objectExpression([]),
|
||||
),
|
||||
),
|
||||
]),
|
||||
);
|
||||
|
||||
builder(body);
|
||||
|
||||
return tree;
|
||||
}
|
||||
|
||||
function buildModule(namespace, builder) {
|
||||
const body = [];
|
||||
builder(body);
|
||||
|
||||
const module = body
|
||||
.map(helper => {
|
||||
const originalIdentifier = helper.expression.left.property.name;
|
||||
const isKeywordHelper = keywordHelpers.indexOf(originalIdentifier) !== -1;
|
||||
const helperIndentifier = isKeywordHelper
|
||||
? `_${originalIdentifier}`
|
||||
: originalIdentifier;
|
||||
|
||||
const variableDeclaration = t.variableDeclaration("var", [
|
||||
t.variableDeclarator(
|
||||
t.identifier(helperIndentifier),
|
||||
helper.expression.right,
|
||||
),
|
||||
]);
|
||||
|
||||
return isKeywordHelper
|
||||
? variableDeclaration
|
||||
: t.exportNamedDeclaration(variableDeclaration, []);
|
||||
})
|
||||
.concat(
|
||||
t.exportNamedDeclaration(
|
||||
null,
|
||||
keywordHelpers.map(keywordHelper =>
|
||||
t.exportSpecifier(
|
||||
t.identifier(`_${keywordHelper}`),
|
||||
t.identifier(keywordHelper),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
return t.program(module);
|
||||
}
|
||||
|
||||
function buildUmd(namespace, builder) {
|
||||
const body = [];
|
||||
body.push(t.variableDeclaration("var", [
|
||||
t.variableDeclarator(namespace, t.identifier("global")),
|
||||
]));
|
||||
body.push(
|
||||
t.variableDeclaration("var", [
|
||||
t.variableDeclarator(namespace, t.identifier("global")),
|
||||
]),
|
||||
);
|
||||
|
||||
builder(body);
|
||||
|
||||
@@ -51,7 +105,7 @@ function buildUmd(namespace, builder) {
|
||||
BROWSER_ARGUMENTS: t.assignmentExpression(
|
||||
"=",
|
||||
t.memberExpression(t.identifier("root"), namespace),
|
||||
t.objectExpression([])
|
||||
t.objectExpression([]),
|
||||
),
|
||||
COMMON_ARGUMENTS: t.identifier("exports"),
|
||||
AMD_ARGUMENTS: t.arrayExpression([t.stringLiteral("exports")]),
|
||||
@@ -63,31 +117,39 @@ function buildUmd(namespace, builder) {
|
||||
|
||||
function buildVar(namespace, builder) {
|
||||
const body = [];
|
||||
body.push(t.variableDeclaration("var", [
|
||||
t.variableDeclarator(namespace, t.objectExpression([])),
|
||||
]));
|
||||
body.push(
|
||||
t.variableDeclaration("var", [
|
||||
t.variableDeclarator(namespace, t.objectExpression([])),
|
||||
]),
|
||||
);
|
||||
builder(body);
|
||||
body.push(t.expressionStatement(namespace));
|
||||
return t.program(body);
|
||||
}
|
||||
|
||||
function buildHelpers(body, namespace, whitelist) {
|
||||
helpers.list.forEach(function (name) {
|
||||
helpers.list.forEach(function(name) {
|
||||
if (whitelist && whitelist.indexOf(name) < 0) return;
|
||||
|
||||
const key = t.identifier(name);
|
||||
body.push(t.expressionStatement(
|
||||
t.assignmentExpression("=", t.memberExpression(namespace, key), helpers.get(name))
|
||||
));
|
||||
body.push(
|
||||
t.expressionStatement(
|
||||
t.assignmentExpression(
|
||||
"=",
|
||||
t.memberExpression(namespace, key),
|
||||
helpers.get(name),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
}
|
||||
export default function (
|
||||
export default function(
|
||||
whitelist?: Array<string>,
|
||||
outputType: "global" | "umd" | "var" = "global",
|
||||
outputType: "global" | "module" | "umd" | "var" = "global",
|
||||
) {
|
||||
const namespace = t.identifier("babelHelpers");
|
||||
|
||||
const builder = function (body) {
|
||||
const builder = function(body) {
|
||||
return buildHelpers(body, namespace, whitelist);
|
||||
};
|
||||
|
||||
@@ -95,6 +157,7 @@ export default function (
|
||||
|
||||
const build = {
|
||||
global: buildGlobal,
|
||||
module: buildModule,
|
||||
umd: buildUmd,
|
||||
var: buildVar,
|
||||
}[outputType];
|
||||
|
||||
@@ -7,7 +7,7 @@ import PluginPass from "../plugin-pass";
|
||||
import { NodePath, Hub, Scope } from "babel-traverse";
|
||||
import sourceMap from "source-map";
|
||||
import generate from "babel-generator";
|
||||
import codeFrame from "babel-code-frame";
|
||||
import { codeFrameColumns } from "babel-code-frame";
|
||||
import traverse from "babel-traverse";
|
||||
import Store from "../store";
|
||||
import { parse } from "babylon";
|
||||
@@ -45,7 +45,7 @@ export default class File extends Store {
|
||||
// passed babel-core's export object, which loads this file, and this 'loadConfig' loading plugins.
|
||||
INTERNAL_PLUGINS = loadConfig({
|
||||
babelrc: false,
|
||||
plugins: [ blockHoistPlugin ],
|
||||
plugins: [blockHoistPlugin],
|
||||
}).passes[0];
|
||||
}
|
||||
|
||||
@@ -61,7 +61,7 @@ export default class File extends Store {
|
||||
};
|
||||
|
||||
for (const pluginPairs of passes) {
|
||||
for (const [ plugin ] of pluginPairs) {
|
||||
for (const [plugin] of pluginPairs) {
|
||||
if (plugin.manipulateOptions) {
|
||||
plugin.manipulateOptions(this.opts, this.parserOpts, this);
|
||||
}
|
||||
@@ -150,7 +150,7 @@ export default class File extends Store {
|
||||
|
||||
if (opts.sourceRoot != null) {
|
||||
// remove sourceRoot from filename
|
||||
const sourceRootRegEx = new RegExp("^" + opts.sourceRoot + "\/?");
|
||||
const sourceRootRegEx = new RegExp("^" + opts.sourceRoot + "/?");
|
||||
filenameRelative = filenameRelative.replace(sourceRootRegEx, "");
|
||||
}
|
||||
|
||||
@@ -172,17 +172,40 @@ export default class File extends Store {
|
||||
|
||||
resolveModuleSource(source: string): string {
|
||||
const resolveModuleSource = this.opts.resolveModuleSource;
|
||||
if (resolveModuleSource) source = resolveModuleSource(source, this.opts.filename);
|
||||
if (resolveModuleSource) {
|
||||
source = resolveModuleSource(source, this.opts.filename);
|
||||
}
|
||||
return source;
|
||||
}
|
||||
|
||||
addImport(source: string, imported: string, name?: string = imported): Object {
|
||||
addImport(
|
||||
source: string,
|
||||
imported?: string = "",
|
||||
name?: string = imported,
|
||||
): Object | null {
|
||||
const prependDeclaration = (
|
||||
specifiers: Array<BabelNodeImportSpecifier>,
|
||||
): void => {
|
||||
const declar = t.importDeclaration(specifiers, t.stringLiteral(source));
|
||||
declar._blockHoist = 3;
|
||||
|
||||
this.path.unshiftContainer("body", declar);
|
||||
};
|
||||
|
||||
// import "module-name";
|
||||
if (!imported) {
|
||||
prependDeclaration([]);
|
||||
return null;
|
||||
}
|
||||
|
||||
const alias = `${source}:${imported}`;
|
||||
let id = this.dynamicImportIds[alias];
|
||||
|
||||
if (!id) {
|
||||
source = this.resolveModuleSource(source);
|
||||
id = this.dynamicImportIds[alias] = this.scope.generateUidIdentifier(name);
|
||||
id = this.dynamicImportIds[alias] = this.scope.generateUidIdentifier(
|
||||
name,
|
||||
);
|
||||
|
||||
const specifiers = [];
|
||||
|
||||
@@ -194,10 +217,7 @@ export default class File extends Store {
|
||||
specifiers.push(t.importSpecifier(id, t.identifier(imported)));
|
||||
}
|
||||
|
||||
const declar = t.importDeclaration(specifiers, t.stringLiteral(source));
|
||||
declar._blockHoist = 3;
|
||||
|
||||
this.path.unshiftContainer("body", declar);
|
||||
prependDeclaration(specifiers);
|
||||
}
|
||||
|
||||
return id;
|
||||
@@ -222,11 +242,12 @@ export default class File extends Store {
|
||||
}
|
||||
|
||||
const ref = getHelper(name);
|
||||
const uid = this.declarations[name] = this.scope.generateUidIdentifier(name);
|
||||
const uid = (this.declarations[name] = this.scope.generateUidIdentifier(
|
||||
name,
|
||||
));
|
||||
|
||||
if (t.isFunctionExpression(ref) && !ref.id) {
|
||||
ref.body._compact = true;
|
||||
ref._generated = true;
|
||||
ref.id = uid;
|
||||
ref.type = "FunctionDeclaration";
|
||||
this.path.unshiftContainer("body", ref);
|
||||
@@ -257,7 +278,9 @@ export default class File extends Store {
|
||||
const declar = this.declarations[name];
|
||||
if (declar) return declar;
|
||||
|
||||
const uid = this.declarations[name] = this.scope.generateUidIdentifier("templateObject");
|
||||
const uid = (this.declarations[name] = this.scope.generateUidIdentifier(
|
||||
"templateObject",
|
||||
));
|
||||
|
||||
const helperId = this.addHelper(helperName);
|
||||
const init = t.callExpression(helperId, [strings, raw]);
|
||||
@@ -270,7 +293,11 @@ export default class File extends Store {
|
||||
return uid;
|
||||
}
|
||||
|
||||
buildCodeFrameError(node: Object, msg: string, Error: typeof Error = SyntaxError): Error {
|
||||
buildCodeFrameError(
|
||||
node: Object,
|
||||
msg: string,
|
||||
Error: typeof Error = SyntaxError,
|
||||
): Error {
|
||||
const loc = node && (node.loc || node._loc);
|
||||
|
||||
const err = new Error(msg);
|
||||
@@ -280,7 +307,8 @@ export default class File extends Store {
|
||||
} else {
|
||||
traverse(node, errorVisitor, this.scope, err);
|
||||
|
||||
err.message += " (This is an error on an internal node. Probably an internal error";
|
||||
err.message +=
|
||||
" (This is an error on an internal node. Probably an internal error";
|
||||
|
||||
if (err.loc) {
|
||||
err.message += ". Location has been estimated.";
|
||||
@@ -308,7 +336,7 @@ export default class File extends Store {
|
||||
// single source file to a single output file.
|
||||
const source = outputMapConsumer.sources[0];
|
||||
|
||||
inputMapConsumer.eachMapping(function (mapping) {
|
||||
inputMapConsumer.eachMapping(function(mapping) {
|
||||
const generatedPosition = outputMapConsumer.generatedPositionFor({
|
||||
line: mapping.generatedLine,
|
||||
column: mapping.generatedColumn,
|
||||
@@ -318,10 +346,13 @@ export default class File extends Store {
|
||||
mergedGenerator.addMapping({
|
||||
source: mapping.source,
|
||||
|
||||
original: mapping.source == null ? null : {
|
||||
line: mapping.originalLine,
|
||||
column: mapping.originalColumn,
|
||||
},
|
||||
original:
|
||||
mapping.source == null
|
||||
? null
|
||||
: {
|
||||
line: mapping.originalLine,
|
||||
column: mapping.originalColumn,
|
||||
},
|
||||
|
||||
generated: generatedPosition,
|
||||
});
|
||||
@@ -385,15 +416,15 @@ export default class File extends Store {
|
||||
const passes = [];
|
||||
const visitors = [];
|
||||
|
||||
for (const [ plugin, pluginOpts ] of pluginPairs.concat(INTERNAL_PLUGINS)) {
|
||||
for (const [plugin, pluginOpts] of pluginPairs.concat(INTERNAL_PLUGINS)) {
|
||||
const pass = new PluginPass(this, plugin.key, pluginOpts);
|
||||
|
||||
passPairs.push([ plugin, pass ]);
|
||||
passPairs.push([plugin, pass]);
|
||||
passes.push(pass);
|
||||
visitors.push(plugin.visitor);
|
||||
}
|
||||
|
||||
for (const [ plugin, pass ] of passPairs) {
|
||||
for (const [plugin, pass] of passPairs) {
|
||||
const fn = plugin.pre;
|
||||
if (fn) fn.call(pass, this);
|
||||
}
|
||||
@@ -401,16 +432,19 @@ export default class File extends Store {
|
||||
debug(this.opts, "Start transform traverse");
|
||||
|
||||
// merge all plugin visitors into a single visitor
|
||||
const visitor = traverse.visitors.merge(visitors, passes, this.opts.wrapPluginVisitorMethod);
|
||||
const visitor = traverse.visitors.merge(
|
||||
visitors,
|
||||
passes,
|
||||
this.opts.wrapPluginVisitorMethod,
|
||||
);
|
||||
traverse(this.ast, visitor, this.scope);
|
||||
|
||||
debug(this.opts, "End transform traverse");
|
||||
|
||||
for (const [ plugin, pass ] of passPairs) {
|
||||
for (const [plugin, pass] of passPairs) {
|
||||
const fn = plugin.post;
|
||||
if (fn) fn.call(pass, this);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return this.generate();
|
||||
@@ -428,11 +462,17 @@ export default class File extends Store {
|
||||
err._babel = true;
|
||||
}
|
||||
|
||||
let message = err.message = `${this.opts.filename}: ${err.message}`;
|
||||
let message = (err.message = `${this.opts.filename}: ${err.message}`);
|
||||
|
||||
const loc = err.loc;
|
||||
if (loc) {
|
||||
err.codeFrame = codeFrame(code, loc.line, loc.column + 1, this.opts);
|
||||
const location = {
|
||||
start: {
|
||||
line: loc.line,
|
||||
column: loc.column + 1,
|
||||
},
|
||||
};
|
||||
err.codeFrame = codeFrameColumns(code, location, this.opts);
|
||||
message += "\n" + err.codeFrame;
|
||||
}
|
||||
|
||||
@@ -524,8 +564,11 @@ export default class File extends Store {
|
||||
|
||||
debug(this.opts, "Generation start");
|
||||
|
||||
const _result = gen(ast, opts.generatorOpts ? Object.assign(opts, opts.generatorOpts) : opts,
|
||||
this.code);
|
||||
const _result = gen(
|
||||
ast,
|
||||
opts.generatorOpts ? Object.assign(opts, opts.generatorOpts) : opts,
|
||||
this.code,
|
||||
);
|
||||
result.code = _result.code;
|
||||
result.map = _result.map;
|
||||
|
||||
|
||||
@@ -5,7 +5,11 @@ import * as t from "babel-types";
|
||||
import File from "./file";
|
||||
import loadConfig from "../config";
|
||||
|
||||
export function analyse(code: string, opts: Object = {}, visitor?: Object): ?BabelFileMetadata {
|
||||
export function analyse(
|
||||
code: string,
|
||||
opts: Object = {},
|
||||
visitor?: Object,
|
||||
): ?BabelFileMetadata {
|
||||
opts.code = false;
|
||||
if (visitor) {
|
||||
opts.plugins = opts.plugins || [];
|
||||
@@ -19,14 +23,18 @@ export function transform(code: string, opts?: Object): BabelFileResult {
|
||||
if (config === null) return null;
|
||||
|
||||
const file = new File(config);
|
||||
return file.wrap(code, function () {
|
||||
return file.wrap(code, function() {
|
||||
file.addCode(code);
|
||||
file.parseCode(code);
|
||||
return file.transform();
|
||||
});
|
||||
}
|
||||
|
||||
export function transformFromAst(ast: Object, code: string, opts: Object): BabelFileResult {
|
||||
export function transformFromAst(
|
||||
ast: Object,
|
||||
code: string,
|
||||
opts: Object,
|
||||
): BabelFileResult {
|
||||
const config = loadConfig(opts);
|
||||
if (config === null) return null;
|
||||
|
||||
@@ -37,14 +45,18 @@ export function transformFromAst(ast: Object, code: string, opts: Object): Babel
|
||||
}
|
||||
|
||||
const file = new File(config);
|
||||
return file.wrap(code, function () {
|
||||
return file.wrap(code, function() {
|
||||
file.addCode(code);
|
||||
file.addAst(ast);
|
||||
return file.transform();
|
||||
});
|
||||
}
|
||||
|
||||
export function transformFile(filename: string, opts?: Object, callback: Function) {
|
||||
export function transformFile(
|
||||
filename: string,
|
||||
opts?: Object,
|
||||
callback: Function,
|
||||
) {
|
||||
if (typeof opts === "function") {
|
||||
callback = opts;
|
||||
opts = {};
|
||||
@@ -54,13 +66,13 @@ export function transformFile(filename: string, opts?: Object, callback: Functio
|
||||
const config = loadConfig(opts);
|
||||
if (config === null) return callback(null, null);
|
||||
|
||||
fs.readFile(filename, function (err, code) {
|
||||
fs.readFile(filename, function(err, code) {
|
||||
let result;
|
||||
|
||||
if (!err) {
|
||||
try {
|
||||
const file = new File(config);
|
||||
result = file.wrap(code, function () {
|
||||
result = file.wrap(code, function() {
|
||||
file.addCode(code);
|
||||
file.parseCode(code);
|
||||
return file.transform();
|
||||
@@ -78,7 +90,10 @@ export function transformFile(filename: string, opts?: Object, callback: Functio
|
||||
});
|
||||
}
|
||||
|
||||
export function transformFileSync(filename: string, opts?: Object = {}): string {
|
||||
export function transformFileSync(
|
||||
filename: string,
|
||||
opts?: Object = {},
|
||||
): string {
|
||||
opts.filename = filename;
|
||||
const config = loadConfig(opts);
|
||||
if (config === null) return null;
|
||||
@@ -86,7 +101,7 @@ export function transformFileSync(filename: string, opts?: Object = {}): string
|
||||
const code = fs.readFileSync(filename, "utf8");
|
||||
const file = new File(config);
|
||||
|
||||
return file.wrap(code, function () {
|
||||
return file.wrap(code, function() {
|
||||
file.addCode(code);
|
||||
file.parseCode(code);
|
||||
return file.transform();
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user