webpack4与babel配合使es6代码可运行于低版本浏览器

使用es6+新语法编写代码,可是不能运行于低版本浏览器,需要将语法转换成es5的。那就借助babel7转换,再加上webpack打包,实现代码的转换。

转换包括两部分:语法和API

let、const这些是新语法。

new promise()等这些是新API。

简单代码

类库 utils.js

const name = 'weiqinl'

let year = new Date().getFullYear()

export {  name,  year }

index.js

import _ from 'lodash'

import {  name,  year } from './utils'

Promise.resolve(year).then(value => {

  console.log(`${name} - ${value} - ${_.add(1, 2)}`)

})

babel转换

安装babel编译器和对应的运行时环境

npm install -D @babel/core @babel/preset-env @babel/plugin-transform-runtime @babel/polyfill babel-loader

并新建.babelrc文件,里面可以配置很多东西,内容为:

{

  "presets": [

    ["@babel/preset-env", {

      "useBuiltIns": "usage",

      "modules": false

    }]

  ],

  "plugins": [

    [

      "@babel/plugin-transform-runtime", {

        "corejs": false,

        "helpers": false,

        "regenerator": false,

        "useESModules": false

      }

    ]

  ],

  "comments": false

}

webpack构建

webpack4,可以零配置构建项目,那是因为它的很多配置值都默认了。在这里,我们需要自己配置。
首先安装webpack

npm i webpack webpack-cli -D

然后创建一个webpack.config.js文件

const path = require('path');

module.exports = {

  mode: "production",

  entry: ['@babel/polyfill', './src/index.js'],

  output: {

    path: path.resolve(__dirname, 'dist'),

    filename: '[name].bundle.js'

  },

  module: {

    rules: [{

      test: /\.js$/,

      include: [

        path.resolve(__dirname, 'src')

      ],

      exclude: /(node_modules|bower_components)/,

      loader: "babel-loader",

    }]

  }

}

使用

webpack构建打包好的js文件,我们将其引入到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>webpack-babel-es6</title>

</head>

<body>

  webpack构建由babel转码的es6语法,支持es6语法和API<br />

  请查看浏览器控制台

  <script src="./dist/main.bundle.js"></script>

</body>

</html>

运行该html,可以看到控制台有内容输出weiqinl - 2018 - 3

最后的目录结构:

目录结构

可以git查看源码https://github.com/weiqinl/demo/tree/master/webpack-bable-es6

[完]

posted @ 2018-10-11 17:03  weiqinl  阅读(6824)  评论(2编辑  收藏  举报