webpack打包library发布到npm
项目结构
$ tree
.
├── package.json
├── src
│ └── index.js
└── webpack.config.js
入口文件 index.js
// src/index.js
export function echo(message) {
console.log(message);
}
依赖配置 package.json
{
"name": "more-echo",
"version": "1.0.0",
"description": "a demo for webpack package to npm",
"main": "dist/more-echo.js",
"scripts": {
"build": "webpack"
},
"keywords": [
"demo"
],
"author": "",
"license": "ISC",
"devDependencies": {
"webpack": "^5.72.1",
"webpack-cli": "^4.9.2"
}
}
配置文件 webpack.config.js
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'more-echo.js',
library: {
name: 'moreEcho',
type: 'umd',
},
},
};
参考 https://www.ctyun.cn/portal/link.html?target=https%3A%2F%2Fwebpack.docschina.org%2Fguides%2Fauthor-libraries%2F
打包发布
# 打包
$ npm run build
# 发布
$ npm publish
npm地址:https://www.ctyun.cn/portal/link.html?target=https%3A%2F%2Fwww.npmjs.com%2Fpackage%2Fmore-echo
Node环境中使用
npm i more-echo
示例
const { echo } = require('more-echo');
echo('Hello World!');
浏览器中使用
<script src="./dist/more-echo.js"></script>
<script>
moreEcho.echo('Hello World');
</script>