• Learning about Babel and what it does

    Popular point saidBabelIs actually a conversion tool, can help us syntax conversion, source code conversion,PolyfillTo achieve goals and alleviate missing functions; The idea is to convert some code that contains code that is not supported by the browser into code that is supported by the browser, for examplees6Converted toes5.

  • The use of Babel

    BabelandpostcssIt’s kind of similar that they can be used separately first of all without having to be combinedwebpackSecondly, they are all a tool chain, which only contains the most basic functions. When using them, we need to install some other plug-ins to realize the functions we need, such as conversionpromiseYou need onepolyfillThe plug-in

    • Install the library
      • @babel/core:babelThe core code must be installed;
      • @babel/cli: We can use it at the command linebabel;

      Installation command:yarn add @babel/cli @babel/core -D

    • Command line usage

      Command parameters:src/test-babelDestination folder--out-dirSpecify the folder to output

      Command:npx babel src/test-babel --out-dir dist, the completed conversion code is as follows:Found that at this timees6Code ores6Has not been converted, which verifies the abovebabelIs a tool chain, which only contains the most basic function code, if you need to do conversion need to configure some plug-ins to achieve

    • Use of plug-ins

      Above,babelThe transformation is discovered after the installation is completees6The code has not been transformedconstIt’s still in the arrow function, and I mentioned that you need some plug-ins to do that, and that’s what I’m using here

      • @babel/plugin-transform-arrow-functionsTransform arrow function

        Install command: yarn add @babel/plugin-transform-arrow-functions -D

        Using the command:npx babel src/test-babel --out-dir dist --plugins=@babel/plugin-transform-arrow-functions
      • @babel/plugin-transform-block-scopingConvert some keywords

        Install command:yarn add @babel/plugin-transform-block-scoping -D

        Using the command:npx babel src/test-babel --out-dir dist --plugins=@babel/plugin-transform-block-scoping
      • Both plug-ins are used together

        Command:npx babel src/test-babel --out-dir dist --plugins=@babel/plugin-transform-block-scoping,@babel/plugin-transform-arrow-functions
    • Babel的预设preset

      If there are multiple plug-ins, you need to put them all into the command. Therefore, if there are many things that need to be converted, it will be troublesome to set up. Therefore, you can use it at this timepresetIt withpluginsThe difference betweenpluginsIt’s more of a one-by-one tool, you use whatever you want to use, andpresetIt’s a collection of tools that give you all the tools.

      • Install command: yarn add @babel/preset-env -D
      • Using the command: npx babel src/test-babel --out-dir dist --presets=@babel/preset-env

    • babel-loader

      In normal development, it is impossible for us to convert every file according to the way of command. One is troublesome or the other is likely to forget to press a file, so at this time we can usewebpackBy configuringbabelTo process the project files, that’s what you need herebabel-loader

      • Installation command:yarn add babel-loader -D
      • Configuration mode: and other configurationsloaderThe way is as follows:

      It also needs to work with plugins or presets

      • Plug-in configuration:Packing results:
      • Default configuration:Pack the result
    • Setting the target Browser

      Two ways:

      1. By adding to the presettargetsTo set the target browser as follows:

      2. browserslistwillcss-loaderI won’t say more here than I have said before (this is more recommended here)

    • BabelConfiguration file of

      webpackYou can also write the configuration in a separate file

      • babel.config.json(or.js,.cjs,.mjs) documents;
      • .babelrc.json(or.babelrc.js.cjs.mjs) documents;

      The difference between the two.babelrc.jsonEarly use of more configuration methods, but for configurationMonoreposProjects are cumbersome;Babel. Config. Json (babel7): can act directly on phiMonoreposProject subpackage, more recommended; The configuration is as follows:

    • The use of polyfill

      polyfillIt’s a patch, so to speak. For example, when we write code, we use some features (Promise), and the browser does not recognize these features, so it can type one or fill in anotherPromiseAt this point the browser includes this feature

      • Install dependencies

        babel7.4.0Before, it can be used@babel/polyfillBut this package is no longer recommended: the official documentation also says soNow usecore-js/stableandregenerator-runtime/runtimealternative

        Installation:yarn add core-js regenerator-runtimeBecause the production environment will also use the corresponding library code, so this is directly added todependenciesRely on
      • use

        Add two parameters to the configuration:
        1. useBuiltIns: How does it be usedpolyfill
          • false: NothingpolyfillRelated code
          • usage: What is required in the codepolyfill, just quote the relevantapi
          • entry: If one of the libraries we rely on itself uses some of Polyfill’s features, but because we are usingusage, so the user can use this property later when the browser may report an error; Manually import in the entry filecore-js/regenerator-runtimeImport all corresponding values based on the target browserpolyfillDoing so would be based onbrowserslistThe target imports allpolyfill, but the corresponding package will also become larger;
        2. corejsSet:corejsversion
    • Plugin-transform-runtime

      Mainly write their own tool library will be used, if the tool library needs to usepolyfillAnd then the tool library passes throughpolyfillThe added features are generated by our library when someone else is using itpolyfillIt contaminates the user’s code so it can be used at this pointPlugin-transform-runtime

    • React JSX support

      In general we writereact“Is used whenjsxSyntax, but the browser does notjsxSyntax so this is where you need to changejsxSyntax conversion, the specific use of plug-ins as follows:

      • @babel/plugin-syntax-jsx
      • @babel/plugin-transform-react-jsx
      • @babel/plugin-transform-react-display-name

      But we don’t need so many plugins to configure it by default@babel/preset-reactThe configuration is as follows:

    • Load the TypeScript

      loadingTypeScriptThere are two ways to do this one is throughts-loaderLoading is also one throughbabel-loader

      • ts-loader

        Browsers are not supportedtsSo this is going to be the codetsCode conversion tojsSo the code needs to be usedtypescriptInstallation method is as followsyarn install typescript -DUsually you write onetsconfig.jsonFile, and then after that we can runnpx tscTo compile your owntsThe code reads the configuration in the configuration file and is available heretsc --initGenerate the configuration file as shown below:At this point you can converttsCode, but converting every file is definitely inefficient so it can be used at this pointts-loaderCooperate withwebpackconvert
        • Install command

          yarn add ts-loader -D
        • configuration

          Packing results are as follows:

          foundtsThe code is converted to normal code
      • babel-loaderusebabel-loaderPackaging can be done using plug-ins@ Babel/tranform - typescript.Presets can also be used@babel/preset-typescriptI recommend using presets,
        • The installation

          yarn add @babel/preset-typescript -D
        • configurationThe running results are as follows:
      • The advantages and disadvantages
        1. babel-loaderSimply convert files without validation
        2. ts-loaderCan do code verification but if the code is useful to the feature and can not addpolyfill

        Therefore, it is not recommended to use language features in your code in general projectsts-loaderTo add the function of type verification, you can use it heretype-checkCan betsType of code to check:

        • Install type-check yarn add type-check -d

        • Configuration use:You can also view the problem of coding in real time as shown below:

          Summary: It is recommended to use babel-loader and type-check to achieve ‘TS’ in actual project practice

  • Analysis of execution principle of Babel compiler

    It can be roughly divided into three stages: parsing, transformation, code generation, and finally to the target source code. However, if it is subdivided into some lexical analysis, grammar analysis, plug-in, etc., the general flow chart is as follows: