Lenny-Hu / note

blog
5 stars 1 forks source link

rollup使用笔记 #107

Open Lenny-Hu opened 3 years ago

Lenny-Hu commented 3 years ago

rollup 搭配 babel es6 2 es5

rollupjs官方文档

以下配置可转换 async、问号操作符等

package.json

{
  "name": "",
  "version": "1.0.0",
  "description": "",
  "main": "",
  "scripts": {
    "dev": "rollup --config rollup.config.js --watch",
    "prod": "cross-env NODE_ENV=production rollup --config rollup.config.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@babel/polyfill": "^7.12.1",
    "core-js": "3",
    "lodash": "^4.17.20"
  },
  "browserslist": "> 0.25%, not dead",
  "devDependencies": {
    "@babel/core": "^7.12.13",
    "@babel/preset-env": "^7.12.13",
    "@rollup/plugin-babel": "^5.2.3",
    "@rollup/plugin-commonjs": "^17.1.0",
    "@rollup/plugin-node-resolve": "^11.1.1",
    "babel-plugin-lodash": "^3.3.4",
    "cross-env": "^7.0.3",
    "rollup-plugin-terser": "^7.0.2"
  }
}

rollup.config.js

import relsolve from '@rollup/plugin-node-resolve';
import babel from '@rollup/plugin-babel';
import commonjs from '@rollup/plugin-commonjs';
import { terser } from 'rollup-plugin-terser';

export default {
  input: './rollup/main.js',
  output: [
    {
      file: './rollup/bundle.js',
      format: 'iife'
    },
    {
      file: './rollup/bundle.min.js',
      format: 'iife',
      name: 'version',
      plugins: [terser()]
    }
  ],
  plugins: [
    commonjs(),
    relsolve(),
    babel({
      babelHelpers: 'bundled',
      exclude: 'node_modules/**' // 只编译我们的源代码
    })
  ]
};

babel.config.json

{
  "presets": [
    [
      "@babel/preset-env",
      {
        "useBuiltIns": "usage",
        "corejs": 3
      }
    ]
  ],
  "plugins": ["lodash"]
}

rollup\main.js

import _ from 'lodash';  // 已配置优化lodash,只打包用到的
import a from './a';

const app = {
  data: {
    n: 1
  },
  sleep (ms = 1000) {
    return new Promise((resolve, reject) => {
      setTimeout(resolve, ms);
    });
  },
  async f1 () {
    console.log('打印a112222', a);
    console.log('睡眠1秒');
    await this.sleep();
    console.log('1秒后,即将睡眠5秒');
    await this.sleep(5000);
    console.log('5秒后');
    console.log(_.isArray([]));
    console.log(_.add(6, 4));
    console.log(_.repeat('*', 3));
  },
  init () {
    this.f1();
    console.log('应用初始化');

    if (this.data.n?.a) {
      console.log('问号');
    }
  } 
};

app.init();

rollup\a.js

const a = 1;
export default a;

rollup\index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="./bundle.min.js"></script>
</head>
<body>
  test rollup
</body>
</html>