您现在的位置是:首页 >技术教程 >rollup打包封装的js类库网站首页技术教程

rollup打包封装的js类库

疆~ 2023-06-13 04:00:03
简介rollup打包封装的js类库

rollup中文网:简介 | rollup.js 中文文档 | rollup.js中文网Rollup 是一个 JavaScript 模块打包器,可以将小块代码编译成大块复杂的代码,Rollup 对代码模块使用新的标准化格式,这些标准都包含在 JavaScript 的 ES6 版本中。https://www.rollupjs.com/ 

 

package.json

{
  "name": "lj3d",
  "version": "1.0.0",
  "description": "",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1",
    "build": "rollup -c",
    "dev": "rollup -c -w"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.12.10",
    "@babel/preset-env": "^7.12.11",
    "@rollup/plugin-babel": "^5.2.2",
    "@rollup/plugin-node-resolve": "^11.0.1",
    "rollup": "^2.35.1",
    "rollup-plugin-terser": "^7.0.2"
  },
  "main": "dist/cjs/index.js",
  "module": "dist/esm/index.js",
  "files": [
    "dist"
  ]
}

rollup.config.js

import { nodeResolve } from "@rollup/plugin-node-resolve";
import { terser } from "rollup-plugin-terser";
import babel from "@rollup/plugin-babel";
import { name } from "./package.json";
let input = ["src/index.js"]
export default [
  {
    // UMD
    input,
    plugins: [
      nodeResolve(),
      babel({
        babelHelpers: "bundled",
      }),
      terser()
    ],
    output: {
      file: `dist/${name}.min.js`,

      format: "umd",
      name: "lj3d", // 全局对象名
      esModule: false,
      exports: "named",
      sourcemap: false,
    },
  },
  // ESM and CJS
  {
    input,
    plugins: [nodeResolve()],
    output: [
      {
        dir: "dist/esm",
        format: "esm",
        exports: "named",
        sourcemap: true,
      },
      {
        dir: "dist/cjs",
        format: "cjs",
        exports: "named",
        sourcemap: true,
      },
    ],
  },
];

.babelrc.json

{
    "presets": [["@babel/env", { "modules": false }]]
  }

src/A/A1/index.js:

export default class A1 {
    constructor(name) {
        this.name = name
    }
    say() {
        console.log("大家好,我是:", this.name)
    }
}

打包

执行命令:npm run build  【即执行:rollup -c】,-c表示读取配置文件

 

 

测试 

 index.html:

<html>

<head>
  <script src="../dist/lj3d.min.js"></script>
</head>

<body>
  <script>
    console.log("window.lj3d:", window.lj3d)
    let a1 = new lj3d.A.A1('张三a')
    console.log("a1:", a1)
    a1.say()
  </script>
</body>

</html>

 

 

风语者!平时喜欢研究各种技术,目前在从事后端开发工作,热爱生活、热爱工作。