What do you need to know when using @ babel / preset-env?

Tram Ho

Hello everyone, package @babel/preset-env may many of you are familiar with it but do you really understand its power? Let’s find out together today. Into the ?

1. Preparation

Request:

  • Already have basic knowledge about Babel .
  • The environment I will demo:
    • macOS
    • node v10.16.1
    • yarn v1.17.3
  • Editor: VSCode

Purpose:

  • Learn more about package @babel/preset-env .
  • Find advantages and disadvantages to use to suit each project.

2. Content

What is Babel?

Babel is a compiler

Like other compilers it runs in 3 stages

Preset env

  • Simply put, it allows you to use the latest JavaScript syntax without worrying about compatibility with JavaScript interpreters in browsers (Of course there will be some exceptions) because it will convert into ES5 syntax (JavaScript engine can understand)
  • It is a collection of @babel/plugin-* , its list of plugins you can see here

For example

Options

We will go through the common options

modules

"amd" | "umd" | "systemjs" | "commonjs" | "cjs" | "auto" | false , defaults to false

For example, we want to convert ES6 module syntax into commonjs module

When working with webpack you may often see the modules: false option, the purpose to turn off the ES6 module conversion function because the webpack already supports it and makes it even better.

targets

string | Array<string> | { [string]: string } , defaults to {}

Describe the environments your project supports

For example you want to support chrome58 and ie11 environments

useBuiltIns

"usage" | "entry" | false , defaults to false This option configures how @babel/preset-env handles polyfill

These 2 packages need to be installed so babel can help you import polyfill

For example we use useBuiltIns: usage and corejs: 3

For each different target , the number of imported polyfill will also be different

  1. with target is ie11

  1. with target chrome60

Normally for company projects, you should use useBuiltIns: entry and import these 2 first in the file entry will bundle

And it will import all the polyfill based on the corresponding environment

loose

boolean defaults to false

Many plugin in babel have 2 modes

  1. Normal mode follows ECMAScript ‘s semantics as closely as possible when converting them into ES5
  2. The loose action will make ES5 code simpler when transformed (less code but sometimes unsafe by 1).

There are also many other options you can read more here

3. Conclusion

Through this article hope to help you somewhat better understand this package:

  1. See the code conversion.
  2. The environment in which your project is directed is most fully supported and also reduces the size of the bundle file.
  3. polyfill code.

Thank you for reading this article.

Complete the above example at the repo

Chia sẻ bài viết ngay

Nguồn bài viết : Viblo