How do I get Babel 6 to compile to ES5 javascript?

后端 未结 3 1083
-上瘾入骨i
-上瘾入骨i 2020-12-08 02:08

I\'ve installed the latest version of babel. Currently 6.4.0. I create a file called myclass.js that has the following code.

class MyClass {
    constructor(         


        
3条回答
  •  一生所求
    2020-12-08 02:19

    Babel doesn't usually target (or you don't usually want it to target) a specific standard, instead what it does is targeting the concrete browser versions you passed in somehow - explicitly like "targets": { "chrome": 70} or implicitly in different ways, for example, like "targets": ">0.25%" (market share) - in config files (package.json, .babelrc or babel.config.js). To make it possible, Babel gets the information about browser usage & features support from a number of other projects like browserlist.

    Then it transforms your code as down as possible & needed in terms of a set of ECMA features whose emulative implementations are defined by presets (groups of plugins, let's say preset-env). It finally comes to what can be run in the browsers you want your code to be run in.

    For example, if you target browsers with market share > 15%, this code - let a = 5; - will stay the same since these popular browsers are highly likely to be the latest versions of Chrome that perfectly support let. On the other hand, if you indicate that you also want support for IE8, let a = 5; becomes var a = 5; since now Babel tries to make your code suitable for IE8 which knows nothing about let. Well, you get the idea.

    Also it is important to understand, that Babel isn't a silver bullet - it doesn't add anything beyond ECMAScript spec. For example, it doesn't provide polyfills for browser APIs (fetch etc).

    And if you gave no indications, then, as the documentation states:

    Sidenote, if no targets are specified, @babel/preset-env will transform all ECMAScript 2015+ code by default. We don't recommend using preset-env this way because it doesn't take advantage of its ability to target specific browsers.

提交回复
热议问题