Webpack_ (Chapter III) _ using Babel processing ES6 grammar

Use Babel processing ES6 syntax (1)

And how to combine webpack Babel so we write ES6 grammar in the project
to write some of the syntax ES6 in index.js

const arr = [
  new Promise(() => {}),
  new Promise(() => {})
]
arr.map(item => {
  console.log(item)
})

Run npx webpackpackaged
Why run npx webpackinstead configured with webpack-dev-server of npm run startit
because want to look at npx webpackpackaging generated main.js file if you use webpack-dev-serve package to do so, the generated files are packaged in memory inside
open main .js code is
Here Insert Picture Description
in main.js Finally, the code is actually packaged content index.js generated under src directory under the src code intact packing out, so this time there will be some problems. This code can not run correctly in a browser it?
Run npm run startlook ES6 operating results of
Here Insert Picture Description
the console can print out the promise object, which is why. Chrome browser with the times, a lot of content specification ES6 have done to achieve, so write ES6 grammar in the Chrome browser can be, but if you open the IE browser in it, especially some of the low version of the IE browser, Some browsers, including domestic, program execution will error, because these packages also main.js browser executing the generated code, the browser does not support syntax for ES6, it will error.
If we go on to write code in the src directory for ES6, webpack will ES6 the code into the code of ES5, so all browsers running on will not be a problem.
To achieve this function, we may be implemented by Babel.
Babel can convert ES6 syntax into a syntax ES5, we use Babel in webpack in.
Execution npm install -D babel-loader @babel/core, installation babel-loader and babel / core (Babel core library)
do the configuration items in webpack-config.js in a rule in increase

  module: {
    rules: [
      {
        test: /\.js/,
        exclude: /node_modules/, exclude的含义是如果js文件在node_modules中,那么就不使用babel-loader
        loader: 'babel-loader'
      }
    ]
   }

If the detected file is js, use babel-loader to perform semantic analysis.
Still need to install npm install @babel/preset-env -D
Why preset-env install this module, because when using the babe-loader js file processing, in fact, babel-loader just webpack and babel make a bridge of communication, and after using it webpack babel get through, but the actual the babel-loader does not help us to translate into js in the ES6 syntax into a syntax ES5 also need the help of some other modules to complete grammar translation, preset-env module is play this role, preset-env module includes All ES6 into rules of grammar ES5
installed the preset-env, need to do some configuration
using a loader when you can configure the options parameter to the loader

      {
        test: /\.js/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        options: {
          presets: ['@babel/preset-env']  将这个包名放在presets中就可以了
        }
      },

So far, the configuration is complete
execution npx webpack, view the generated main.js
Here Insert Picture Description
then found ES6 grammatical syntax became ES5's been translated, const becomes var, arrow function becomes normal function, but not enough light to do this, for example, promise this new syntax variables, including arrays inside the map method in a low version of the browser is actually non-existent, while doing a translation, but only a part of the translation, as well as some objects and functions and then some low version of the browser or not, it is not only the need to use the preset-env translator grammar, also need to supplement the missing variables or functions to lower version browser, how to add to it
using the babel of polyfill
install npm install --save @ babel / polyfill
installation End how to use it, just before the introduction of more than a code runs to go import '@babel.polybill'to supplement the lack of content enough
to import '@babel.polybill'put a head on it index.js file
after the code is now almost completed, and the use of @ babel / polyfill complete package the main.js will be a lot of great content, extra polyfill is going to add a low version of the browser does not exist. If we do not need to look useless to the syntax packaged into main.js, for example, now requires only promise and map method, how to configure it
to add a new argument to the preset-env

      {
        test: /\.js/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        options: {
          presets: [['@babel/preset-env', {
            useBuiltIns: 'usage'
          }]]
        }
      },

useBuiltIns: 'usage'When do mean as polyfill padding when the page to add some low version of the browser may not exist features, not all the features are added in, is based on the business code to decide. Added as needed.
All this packaged completed main.js much smaller than the package, you can also run in a low version

Use Babel processing ES6 grammar (2)

Babel's presets can also configure some additional parameters
such as targets property

        options: {
          presets: [['@babel/preset-env', {
            targets: {
              edge: '17',
              firefox: '60',
              chrome: '67',
              safari: '11.1',
            },
            useBuiltIns: 'usage'
          }]]
        }

Means that the package generated project will run under version is greater than 67, babel package in the process of using present-env binding babel / polyfill going to become the ES6 syntax grammar of ES5, depending on whether it is necessary to do ES6 conversion of ES5, whether it is necessary to inject about this project in the promise and function map, more than 67 versions of the Chrome browser, which ES6 support for good, in fact, no need to do this operation ES6 turn ES5, this configuration after come packaged, the project will be much smaller

In a development of the third-party libraries and modules when, or to develop a library of components used babel / polyfill this solution is problematic, because it is injected in the map and promise such a function, it will be in the form of a global variable injection, will contaminate the global environment, so in this case the packaged library or libraries UI components, the need for a way configured to remove the introduced polyfill in index.js.
Installation npm install @babel/plugin-transform-runtime -D
also install the npm install -save @babel/runtime
loader babel corresponding increase configuration plugins

        options: {
          // presets: [['@babel/preset-env', {
          //   targets: {
          //     edge: '17',
          //     firefox: '60',
          //     chrome: '67',
          //     safari: '11.1',
          //   },
          //   useBuiltIns: 'usage'
          // }]]
          plugins: [['@babel/plugin-transform-runtime', {
            corejs: 2,
            helpers: true,
            regenerator: true,
            useESModules: false
          }]]
        }

If you have configured corejs: 2,so requires additional installation npm install --save @babel/runtime-corejs2, repackaging project run
corejs: 2effect is when the page does not exist a promise and a map method when it will go to this package your code main.js which, if not configured, is not packaged the incoming
sum up, if only to write business code, then the configuration, then only need to configure presets, while the introduction of index.js babel / polyfill can, if writing is a library project code, requires the use of babel / plugins -transform-runtime plug-in, the benefits of this plugin is that you can effectively prevent a problem of presets, or is that a question of polyfill, polyfill will pollute the global, plugins-transform-runtime will be in the form of closure to injection, or help components corresponding to the introduction of the content, so the concept of global pollution does not exist, so when writing in the library do not pollute the global environment, it is a better solution.

babel corresponding configuration items will be very much, if we are careful to configure babel-related content, you'll find content options may be very much, how to solve this problem?
We can create a file in the root directory of a .babelrc project, the options that are out on the subject of the file
in the file .babelrc

{
  "plugins": [["@babel/plugin-transform-runtime", {
    "corejs": 2,
    "helpers": true,
    "regenerator": true,
    "useESModules": false
  }]]
}

Configuration options can remove the item in webpack.config.js configuration of babel

These are the two configurations often used babel

Published 137 original articles · won praise 30 · views 260 000 +

Guess you like

Origin blog.csdn.net/hani_wen/article/details/100029991