天天看點

使用 Webpack 與 Babel 配置 ES6 開發環境使用 Webpack 與 Babel 配置 ES6 開發環境

使用 Webpack 與 Babel 配置 ES6 開發環境

安裝 Webpack

安裝:

# 本地安裝
$ npm install --save-dev webpack webpack-cli

# 全局安裝
$ npm install -g webpack webpack-cli
           

在項目根目錄下建立一個配置檔案—— webpack.config.js 檔案:

const path = require('path');

module.exports = {
  mode: 'none',
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  }
}
           

在 src 目錄下建立 a.js 檔案:

export const isNull = val => val === null

export const unique = arr => [...new Set(arr)]
           

在 src 目錄下建立 index.js 檔案:

import { isNull, unique } from './a.js'

const arr = [1, 1, 2, 3]

console.log(unique(arr))
console.log(isNull(arr))
           

執行編譯打包指令,完成後打開 bundle.js 檔案發現 isNull 和 unique 兩個函數沒有被編譯,和 webpack 官方說法一緻:webpack 預設支援 ES6 子產品文法,要編譯 ES6 代碼依然需要 babel 編譯器。

安裝配置 Babel 編譯器

使用 Babel 必須先安裝 @babel/core 和 @babel/preset-env 兩個子產品,其中 @babel/core 是 Babel 的核心存在,Babel 的核心 api 都在這個子產品裡面,比如:transform。而 @babel/preset-env 是一個智能預設,允許您使用最新的 JavaScript,而無需微觀管理您的目标環境需要哪些文法轉換(以及可選的浏覽器polyfill)。因為這裡使用的打包工具是 Webpack,是以還需要安裝 babel-loader 插件。

安裝:

$ npm install --save-dev @babel/core @babel/preset-env babel-loader
           

建立 .babelrc 檔案:

{
  "presets": [
    "@babel/preset-env"
  ]
}
           

修改 webpack 配置檔案(webpack.config.js):

const path = require('path');

module.exports = {
  mode: 'none',
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  },
  module: {
    rules: [
      {
        test: /\.js$/,
          loader: 'babel-loader',
          exclude: /node_modules/
      }
    ]
  }
}
           

由于 babel 預設隻轉換 ES6 新文法,不轉換新的 API,如:Set、Map、Promise等,是以需要安裝 @babel/polyfill 轉換新 API。安裝 @babel/plugin-transform-runtime 優化代碼,@babel/plugin-transform-runtime 是一個可以重複使用 Babel 注入的幫助程式代碼來節省代碼的插件。

安裝 @babel/polyfill、@babel/plugin-transform-runtime 兩個插件:

$ npm install --save-dev @babel/polyfill @babel/plugin-transform-runtime
           

修改 .babelrc 配置檔案:

{
  "presets": [
    ["@babel/preset-env", {
      "useBuiltIns": "usage", // 在每個檔案中使用polyfill時,為polyfill添加特定導入。利用捆綁器隻加載一次相同的polyfill。
      "modules": false // 啟用将ES6子產品文法轉換為其他子產品類型,設定為false不會轉換子產品。
    }]
  ],
  "plugins": [
    ["@babel/plugin-transform-runtime", {
      "helpers": false
    }]
  ]
}
           

最後,配置相容的浏覽器環境。在 .babelrc 配置檔案中設定 targets 屬性:

{
  "presets": [
    ["@babel/preset-env", {
      "useBuiltIns": "usage",
      "modules": false,
      "targets": {
        "browsers": "last 2 versions, not ie <= 9"
      }
    }]
  ],
  "plugins": [
    ["@babel/plugin-transform-runtime", {
      "helpers": false
    }]
  ]
}
           

執行指令編譯代碼,完成後檢查 bundle.js 檔案,是否成功轉換新 API 。如果發現以下代碼即說明轉換成功:

// 23.2 Set Objects
module.exports = __webpack_require__(80)(SET, function (get) {
  return function Set() { return get(this, arguments.length > 0 ? arguments[0] : undefined); };
}, {
  // 23.2.3.1 Set.prototype.add(value)
  add: function add(value) {
    return strong.def(validate(this, SET), value = value === 0 ? 0 : value, value);
  }
}, strong);
           

其他關于 js 壓縮和 Webpack 啟用 tree shaking 功能的設定本文不在贅述。

配置檔案詳情概覽

package.json 檔案:

{
  "name": "demo",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "webpack"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.3.4",
    "@babel/plugin-transform-runtime": "^7.3.4",
    "@babel/polyfill": "^7.2.5",
    "@babel/preset-env": "^7.3.4",
    "babel-loader": "^8.0.5",
    "webpack": "^4.29.6",
    "webpack-cli": "^3.2.3"
  }
}
           

webpack.config.js 檔案:

const path = require('path');

module.exports = {
  mode: 'none',
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  },
  module: {
    rules: [
      {
        test: /\.js$/,
          loader: 'babel-loader',
          exclude: /node_modules/
      }
    ]
  }
}
           

.babelrc 檔案:

{
  "presets": [
    ["@babel/preset-env", {
      "useBuiltIns": "usage",
      "modules": false,
      "targets": {
        "browsers": "last 2 versions, not ie <= 9"
      }
    }]
  ],
  "plugins": [
    ["@babel/plugin-transform-runtime", {
      "helpers": false
    }]
  ]
}
           

符錄

usuallyjs 項目是本人最近建設的開源項目,歡迎感興趣的同行交流。

usuallyjs: https://github.com/JofunLiang/usuallyjs