Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Get to Know Babel

Get to Know Babel

Since the introduction of ES6, JavaScript developers have been faced with the problem of the latest features not always being available in current or older browsers. So how should you deal with this problem? Do you write code that works in all browsers or only the newest ones? With Babel, you don't have to decide. Babel is a JavaScript compiler that lets you write next generation JavaScript code that runs in both current and older browsers or environments. Babel has become an indispensable tool for JavaScript developers because it solves this problem, but you may not be aware of everything it can do. In this session, we'll look at several of the different features of Babel, see how they work and learn how you can use them in your applications.

Jonathan Kemp

August 23, 2019
Tweet

More Decks by Jonathan Kemp

Other Decks in Technology

Transcript

  1. Overview • What is Babel? • Browser Compatibility • Getting

    Started • Babel and Frameworks • Demo • Conclusion
  2. Babel: Past • 6to5: an ES6 to ES5 transpiler •

    6to5 > Babel • ES2016+ • Babel 6 was released in 2015
  3. Babel: Present • Babel 7 was released in 2018 •

    Used in Next.js, vue-cli, React Native, and even WordPress.com's 
 frontend ! • Babel is fundamental to JavaScript development today.
  4. Babel: Present Currently (as of 2018): • Over 1.3 million

    dependent repos on GitHub • 17 million downloads on npm per month • hundreds of users including many major frameworks (React, Vue, Ember, Polymer), and companies (Facebook, Netflix, Airbnb). • Even if you aren't using it yourself, it's highly likely your dependencies are using Babel.
  5. Babel: Present Use the latest JavaScript syntax and make it

    backwards compatible by translating it.
  6. Babel: Present Because of its ability to transform JavaScript code,

    it also can be used to implement new features.
  7. Babel: Future? • Babel is inherently tied to what it

    compiles: JavaScript. • As long as there are new additions to propose/work on there is work to be done there. • New features • Roadmap: https://babeljs.io/docs/en/roadmap
  8. Babel 7 • Released in 2018 • Introduces a new

    config file: babel.config.js. • Comes with a new upgrade tool called babel-upgrade. • One important change is finally switching all packages to scoped packages.
  9. Babel 7 • The "env" preset replaces some of the

    presets suggested earlier. • i.e. babel-preset-es2015
  10. Destructuring assignment var a, b, rest; [a, b] = [10,

    20]; console.log(a); // expected output: 10 console.log(b); // expected output: 20 [a, b, ...rest] = [10, 20, 30, 40, 50]; console.log(rest); // expected output: [30,40,50]
  11. Rest Parameters function sum(...theArgs) { return theArgs.reduce((previous, current) => {

    return previous + current; }); } console.log(sum(1, 2, 3)); // expected output: 6 console.log(sum(1, 2, 3, 4)); // expected output: 10
  12. Spread syntax function sum(x, y, z) { return x +

    y + z; } const numbers = [1, 2, 3]; console.log(sum(...numbers)); // expected output: 6 console.log(sum.apply(null, numbers)); // expected output: 6
  13. Plugins • Out of the box Babel doesn't do anything.

    • You will need to add plugins for Babel to do something.
  14. @babel/plugin-transform-parameters This plugin transforms ES2015 parameters to ES5, this includes:

    • Destructuring parameters • Default parameters • Rest parameters
  15. Rest operator (...) in object destructuring const obj = {foo:

    1, bar: 2, baz: 3}; const {foo, ...rest} = obj; // Same as: // const foo = 1; // const rest = {bar: 2, baz: 3};
  16. Spread operator (...) in object literals > const obj =

    {foo: 1, bar: 2, baz: 3}; > {...obj, qux: 4} { foo: 1, bar: 2, baz: 3, qux: 4 }
  17. Stage-X (Experimental Presets) The TC39 categorizes proposals into the following

    stages: • Stage 0 - Strawman: just an idea, possible Babel plugin. • Stage 1 - Proposal: this is worth working on. • Stage 2 - Draft: initial spec. • Stage 3 - Candidate: complete spec and initial browser implementations. • Stage 4 - Finished: will be added to the next yearly release.
  18. Stage-X (Experimental Presets) • Any transforms in stage-x presets are

    changes to the language that haven't been approved to be part of a release of Javascript. • These proposals are subject to change so use with extreme caution, especially for anything pre stage-3. • As of v7, Babel is removing (stop publishing) the Stage presets.
  19. Optional Chaining for JavaScript • Current Stage: Stage 3 •

    https://github.com/tc39/proposal-optional-chaining • @babel/plugin-proposal-optional-chaining • https://babeljs.io/docs/en/babel-plugin-proposal-optional-chaining
  20. babel.config.js export default () => ({ presets: [ [ "@babel/preset-env",

    { "targets": "> 0.25%, not dead”, "useBuiltIns": "usage" } ], plugins: ["@babel/plugin-proposal-optional-chaining"] ] });
  21. @babel/polyfill • Package for adding ES6+ features into ES5. •

    This will emulate a full ES2015+ environment. • This means you can use new built-ins like Promise or WeakMap.
  22. babel.config.js export default () => ({ presets: [ [ "@babel/preset-env",

    { "targets": "> 0.25%, not dead”, "useBuiltIns": "usage" } ] ] });
  23. babel.config.js export default () => ({ presets: [ [ "@babel/preset-env",

    { "targets": { “chrome": "58", "ie": "11" }, “useBuiltIns": "usage" } ] ] });
  24. @babel/preset-env Takes any target environments you've specified and checks them

    against its mappings to compile a list of plugins and passes it to Babel.
  25. babel.config.js export default () => ({ presets: [ [ "@babel/preset-env",

    { "targets": "> 0.25%, not dead”, "useBuiltIns": "usage" } ] ] });
  26. Browserslist • Set versions list in queries like last 2

    versions to be free from updating versions manually. • Browserslist will use Can I Use data for this queries. • > 5%: browsers versions selected by global usage statistics. • dead: browsers without official support or updates for 24 months.
  27. Browserslist • There is a defaults query, which gives a

    reasonable configuration for most users. • If no valid config is specified, Browserslist will use defaults: > 0.5%, last 2 versions, Firefox ESR, not dead. • Run npx browserslist in your project directory to see project’s target browsers. This CLI tool is built-in and available in any project with Autoprefixer.
  28. Configuring for Different Environments • You can specify the browser

    and Node.js versions by queries • Target node just like you would a browser • You can also specify different browser queries for various environments. • Browserslist will choose query according to BROWSERSLIST_ENV or NODE_ENV variables.
  29. package.json "browserslist": { "production": [ "> 1%", "ie 10" ],

    "modern": [ "last 1 chrome version", "last 1 firefox version" ], "ssr": [ "node 12" ] }
  30. babel.config.js export default () => ({ presets: [ [ "@babel/preset-env",

    { "targets": { “chrome": "58", "ie": "11" }, “useBuiltIns": "usage" } ] ] });
  31. Presets Presets also accept an object of minimum environment versions

    to support • Example environments: chrome, opera, edge, firefox, safari, ie, ios, android, node, electron. • If no targets are specified, @babel/preset-env will transform all ECMAScript 2015+ code by default. • Using preset-env this way doesn't take advantage of its ability to target specific browsers.
  32. @babel/preset-env • You may also target browsers supporting ES Modules.


    https://www.ecma-international.org/ecma-262/6.0/#sec-modules • When specifying this option, the browsers field will be ignored.
  33. Other preset-env options • include - An array of plugins

    to always include. • exclude - An array of plugins to always exclude/remove.
  34. Lebab: Turn your ES5 code into readable ES6 (sugar-syntax). 


    It does the opposite of what Babel does.
  35. Lebab $ npm install -g lebab $ lebab es5.js -o

    es6.js --transform let $ lebab --replace src/js/ --transform arrow
  36. JSX

  37. @babel/preset-react This preset always includes the following plugins: • @babel/plugin-syntax-jsx

    • @babel/plugin-transform-react-jsx • @babel/plugin-transform-react-display-name
  38. Create React App What’s included: • React, JSX, ES6, TypeScript

    and Flow syntax support. • Language extras beyond ES6 like the object spread operator. • Support for Browserslist
  39. @vue/cli-plugin-babel • Babel plugin for vue-cli • Uses Babel 7

    + babel-loader + @vue/babel-preset-app by default, but can be configured via babel.config.js to use any other Babel presets or plugins
  40. @vue/babel-preset-app Included features: • @babel/preset-env • The following stage 3

    or below features are supported: • Dynamic Import Syntax, Proposal Class Properties, Proposal Decorators (legacy) • Vue JSX support • @babel/plugin-transform-runtime
  41. Closing • Use the latest JavaScript syntax and make it

    backwards compatible by translating it. • You will need to add plugins for Babel to do anything. • Presets are collections of Babel plugins. • For browser- or Electron-based projects, use Browserslist to specify targets.
  42. Closing • Babel is simple to setup, but if you

    are using a framework, it can be pre- configured for you.
  43. Resources • Docs - https://babeljs.io/docs/en/ • Awesome Babel - https://github.com/babel/awesome-babel

    • ES6 Compatibility Table - https://kangax.github.io/compat-table/es6/ • Can I use - https://caniuse.com/#