您现在的位置是:首页 >技术教程 >rollup打包封装的js类库网站首页技术教程
rollup打包封装的js类库
简介rollup打包封装的js类库
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>
风语者!平时喜欢研究各种技术,目前在从事后端开发工作,热爱生活、热爱工作。