JS问题整理与思考--ES6模块化如何使用,开发环境如何打包

使用方法

// util1.js
export default {
    a:100
}
// util2.js
export function fn1() {
    alert(1)
}
export function fn2() {
    alert(2)
}
// ------------------
// index.js
import util1 from './util1.js'
import {fn1,fn2} from './util2.js'

console.log(util1)
fn1()
fn3()

babel转译

  • 1.npm init
  • 2.npm install --save-dev babel-core babel-preset-es2015 babel-preset-latest
  • 3.创建.babelrc。
                {
            "presets": ["es2015","latest"],
            "plugins": []
            }
            
  • 4.sudo npm install -g babel-cli
  • 5.创建函数[1,2,3].map(item=>item+1),然后终端 babel index.js
                [1, 2, 3].map(function (item) {
                  return item + 1;
                });
            

webpack 模块化

  • npm install -save-dev webpack babel-loader
  • 创建webpack.config.js,并写入
    module.exports = {
        entry:'./index.js',
        output:{
            path:__dirname,
            filename:'./build/boundle.js'
        },
        module:{
            rules:[{
                test:/\.js?$/,
                exclude:/(node_modules)/,
                loader:'babel-loader'
            }]
        }
    }
            
  • package.json中添加
     "scripts": {
        "start":"webpack",
        "test": "echo \"Error: no test specified\" && exit 1"
      },
        
  • npm start(需要安装webpack-cli)

校验转译和模块化

  • 1.创建index.html,并引入build/boundle.js
  • 2.http-server -p 8881

rollup 使用

  • npm init
  • rollup wedive$ npm i --save-dev rollup rollup-plugin-node-resolve rollup-plugin-babel babel-core babel-plugin-external-helpers babel-preset-latest
  • 设置.babelrc
    {
      "presets": [
        ["latest",{
          "es2015":{
            "modules":false
          }
        }]
      ],
      "plugins": ["external-helpers"]
    }
            
  • 设置rollup.config.js
    import babel from 'rollup-plugin-babel'
    import resolve from 'rollup-plugin-node-resolve'
    
    export default {
        entry:'src/index.js',
        format:'umd',   // 兼容amd/commonjs
        plugin:[
            resolve(),
            babel({
                exclude:'node_modules/**'
            })
        ],
        dest:'build/build.js'
    }
            
  • 修改package.json
    "scripts": {
        "start": "rollup -c rollup.config.js"
    },
            

webpack和rollup代码对比

rollup功能单一,但是打包之后非常轻量

webpack功能强大,但打包出来比rollup大。

总结:

语法:import export(注意有无default)

环境:babel编译ES6语法,模块化可用webpack和rollup

扩展:对模块化标准统一对期望

随机浏览