Giter Site home page Giter Site logo

babel / babel-preset-env Goto Github PK

View Code? Open in Web Editor NEW
3.5K 68.0 158.0 1.03 MB

PSA: this repo has been moved into babel/babel -->

Home Page: https://github.com/babel/babel/tree/master/packages/babel-preset-env

License: MIT License

JavaScript 100.00%
babel-preset autoprefixer javascript es6 moved

babel-preset-env's Introduction

Now that babel-preset-env has stabilized, it has been moved into the main Babel mono-repo and this repo has been archived.

The move makes it much easier to release and develop in sync with the rest of Babel!

This repo will be made read-only, as all of the issues/labels have been moved over as well. Please report any bugs and open pull requests over on the main mono-repo.


babel-preset-env npm travis npm-downloads codecov

A Babel preset that compiles ES2015+ down to ES5 by automatically determining the Babel plugins and polyfills you need based on your targeted browser or runtime environments.

npm install babel-preset-env --save-dev

Without any configuration options, babel-preset-env behaves exactly the same as babel-preset-latest (or babel-preset-es2015, babel-preset-es2016, and babel-preset-es2017 together).

However, we don't recommend using preset-env this way because it doesn't take advantage of it's greater capabilities of targeting specific browsers.

{
  "presets": ["env"]
}

You can also configure it to only include the polyfills and transforms needed for the browsers you support. Compiling only what's needed can make your bundles smaller and your life easier.

This example only includes the polyfills and code transforms needed for coverage of users > 0.25%, ignoring Internet Explorer 11 and Opera Mini.. We use browserslist to parse this information, so you can use any valid query format supported by browserslist.

{
  "presets": [
    ["env", {
      "targets": {
        // The % refers to the global coverage of users from browserslist
        "browsers": [ ">0.25%", "not ie 11", "not op_mini all"]
      }
    }]
  ]
}

You can also target individual versions of browsers instead of using a query with "targets": { "chrome": "52" }.

Similarly, if you're targeting Node.js instead of the browser, you can configure babel-preset-env to only include the polyfills and transforms necessary for a particular version:

{
  "presets": [
    ["env", {
      "targets": {
        "node": "6.10"
      }
    }]
  ]
}

For convenience, you can use "node": "current" to only include the necessary polyfills and transforms for the Node.js version that you use to run Babel:

{
  "presets": [
    ["env", {
      "targets": {
        "node": "current"
      }
    }]
  ]
}

Check out the many options (especially useBuiltIns to polyfill less)!

How it Works

Determine environment support for ECMAScript features

Use external data such as compat-table to determine browser support. (We should create PRs there when necessary)

We can periodically run build-data.js which generates plugins.json.

Ref: #7

Maintain a mapping between JavaScript features and Babel plugins

Currently located at plugin-features.js.

This should be straightforward to do in most cases. There might be cases where plugins should be split up more or certain plugins aren't standalone enough (or impossible to do).

Support all plugins in Babel that are considered latest

Default behavior without options is the same as babel-preset-latest.

It won't include stage-x plugins. env will support all plugins in what we consider the latest version of JavaScript (by matching what we do in babel-preset-latest).

Ref: #14

Determine the lowest common denominator of plugins to be included in the preset

If you are targeting IE 8 and Chrome 55 it will include all plugins required by IE 8 since you would need to support both still.

Support a target option "node": "current" to compile for the currently running node version.

For example, if you are building on Node 6, arrow functions won't be converted, but they will if you build on Node 0.12.

Support a browsers option like autoprefixer

Use browserslist to declare supported environments by performing queries like > 1%, last 2 versions.

Ref: #19

Install

With npm:

npm install --save-dev babel-preset-env

Or yarn:

yarn add babel-preset-env --dev

Usage

The default behavior without options runs all transforms (behaves the same as babel-preset-latest).

{
  "presets": ["env"]
}

Options

For more information on setting options for a preset, refer to the plugin/preset options documentation.

targets

{ [string]: number | string }, defaults to {}.

Takes an object of environment versions to support.

Each target environment takes a number or a string (we recommend using a string when specifying minor versions like node: "6.10").

Example environments: chrome, opera, edge, firefox, safari, ie, ios, android, node, electron.

The data for this is generated by running the build-data script which pulls in data from compat-table.

targets.node

number | string | "current" | true

If you want to compile against the current node version, you can specify "node": true or "node": "current", which would be the same as "node": process.versions.node.

targets.browsers

Array<string> | string

A query to select browsers (ex: last 2 versions, > 5%) using browserslist.

Note, browsers' results are overridden by explicit items from targets.

targets.uglify

true

When using uglify-js to minify your code, you may run into syntax errors when targeting later browsers since uglify-js does not support any ES2015+ syntax.

To prevent these errors - set the uglify option to true, which enables all transformation plugins and as a result, your code is fully compiled to ES5. However, the useBuiltIns option will still work as before and only include the polyfills that your target(s) need.

Uglify has support for ES2015 syntax via uglify-es. If you are using syntax unsupported by uglify-es, we recommend using babel-minify.

Note: This option is deprecated in 2.x and replaced with a forceAllTransforms option.

spec

boolean, defaults to false.

Enable more spec compliant, but potentially slower, transformations for any plugins in this preset that support them.

loose

boolean, defaults to false.

Enable "loose" transformations for any plugins in this preset that allow them.

modules

"amd" | "umd" | "systemjs" | "commonjs" | false, defaults to "commonjs".

Enable transformation of ES6 module syntax to another module type.

Setting this to false will not transform modules.

debug

boolean, defaults to false.

Outputs the targets/plugins used and the version specified in plugin data version to console.log.

include

Array<string>, defaults to [].

NOTE: whitelist is deprecated and will be removed in the next major in favor of this.

An array of plugins to always include.

Valid options include any:

  • Babel plugins - both with (babel-plugin-transform-es2015-spread) and without prefix (transform-es2015-spread) are supported.

  • Built-ins, such as map, set, or object.assign.

This option is useful if there is a bug in a native implementation, or a combination of a non-supported feature + a supported one doesn't work.

For example, Node 4 supports native classes but not spread. If super is used with a spread argument, then the transform-es2015-classes transform needs to be included, as it is not possible to transpile a spread with super otherwise.

NOTE: The include and exclude options only work with the plugins included with this preset; so, for example, including transform-do-expressions or excluding transform-function-bind will throw errors. To use a plugin not included with this preset, add them to your config directly.

exclude

Array<string>, defaults to [].

An array of plugins to always exclude/remove.

The possible options are the same as the include option.

This option is useful for "blacklisting" a transform like transform-regenerator if you don't use generators and don't want to include regeneratorRuntime (when using useBuiltIns) or for using another plugin like fast-async instead of Babel's async-to-gen.

useBuiltIns

boolean, defaults to false.

A way to apply babel-preset-env for polyfills (via "babel-polyfill").

NOTE: This does not currently polyfill experimental/stage-x built-ins like the regular "babel-polyfill" does. This will only work with npm >= 3 (which should be used with Babel 6 anyway)

npm install babel-polyfill --save

This option enables a new plugin that replaces the statement import "babel-polyfill" or require("babel-polyfill") with individual requires for babel-polyfill based on environment.

NOTE: Only use require("babel-polyfill"); once in your whole app. Multiple imports or requires of babel-polyfill will throw an error since it can cause global collisions and other issues that are hard to trace. We recommend creating a single entry file that only contains the require statement.

In

import "babel-polyfill";

Out (different based on environment)

import "core-js/modules/es7.string.pad-start";
import "core-js/modules/es7.string.pad-end";
import "core-js/modules/web.timers";
import "core-js/modules/web.immediate";
import "core-js/modules/web.dom.iterable";

This will also work for core-js directly (import "core-js";)

npm install core-js --save

Examples

Export with various targets

export class A {}

Target only Chrome 52

.babelrc

{
  "presets": [
    ["env", {
      "targets": {
        "chrome": 52
      }
    }]
  ]
}

Out

class A {}
exports.A = A;

Target Chrome 52 with webpack 2/rollup and loose mode

.babelrc

{
  "presets": [
    ["env", {
      "targets": {
        "chrome": 52
      },
      "modules": false,
      "loose": true
    }]
  ]
}

Out

export class A {}

Target specific browsers via browserslist

.babelrc

{
  "presets": [
    ["env", {
      "targets": {
        "chrome": 52,
        "browsers": ["last 2 versions", "safari 7"]
      }
    }]
  ]
}

Out

export var A = function A() {
  _classCallCheck(this, A);
};

Target latest node via node: true or node: "current"

.babelrc

{
  "presets": [
    ["env", {
      "targets": {
        "node": "current"
      }
    }]
  ]
}

Out

class A {}
exports.A = A;

Show debug output

.babelrc

{
  "presets": [
    [ "env", {
      "targets": {
        "safari": 10
      },
      "modules": false,
      "useBuiltIns": true,
      "debug": true
    }]
  ]
}

stdout

Using targets:
{
  "safari": 10
}

Modules transform: false

Using plugins:
  transform-exponentiation-operator {}
  transform-async-to-generator {}

Using polyfills:
  es7.object.values {}
  es7.object.entries {}
  es7.object.get-own-property-descriptors {}
  web.timers {}
  web.immediate {}
  web.dom.iterable {}

Include and exclude specific plugins/built-ins

always include arrow functions, explicitly exclude generators

{
  "presets": [
    ["env", {
      "targets": {
        "browsers": ["last 2 versions", "safari >= 7"]
      },
      "include": ["transform-es2015-arrow-functions", "es6.map"],
      "exclude": ["transform-regenerator", "es6.set"]
    }]
  ]
}

Caveats

If you get a SyntaxError: Unexpected token ... error when using the object-rest-spread transform then make sure the plugin has been updated to, at least, v6.19.0.

Other Cool Projects

babel-preset-env's People

Contributors

aaronang avatar anaisbetts avatar baer avatar bakkot avatar basicdays avatar brokenmass avatar caaatisgood avatar chicoxyzzy avatar corysimmons avatar danez avatar darahak avatar devongovett avatar evilebottnawi avatar existentialism avatar gerhut avatar hzoo avatar josephrexme avatar jthegedus avatar kaicataldo avatar kilian avatar kolesnichenkoevheniy avatar leggiero avatar matthiaskern avatar mikegreiling avatar nhajidin avatar oleksandr-kuzmenko avatar rohmanhm avatar roman-yakobnyuk avatar xtuc avatar yavorsky avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

babel-preset-env's Issues

Async functions with parameter destructuring don't work on Node 4.x

  var _ref = _asyncToGenerator(function* ({ bar }) {});
                                          ^

SyntaxError: Unexpected token {
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:373:25)
    at loader (/private/tmp/foo/node_modules/babel-cli/node_modules/babel-register/lib/node.js:144:5)
    at Object.require.extensions.(anonymous function) [as .js] (/private/tmp/foo/node_modules/babel-cli/node_modules/babel-register/lib/node.js:154:7)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Function.Module.runMain (module.js:441:10)
    at /private/tmp/foo/node_modules/babel-cli/lib/_babel-node.js:159:24
    at Object.<anonymous> (/private/tmp/foo/node_modules/babel-cli/lib/_babel-node.js:160:7)
    at Module._compile (module.js:409:26)

Self-contained test: https://github.com/djanowski/babel-preset-env-async-destructuring

Send file path to browserslist

Browserslist could use browserslist config file. It is useful, because many different tools will share same config (Autoprefixer, Stylelint, cssnext, doiuse).

But to enable a config, you need to pass a path for current file:

browserslist(opts.browsers, { path: opts.file })

Promise seems to be polyfilled in environments that support promises

Just messing around with the new polyfill stuff, but not sure it's working for promises. Here's my .babelrc:

{
  "presets": [
    [ "env", { loose: true, modules: false, useBuiltins: true, targets: { chrome: 55 } } ],
    [ "react" ]
  ],
  "plugins": [
    "transform-runtime",
    "transform-class-properties",
    ["transform-react-jsx", { "pragma": "h" }]
  ]
}

Here's my file:

export default class Callout extends Component {

  construct () {
    new Promise((reject, resolve) => {
      resolve('hi!')
    })
  }

  render () {
    return (
      <div>hello world!</div>
    )
  }
}

And here's my output (from babel index.js):

import _Promise from 'babel-runtime/core-js/promise';

export default class Callout extends Component {

  construct() {
    new _Promise((reject, resolve) => {
      resolve('hi!');
    });
  }

  render() {
    return h(
      'div',
      null,
      'hello world!'
    );
  }
}

Based on the data, Promises have been supported since chrome 51.

It's doing something though, because it's not polyfilling classes, and if I change it to { ie: 8 }, it'll include a bunch more deps.

can't resolve `es6.object.get-own-property-symbols`

version 1.0.1

When babel config is

    "presets": [
      [
        "env",
        {
          "targets": {
            "browsers": [
              "last 2 versions"
            ]
          },
          "debug": true,
          "modules": false,
          "useBuiltIns": true
        }
      ],
      "react"
    ],

i get the error

ERROR in ./app/app.js
Module not found: Error: Can't resolve 'core-js/modules/es6.object.get-own-property-symbols' in '/Users/andykenward/Documents/_github/bob/app'
 @ ./app/app.js 32:0-61

travis-ci log
repo commit

[Question] how to use with babili?

how my preset should look like if i want to merge babel-preset-env + babili ?
And imo its make sense to make babili integrate into this preset as a flag

TypeError: Cannot read property 'loose' of undefined

Error while using example from documentation.

CLI, babel-node, 6.16, babel-preset-env - 0.0.4, .babelrc content:

{
  "presets": [
    "env", {
      "targets": {
        "node": 6.7
      },
      "modules": false
    }
  ]
}

Running command babel-node tasks/dev fails with error:

/Users/tino/Sites/transfers.do/node_modules/babel-core/lib/transformation/file/options/option-manager.js:333
        throw e;
        ^

TypeError: Cannot read property 'loose' of undefined (While processing preset: "/Users/tino/Sites/transfers.do/node_modules/babel-preset-env/lib/index.js")
    at buildPreset (/Users/tino/Sites/transfers.do/node_modules/babel-preset-env/lib/index.js:93:39)
    at /Users/tino/Sites/transfers.do/node_modules/babel-core/lib/transformation/file/options/option-manager.js:322:46
    at Array.map (native)
    at OptionManager.resolvePresets (/Users/tino/Sites/transfers.do/node_modules/babel-core/lib/transformation/file/options/option-manager.js:269:20)
    at OptionManager.mergePresets (/Users/tino/Sites/transfers.do/node_modules/babel-core/lib/transformation/file/options/option-manager.js:258:10)
    at OptionManager.mergeOptions (/Users/tino/Sites/transfers.do/node_modules/babel-core/lib/transformation/file/options/option-manager.js:243:14)
    at OptionManager.init (/Users/tino/Sites/transfers.do/node_modules/babel-core/lib/transformation/file/options/option-manager.js:373:12)
    at compile (/Users/tino/Sites/transfers.do/node_modules/babel-register/lib/node.js:103:45)
    at loader (/Users/tino/Sites/transfers.do/node_modules/babel-register/lib/node.js:144:14)
    at Object.require.extensions.(anonymous function) [as .js] (/Users/tino/Sites/transfers.do/node_modules/babel-register/lib/node.js:154:7)

Document compilation performance enhancements

I am assuming that usage of this plugin during development when one targets say the locally installed Chrome that is latest, will bypass most of the conversions Babel does.

The question then is how much of a speedup does this cause during development. (In fact, that's the path via which I found this lib, I was thinking if I could get babel to just compile the JSX bits in my react app, it would make things much faster for compilation.)

It would be nice to document these speedups so that if they are good enough, we can suggest people to use this especially development to minimize compilation times.

Options?

Should we care about options for:

  • flags to turn on a feature (whitelist?)
  • "strict" option on the compat-table Babel assumes strict
  • or % supported rather than 100% supported
    • node 5 -> 6 there's a lot for iterator closing
    • how many are actually writing code that uses those features? Should it be smarter about how to transpile? Should it try to run through with node 4 and if it fails, use 5, 6?

Targeting Node.js LTS

nvm supports installing Node.js using LTS version specifiers lts/argon and lts/boron. It would be great if BPE supported these specifiers too.

Strange behavior when setting targets = { chrome: 55 }.

Thanks for your preset. It makes babel transformation much more graceful. :)

I encountered a strange problem when setting targets = { chrome: 55 }.

ERROR in ./src/client.js
    Module parse failed: ./react-starter-kit/node_modules/babel-loader/lib/index.js?{"cacheDirectory":true,"babelrc":false,"presets":[["env",{"targets":{"chrome":55},"useBuiltIns":true,"debug":true}],"react"],"plugins":["react-hot-loader/babel","transform-object-rest-spread","transform-class-properties","transform-runtime","transform-react-jsx-source","transform-react-jsx-self"]}!/Users/ajih/Documents/git/react-starter-kit/src/client.js Unexpected token (156:6)
    You may need an appropriate loader to handle this file type.
    SyntaxError: Unexpected token (156:6)

It seems that async functions is not recognized by babel. Setting chrome=54 or adding transform-async-to-generators to whitelist will solve the problem(but will transform async functions to generators).

I have created a repo based on react-starter-kit to reproduce the bug.

The webpack and babel config is in file tools/webpack.config.js.

no node7 rules. node -> chrome version aliases miss gaps

Currently the version aliases are:

{
	"safari6": "phantom",
	"chrome44": "node4",
	"chrome50": "node6",
	"chrome51": "node65",
	"chrome54": "node7",
	"chrome30": "android44",
	"chrome37": "android50",
	"chrome39": "android51",
	"safari51": "ios6",
	"safari7": "ios7",
	"safari71_8": "ios8",
	"safari9": "ios9",
	"safari10": "ios10"
}

note that chrome53 and chrome52 are missing. This means that any rule, eg async-functions does not include those changes.

This is currently fine because all those changes are covered by flags

suggestion

Foreword: It's hard to summarize my thoughts via a handful of sparse "issues", so I'll try to be concise in a unicorn "issue" instead, pick your brain, and take it from there.

There's not just one babel-plugin that can provide support for a feature e.g. async/await has multiple implementation alternatives. On top of that, one might want to blacklist a plugin.

Given these two scenarios alone, I see a standalone package that has 1 concern alone: decide which features are needed for a specific environment. Another package can then have the concern to map a set of desired features to known plugins (the mapping should be allowed to be extended, the plugins should be prioritized, and the prioritization should be allowed to be extended).

At this stage, a babel-preset package could just hold a set of the required features, and use the other two packages to return the necessary babel plugins. The babel plugins themselves would not be dependencies, but peerDependencies at most, leaving the dependency resolution up to the caller so that we don't end up installing n dependencies, while only 1 is actually truly required.

Hope the above makes some sense. I like the base of this data-driven preset, but I'd like the rigid structure (strict set of plugins and download of maybe-redundant dependencies) to shed off.

How to handle stage-x

Do we want to allow for users to stage-x plugins with this preset as well?
Or should this only cover for everything under latest?

Since browsers don't implement stage-x features anyway (otherwise they'd be stage-4), it would be only supported by browsers through a flag...

Maybe we should just leave it alone and users will just specify stage-x presets individually?

{
  "presets": [
    ["env", {
      "targets": {
        "chrome": 52
      }
    }],
    "stage-2"
  ]
}

Actually now that I think about that seems fine?

useBuiltIns: figure out how to remove polyfills that aren't actually used in the codebase

Goal: only include necessary polyfills

Don't include if supported environments support it natively #20

  • Use preset-env config to determine what parts of core-js to pull in (original PR, #55)
import "babel-polyfill";

gets transformed to

import "core-js/modules/es6.map";
import "regenerator-runtime/runtime";
...

Don't include if you have blacklisted it yourself (regenerator for example) #60

  • Be able to blacklist transforms or specific builtIns?
{
  "presets": [
    ["env", {
      "targets": {
        "browsers": ["last 2 versions", "safari >= 7"]
      },
      "blacklist": [
        "transform-regenerator" // won't include "regenerator-runtime/runtime"
      ]
    }]
  ]
}

Don't include if the codebase doesn't actually use the builtIn (this)

this would need to be a whole codebase transformation so it probably won't work in this preset/plugin

The problem with the first heading ^ is that even if you remove the polyfills supported natively in the environment, you might not actually use them in your codebase anyway.

Possible solution: run an analyzer (separate babel pass like transform-runtime) on the whole codebase and remove imports that aren't used anywhere.

EDIT: A big problem atm is that Babel runs per file. So unless we understand the whole codebase it sounds like something webpack could do? cc @TheLarkInn @keyanzhang

Promote shareable browserslist config

I think we should promote shareable browsers config instead of browsers option. Maybe browserslist key in package.json will be the best way.

I think most of babel-preset-env users also use Autoprefixer. So for better maintainability they should use shareable browsers config to use same browsers list in Autoprefixer and babel-preset-env. But most of developers doesnโ€™t know about this option and benefits of it.

I already removed browsers option from all examples in Autoprefixer docs and focused on sharable configs.

3rd party lib depends on import "babel-polyfill"; cause issues

Please correct me if I'm wrong.
"useBuiltIns": true will lead to remove some polyfill depends on the "targets".
But some libs depends on babel-polyfill, for example Relay.js.
App might break on some old browsers.

Is there a better solution than include the whole babel-polyfill?
Thanks.

Failing to replace `babel-preset-es2015` by `babel-preset-env`

I'm replacing the usage of the es2015 preset by this env preset on one of my node application but I'm facing some weird behavior. Not sure is that's a bug or my that make a mistake.

The doc said:

Default behavior without options is the same as babel-preset-latest

So I replace my es2015 preset by this one in my .babelrc without specifing any options. Everything keep working in my app.

The next step was to specify the target in the options: ["env", { "targets": { "node": "current" }}],. Now my app failed to start with a lots of weird errors. After digging into this it seems that some of the es2015 transformer are missing... The transform-es2015-classes and the transform-es2015-destructuring. When I force their activation, everything works again.

Here my .babelrc:

{
    "presets": [
        ["env", {
            "targets": {
                "node": "current"
            },
            "include": [
                "transform-es2015-classes",
                "transform-es2015-destructuring",
                "transform-regenerator" 
            ],
            "useBuiltIns": true
        }],
        "stage-1",
        "react"
    ],
    "env": {
        "development": {
            "plugins": ["transform-react-jsx-source"]
        },
        "testing": {
            "plugins": ["transform-react-jsx-source"]
        },
        "production": {
            "plugins": ["transform-react-constant-elements"]
        }
    }
}

I'm running on node LTS v6.9.2.

What is "loose" transformation?

Hi! In the documentation you've written the following:

Enable "loose" transformations for any plugins in this preset that allow them.

Could you please tell me what "loose" transformations are? After a quick google, I found this article, which I think is what you're talking about, but I just wanted to get clarification!

Thanks for the awesome looking project!

Yours, Em

import of `regenerator-runtime` is incorrect and UglifyJs issue

Using v1.0.0 and import 'babel-polyfill';
I get this error when building my project.

ERROR in ./app/app.js
Module not found: Error: Can't resolve 'core-js/modules/regenerator-runtime/runtime' in '/Users/andykenward/Documents/_github/bob/app'
 @ ./app/app.js 46:0-53
 @ multi main

ERROR in main.5954769afe0c86762c19.js from UglifyJs
SyntaxError: Unexpected token punc ยซ}ยป, expected punc ยซ:ยป [main.5954769afe0c86762c19.js:560,18]

shouldnt the import be

import "regenerator-runtime/runtime"

I thought it may have been a yarn over npm. So tried install dependency both ways but no change

  "engines": {
    "node": "6.9.1",
    "npm": "3.10.8",
    "yarn": "0.17.10"
  },

here is my babel config

"babel": {
    "babelrc": false,
    "presets": [
      [
        "env",
        {
          "targets": {
            "browsers": [
              "last 2 versions",
              "not ios_saf <= 8",
              "not IE <= 11"
            ]
          },
          "debug": true,
          "modules": false,
          "useBuiltIns": true
        }
      ],
      "react"
    ],
    "plugins": [
      "transform-object-rest-spread",
      "transform-flow-strip-types"
    ],
    "env": {
      "development": {
        "only": [
          "app"
        ],
        "plugins": [
          "transform-react-jsx-source"
        ]
      },
      "production": {
        "only": [
          "app"
        ],
        "plugins": [
          "transform-react-remove-prop-types",
          "transform-react-constant-elements",
          "transform-react-inline-elements"
        ]
      },
      "test": {
        "plugins": [
          "transform-es2015-modules-commonjs"
        ]
      }
    }
  }

you can clone the repo

regeneratorRuntime is not defined

I use the latest Chrome 55, it supports generators. It works well if only I exclude transform-generator explicitly. With useBuiltIns: true I also got the issue. It seems to be a bug.

// webpack.config.js
  module: {
    rules: [{
      test: /\.jsx?$/,
      include: SRC,
      loader: 'babel-loader',
      options: {
        "presets": [ "react",
          [ "env", {
            "targets": {
              "browsers": [ "last 2 versions" ]
            },
            //exclude: [ 'transform-regenerator' ],
            "modules": false
          }]
        ]
      }
    }]
  }

I suppose the preset should include babel-plugin-transform-regenerator if it needed, but it doesn't for some reason.

Does not accept options

I've got an error Options {"targets":{"chrome":51},"modules":false,"loose":false} passed to /Users/tino/Sites/transfers.do/node_modules/babel-preset-env/lib/index.js which does not accept options. (While processing preset: "/Users/tino/Sites/transfers.do/node_modules/babel-preset-env/lib/index.js") while trying to use this module in following code:

file = babel.transform(file, {
        sourceMap: false,
        babelrc: false,
        plugins: ['transform-strict-mode'],
        parserOpts: {
          sourceType: 'script',
          plugins: ['flow'],
        },
        presets: [
          ['env', {
            targets: {
              chrome: 51,
            },
            modules: false,
            loose: false,
          }],
        ],
        env: {
          production: {
            // presets: ['babili'],
            compact: true,
            minified: true,
            comments: false,
          },
        },
      }).code

Feature request: transform a require('babel-polyfill') call to specific requires base on the env config

First of all, babel-preset-env is awesome. Thanks for making this happen!

I'm thinking about how to make polyfills better. If someone uses babel-preset-env it means he/she has a few specific platforms to target and it's probably not necessary to require the entire babel-polyfill library.

Since we now know what the targets are, can we transform a require('babel-polyfill'); call to specific requires? For example, if someone targets IE 11 then

require('babel-polyfill');

gets transformed to

require('babel-polyfill/array-from');
require('babel-polyfill/array-of');
require('babel-polyfill/object-assign');
require('babel-polyfill/regenerator-runtime');
/* ... other polyfills that IE 11 needs */

The example above is not comprehensive and there should be a better way to require individual polyfill libraries, but you get the idea. If someone targets Chrome 55 then there are only very few polyfills that need to be applied.

It's probably gonna be a new transform plugin (transform-polyfill-require? :D) and won't live in this repo, but it should use the compat-table data here. Feedbacks are welcome!

Related tweet: https://twitter.com/left_pad/status/784611480947810304

ios version issue

because of browserlist not returning version in a reliable order (browserslist/browserslist#99 ) if the version is a 'range (10-10.1 for example) babel-preset-env doesn not handle correctly ios version

if you use the following targets configuration

targets: {
  browsers: [
    '> 1%',
    'last 3 versions',
    'ios >= 6',
    'not ie < 10'
  ]
}

you get

// Using targets:
{
  "chrome": 49,
  "edge": 12,
  "firefox": 48,
  "ie": 9,
  "ios": 10,
  "safari": 9
}

with ios being 10 instead of the expected 6.

this happens because babel-preset-env strongly relies on the list being ordered and just takes the last returned version.

return browsers.reduce(function (all, browser) {
  var _browser$split = browser.split(" "),
      browserName = _browser$split[0],
      browserVersion = _browser$split[1];

  if (browserName in browserNameMap) {
    all[browserNameMap[browserName]] = parseInt(browserVersion);
  }
  return all;
}, {});

maybe would be a good idea to do not rely on the order and just explicitly get the smallest version :

return browsers.reduce(function (all, browser) {
  var _browser$split = browser.split(" "),
      browserName = _browser$split[0],
      browserVersion = _browser$split[1];

  if (browserName in browserNameMap) {
    all[browserNameMap[browserName]] = Math.min(all[browserNameMap[browserName]] || Infinity, parseInt(browserVersion));
  }
  return all;
}, {});

Features support data source

Currently we use compat-table as a source of feature support data source.

There are some issues with this approach:

  • currently we are use outdated info
  • babel-preset-env needs build script to be maintained and updated every time compat-table changes
    • current build script is outdated
    • we consider ES6 features only, for ES2016+ features we need to modify build script
    • every change in compat-table can break build script (see recent example)
    • mapping from test names to babel features names may break
    • there is no any workflow in compat-table contributing that guarantees that changes will be reviewed before merging (some commits are pushed directly to gh-pages branch)
  • compat-table wasn't designed to be a data source and it's not easy to rewrite it because it's data, build script and UI are coupled

I'm going to create an alternative to compat-table which:

  • will hold all necessary data in npm as json
  • will be modular (one feature - one json file) so projects like babel-preset-env will be able to use only part of data they need
  • will use test262 instead of alternative tests because
    • tests unlikely will change their name
    • these tests are used by browsers vendors so they are more precise
    • every new test262 test can be automatically handled and added to feature support data

Any thoughts?

Add blacklist for transform plugins

Hi!
I've found some problem with usage of this preset.
My config looks like this:

presets: [
    ['env', {
        targets: {
            ie: 11,
            chrome: 47, //Sputnik browser,
            firefox: 'last 2 versions'
        },
        loose: true
    }]
],
plugins: [
    'fast-async'
]

And it's doesn't work, because preset tries to transform async functions with babel-plugin-transform-async-to-generator instead of fast-async.
It looks strange to me, I think, user should have ability to ignore some plugins.
In my opinion, it should look like this:

presets: [
    ['env', {
        blacklist: ['babel-plugin-transform-async-to-generator']
    }]
]

Object Spread Transform Not Included

I was trying to create a babel config for some dev work and just wanted the target recent Chrome. I'm using Webpack 2 and babel-loader as the build pipeline. The following config caused a compiler error:

{
  "presets": [
    ["env", {
      "targets": {
        "browsers": "last 2 Chrome versions"
      },
      "modules": false,
      "loose": true
    }]
  ]
}

However, manually adding babel-plugin-transform-object-rest-spread fixed the errors.

{
  "presets": [
    ["env", {
      "targets": {
        "browsers": "last 2 Chrome versions"
      },
      "modules": false,
      "loose": true
    }]
  ],
  "plugins": [
    ["transform-object-rest-spread", { "useBuiltIns": true }]
  ]
}

What is the expected behavior here? Is babel-plugin-transform-object-rest-spread meant to be added manually?

Might relate to #22.

[Question] get rid of defaultInclude

Trying to get rid of all the unused polyfills that env includes in my code. I have found that there are three polyfills which are always included no matter what and weigh ~35KB uncompressed. These are:

  1. web.timers
  2. web.immidiate
  3. web.dom.iterable

I'd like to remove them and include them only if they are needed, but first, is there any particular reason, why are they always in the bundle?
With thanks,
Laszlo

Support `browserslist` files

Support loading the browsers data from a browserslist file, resolved the same way .babelrc is.

browserslist.readConfig(pathToFile) should DTRT (or return false).

regeneratorRuntime issue

Here is my .babelrc :

{
	"presets": [
		["env", {
			"targets": {
				"chrome": 47,
    		"edge": 13,
    		"firefox": 45,
    		"safari": 10,
    		"node": 6,
    		"ios": 10,
    		"opera": 34
			},
			"modules": "umd"
		}
		]
	]
}

All code *entries() { is tranformed to

entries() {
      var map, opts, name, _iteratorNormalCompletion4, _didIteratorError4, _iteratorError4, _iterator4, _step4, _ref2, _ref3, value, filename;

      return regeneratorRuntime.wrap(function _callee$(_context) {

Which throw a :

VM1014 formdata.min.js:12 Uncaught ReferenceError: regeneratorRuntime is not defined

I then think about adding babel-polyfill or babel-runtime but then what would be the point of that preset ๐Ÿค”

So here I come, and how should we configure our .babelrc file for regenerators

thanks a lot !

Verify IE, other environments

Currently: "chrome, edge, firefox, safari, node"

https://kangax.github.io/compat-table/es6/ supports a lot more?

  • First which environments? (ie, ios, android)
  • How do we fix data/logic around edgecases/make it robust?
    • const envMap = {
      safari51: "safari5",
      safari71_8: "safari7",
      chrome: "chrome19",
      chrome19dev: "chrome19",
      chrome21dev: "chrome21",
      firefox3_5: "firefox3",
      firefox3_6: "firefox3",
      node012: "node0.12",
      node64: "node6",
      node65: "node6.5"
      };
      is kind of a hack
    • as is
      return Object.keys(test)
      .filter((t) => t.startsWith(env))
      // TODO: make flagged/etc an options
      .filter((test) => tests[i].res[test] === true || tests[i].res[test] === "strict")
      // normalize some keys
      .map((test) => envMap[test] || test)
      .filter((test) => !isNaN(parseInt(test.replace(env, ""))))
      .shift();

Bug in computed properties implementation in Chrome < 52

In our app, we were experiencing a crash in certain scenarios when using computed properties in Chrome < 52. This bug has been fixed in Chrome 52 and above.

https://bugs.chromium.org/p/v8/issues/detail?id=5033
https://bugs.chromium.org/p/chromium/issues/detail?id=625868

Given that, would you accept a pull request to bump the required Chrome version to 52 for transform-es2015-computed-properties? I suppose Opera would have been affected as well. Would this need to be authored as an override in the build-data.js script?

cc @jayfunk

Add a "target preset" option?

{
  "presets": [
    "env", {
      "targetPreset": "experimental-stage-3" // default to latest like it is currently,
      "targets": {
        "browsers": ["last 2 versions"]
      },
      "exclude": ["transform-regenerator"],
    }
  ] 
}

TLDR - figure out how we should include stage-3 plugins.


Oh man naming is hard: basically there's a difference between the "target javascript" you want to write in. What is currently "targets" is the list of environments you support (why didn't I just call it "environments" when the preset is preset-env lol ๐Ÿค” ).

The values of this option could potentially be any year, latest, or stage 3 (basically the current official presets that we have). In reality I think the only ones we care about would be latest and stage 3. The reason why we didn't add stage-3 earlier was because I kept thinking about the latest spec rather than forgetting that at stage-3 browser vendors will start implementations. Many projects/companies choose to target stage-3 (and if you are doing lower without codemods or serious consideration of the consequences then there will be issues and that's why we have been discussing babel/babel#4914 and others).

Node: crash on for-of in async function

When I use target node: 'current', I get this crash on transpile (both for Node 6.9 and 7.1):

Module build failed: Error: /project/lib/database/DB.js: unknown Statement of type "ForOfStatement"
    at /project/node_modules/regenerator-transform/lib/emit.js:657:15
...

I presume this is similar to facebook/regenerator#229, and indeed when I manually add the plugin babel-plugin-transform-es2015-for-of things work again.

So either the for-of transform should stay enabled, regenerator-transform should handle for-of, or there should be one that only changes for-of inside async functions.

This is the debug configuration:

babel-preset-env: `DEBUG` option

Using targets: {
  "node": "current"
}

modules transform: commonjs

Using plugins:

 transform-exponentiation-operator {}

 transform-async-to-generator {}

 syntax-trailing-function-commas {}

Using polyfills:

 es6.weak-map {}

 es6.weak-set {}

 es6.reflect.apply {}

 es6.reflect.construct {}

 es6.reflect.define-property {}

 es6.reflect.delete-property {}

 es6.reflect.get {}

 es6.reflect.get-own-property-descriptor {}

 es6.reflect.get-prototype-of {}

 es6.reflect.has {}

 es6.reflect.is-extensible {}

 es6.reflect.own-keys {}

 es6.reflect.prevent-extensions {}

 es6.reflect.set {}

 es6.reflect.set-prototype-of {}

 es6.symbol {}

 es6.regexp.flags {}

 es7.array.includes.js {}

 es7.string.pad-start {}

 es7.string.pad-end {}

Not working with webpack-dev-server v2.2.0-rc.0

I have the following base config:

const config = require('./config');
const path = require('path');

module.exports = {
    devtool: 'source-map',
    performance: { 
        hints: false 
    },
    entry: [
        './src/index.js',
    ],
    output: {
        path: path.join(__dirname, '../dist'),
        publicPath: '/dist/',
        filename: 'app.js'
    },
    plugins: [],
    module: {
        loaders: [
            {
                test: /\.js$/,
                loader: 'babel-loader',
                exclude: ['/node_modules/'],
                query: {  
                    'presets': [['env', { 
                        "modules": false,
                        "targets": {
                            "browsers": ["last 2 versions", "safari >= 7"]
                        }
                    }]],
                    'plugins': [],
                },
            },
            //...
        ],
    },
}

And the following prod config:

const base = require('./webpack.base');
const webpack = require('webpack');

base.plugins.push(
    new webpack.optimize.UglifyJsPlugin({
        compress: {
            warnings: true,
        },
    })
);

module.exports = base;

And the following dev config:

const base = require('./webpack.base');
const webpack = require('webpack');

base.entry.push(
    'webpack/hot/dev-server',
    'webpack-dev-server/client?http://localhost:4000'
);

base.plugins.push(
    new webpack.HotModuleReplacementPlugin()
);

module.exports = base;

And finally here is my dev server config:

const dev = require('./webpack.dev');
const webpack = require('webpack');
const server = require('webpack-dev-server');
const path = require('path');

const compiler = webpack(dev);

const instance = new server(compiler, {
    hot: true,
    filename: dev.output.filename,
    publicPath: dev.output.publicPath,
    stats: {
        colors: true,
    }
});

instance.listen(4000, 'localhost', () => {})

Now when I run with the prod config everything compiles fine, however when I run with the dev config I get the following error:

ERROR in ./~/debug/browser.js
Module build failed: Error: Couldn't find preset "es2015" relative to directory "/home/otis/Developer/hassle/node_modules/debug"                                                        
    at /home/otis/Developer/hassle/node_modules/babel-core/lib/transformation/file/options/option-manager.js:299:19                                                                     
    at Array.map (native)                                                                                                                                                               
    at OptionManager.resolvePresets (/home/otis/Developer/hassle/node_modules/babel-core/lib/transformation/file/options/option-manager.js:270:20)                                      
    at OptionManager.mergePresets (/home/otis/Developer/hassle/node_modules/babel-core/lib/transformation/file/options/option-manager.js:259:10)                                        
    at OptionManager.mergeOptions (/home/otis/Developer/hassle/node_modules/babel-core/lib/transformation/file/options/option-manager.js:244:14)                                        
    at OptionManager.init (/home/otis/Developer/hassle/node_modules/babel-core/lib/transformation/file/options/option-manager.js:374:12)                                                
    at File.initOptions (/home/otis/Developer/hassle/node_modules/babel-core/lib/transformation/file/index.js:216:65)                                                                   
    at new File (/home/otis/Developer/hassle/node_modules/babel-core/lib/transformation/file/index.js:139:24)                                                                           
    at Pipeline.transform (/home/otis/Developer/hassle/node_modules/babel-core/lib/transformation/pipeline.js:46:16)                                                                    
    at transpile (/home/otis/Developer/hassle/node_modules/babel-loader/lib/index.js:38:20)                                                                                             
 @ ./~/sockjs-client/lib/main.js 25:10-26                                                                                                                                               
 @ ./~/sockjs-client/lib/entry.js                                                                                                                                                       
 @ (webpack)-dev-server/client/socket.js                                                                                                                                                
 @ (webpack)-dev-server/client?http://localhost:4000                                                                                                                                    
 @ multi main

Here is a copy of my package.json if it helps:

{
  "name": "hassle",
  "version": "0.0.0",
  "description": "Hassle an event organisation app",
  "main": "index.js",
  "scripts": {
    "dev": "NODE_ENV=development node build/server.js",
    "build": "NODE_ENV=production webpack --config build/webpack.prod.js",
    "test": "echo 'lets implement'"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/Shipwrecked/Hassle.git"
  },
  "author": "Otis Wright",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/Shipwrecked/Hassle/issues"
  },
  "homepage": "https://github.com/Shipwrecked/Hassle#readme",
  "dependencies": {},
  "devDependencies": {
    "babel-core": "^6.2",
    "babel-loader": "^6.2",
    "babel-preset-env": "^1.0",
    "css-loader": "^0.26",
    "file-loader": "^0.9",
    "node-sass": "^4.0",
    "rimraf": "^2.5",
    "sass-loader": "^4.1",
    "style-loader": "^0.13",
    "webpack": "^2.2.0-rc.1",
    "webpack-dev-server": "^2.2.0-rc.0"
  }
}

Target node 6.7 not including Object spread transform

.babelrc:

{
  "presets": [
    ["env", {
      "targets": {
        "node": 6.7
      },
      "loose": true
    }]
  ]
}

error after script run:

SyntaxError: /Users/tino/Sites/transfers.do/tasks/sass.js: Unexpected token (159:4)
  157 |     file,
  158 |     outFile,
> 159 |     ...sassOptions,
      |     ^

Environment "browser" and version "latest"

It would be nice if we had a "browser" environment which would cover all browsers and a "latest" version to target the latest version of an environment.

Examples:

{ browser: 'latest' }
// =>
{ chrome: 'latest', edge: 'latest', firefox: 'latest', safari: 'latest' }
// =>
{ chrome: 123, edge: 123, firefox: 123, safari: 123 }

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.