如何打包一个插件工具库
# 工具类
下面,我们就打包一个简单的工具函数,对此 js 文件分别进行 webpack 和 rollup 的打包
// index.js
function add(a, b) {
return a + b;
}
export { add };
1
2
3
4
5
2
3
4
5
打包之前我们先配置一些 package.json
{
"name": "tools",
"version": "0.0.1",
"description": "",
"main": "dist/eff.cjs.js", //包文件入口位置 默认index.js,应该放commonJs(cjs)模块,以require的方式引入模块
"module": "dist/eff.esm.js", //这里放es module(esm)模块,以import的方式引入模块应
"jsnext:main": "dist/eff.esm.js", //跟module一样,只是jsnext:main是社区支持的。而 module 则是官方字段,大量社区插件只认识jsnext:main所以建议"module"和"jsnext:main"一起使用
"browser": "dist/eff.browser.js", //可不通过编译直接在scrip src='dist/eff.browser.js'使用,但是打包时需要暴露出一个变量,可以直接在scrip标签中调用此变量
"scripts": {
"build:webpack": "webpack --config webpack.build.config.js", //使用webpack打包
"build:rollup": "npx rollup -c rollup.config.js" //使用rollup打包
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
# 使用 webpack
// webpack.build.config.js
const path = require("path");
var config = { module: {} };
var umd = Object.assign({}, config, {
entry: {
"eff.cjs": path.resolve(__dirname, "src/index.js"),
"eff.browser": path.resolve(__dirname, "src/index.js"),
},
output: {
path: path.resolve(__dirname, "./dist"),
filename: "[name].js",
library: {
type: "umd",
},
globalObject: "this", // 定义全局变量,兼容node和浏览器运行,避免出现"window is not defined"的情况
},
});
var esm = Object.assign({}, config, {
entry: {
"eff.esm": path.resolve(__dirname, "src/index.js"),
},
output: {
path: path.resolve(__dirname, "./dist"),
filename: "[name].js",
library: {
type: "module",
},
},
experiments: {
outputModule: true,
},
});
// Return Array of Configurations
module.exports = [esm, umd];
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# 使用 rollup
// rollup.config.js
import pkg from "./package.json";
import json from "rollup-plugin-json";
import resolve from "rollup-plugin-node-resolve";
import commonjs from "@rollup/plugin-commonjs";
import { babel } from "@rollup/plugin-babel";
import { terser } from "rollup-plugin-terser";
import filesize from "rollup-plugin-filesize";
const formatName = "eff";
export default {
input: "./src/index.js",
output: [
{
file: pkg.main,
format: "cjs",
},
{
file: pkg.module,
format: "esm",
},
{
file: pkg.browser,
format: "umd",
name: formatName,
},
],
plugins: [
terser(),
filesize(),
json(),
commonjs({
include: /node_modules/,
}),
resolve({
preferBuiltins: true,
jsnext: true,
main: true,
brower: true,
}),
babel({ exclude: "node_modules/**" }),
],
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# 点击查看源码 (opens new window)
编辑 (opens new window)
上次更新: 2022/06/01, 09:55:08