webpack4 babel 篇


demo 代碼點此,如果對 babel 不熟,可以看一下babel 7 簡單指北

webpack 使用 babel 來打包使用 es6 及以上語法的 js 文件是非常方便的,可以通過配置,將 es6 轉化為 es5.

start


准備個空文件,執行如下命令:

npm init -y
npm i -D webpack webpack-cli
npm i -D babel-loader @babel/core

然后創建一個 dist 文件夾,創建一個 html 文件:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>webpack4 babel 篇</title>
<body>
  <div id="root"></div>
<script type="text/javascript" src="bundle.js"></script></body>
</html>

根目錄下創建 webpack.config.js,配置 webpack:

const path = require('path');

module.exports = {
  mode: 'development',
  entry: {
    main: './index.js',
  },
  module: {
    rules: [
      { 
        test: /\.js$/, 
        exclude: /node_modules/, 
        loader: "babel-loader",
      },
    ],
  },
  devtool: 'source-map',
  // 出口
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
  },
}

為了轉化 es6 代碼,要安裝 babel 插件:

npm i -D @babel/preset-env @babel/polyfill

然后在根目錄下創建 babel 配置文件 .babelrc:

{
  "presets": [
    [
      "@babel/preset-env",
      {
        "useBuiltIns": "usage",
        "targets": {
          "browsers": ["last 2 versions", "ie >= 10"]
        }
      }
    ]
  ]
}

然后在根目錄下創建 index.js:

const add = (x, y) => {
  return new Promise((resolve, reject) => {
    resolve( x + y);
  });
}

add(1, 2).then(res => console.log(res));

打包


終端執行打包:

npx webpack

打開 dist 目錄下的 bundle.js,可以看見代碼已經轉為 es5,搜索 promise,會發現加上了 promise 的 polyfill:

// bundle.js

...
var add = function add(x, y) {
  return new Promise(function (resolve, reject) {
    resolve(x + y);
  });
};

add(1, 2).then(function (res) {
  return console.log(res);
});
...

訪問 index.html,console 也打印正常。

防止全局污染


如果是寫第三方庫或者框架,使用 polyfill 可能會造成全局污染,所以可以使用 @babel/plugin-transform-runtime 防止全局污染。

安裝:

npm i -D @babel/plugin-transform-runtime
npm i -S @babel/runtime @babel/runtime-corejs2

修改 babel 配置:

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

打包即可。

備注


這個主要是 babel 的配置。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM