我们常用的一些库,可以自行打包,发布到npm仓库。
具体步骤;
1、执行npm init -y
,初始化一个package.json
文件
2、完成库文件代码书写
3、创建
webpack.config.js
文件,查看详细配置
const path = require('path');
module.exports = {
mode: "production",
entry: "./src/index.js",
output: {
path: path.resolve(__dirname, "dist"),
filename: "library.js",
library: "root", //
libraryTarget: "umd" //umd:表示支持amd、cmd、commonjs、es6 module、import所有这些引入方式
},
externals: "lodash" //防止将某些 import 的包(package)打包到 library.js 中,而是在运行时(runtime)再去从外部获取这些扩展依赖(external dependencies)。
};
4、执行npx webpack
打包
5、修改package.json
文件
{
"name": "6feel-library-test",
"version": "1.0.0",
"description": "",
"main": "./dist/library.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack"
},
"keywords": [],
"author": "飞牛",
"license": "MIT",
"devDependencies": {
"webpack": "^4.43.0",
"webpack-cli": "^3.3.11"
},
"dependencies": {
"lodash": "^4.17.15"
}
}
6、到npm官网创建账号
7、本地npm login
登录
8、执行npm publish
发布成功,完成操作。【例子在线演示】
然后就可以npm i 6feel-library-test
进行安装了;
调用时注意,webpack.config.js
中配置了externals: "lodash"
,表示lodash
这个包没有被打包在./dist/library.js
中,所以还需要引入lodash
;
import _ from "lodash";
import 6feel-library-test from " 6feel-library-test";