一、优点
1、文件小,打包后仅一个js文件 2、引入js后可全局使用,不必单独import每个方法 3、上传仓库可供他人npm下载使用 补充:封装自定义工具代码包:代码包
二、使用步骤
1、在编写的项目代码(非中文)文件夹里面输入cmd命令 npm init -y,会在根目录生成一个package.json文件,如下图
2、npm install webpack webpack-cli,会在根目录生成一个文件夹node_modules
3、手动新建文件webpack.config.js,写入以下内容:
const path = require('path');
module.exports = {
mode: 'development',
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'furenqiang-utils.js',
library: 'utils',
libraryTarget: 'umd',
},
}
4、新建指定的入文件(entry: ‘./src/index.js’,)index.js,写入需要导出的方法有哪些,模块化导出的内容、语法可参考以下代码:
export { apply } from "./function/apply";
export { bind } from "./function/bind";
export { call } from "./function/call";
export { debounce } from "./function/debounce";
export { throttle } from "./function/throttle";
export { chunk } from "./array/chunk";
export { concat } from "./array/concat";
export {
map,
reduce,
filter,
find,
findIndex,
every,
some,
} from "./array/declares";
export { difference } from "./array/difference";
export { drop, dropRight } from "./array/drop";
export { flatten } from "./array/flatten";
export { pull, pullAll } from "./array/pull";
export { slice } from "./array/slice";
export { unique } from "./array/unique";
export { clone1, clone2 } from "./object/clone";
export {
deepClone1,
deepClone2,
deepClone3,
deepClone4,
} from "./object/deepClone";
export { mergeObject } from "./object/mergeObject";
export { myInstanceOf } from "./object/myInstanceOf";
export { newInstance } from "./object/newInstance";
export { reverseString, palindrome, truncate } from "./string/reverseString";
export { myAddEventListener } from "./eventBind/myAddEventListener";
export { eventBus } from "./eventBind/eventBus";
export { PubSub } from "./eventBind/myPubSub";
5、在package.json文件中加入脚本,内容如下:
"scripts": {
"build:watch": "webpack --watch",
},
6、输入打包cmd命令:npm run build:watch 。打包成功后看到如下文件
7、测试使用。新建html文件,引入打包后的js文件,如下图:
三、上传npm仓库
上面第一步中package.json可参考以下代码:
{
"name": "furenqiang-own-util",
"version": "1.0.1",
"description": "",
"main": "./dist/furenqiang-utils.js",
"directories": {
"test": "test"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build:watch": "webpack --watch"
},
"keywords": [
"furenqiang",
"utils",
"array",
"object",
"function",
"string",
"axios",
"event-bus",
"pub-sub"
],
"author": "furenqiang",
"license": "ISC",
"dependencies": {
"webpack": "^5.16.0",
"webpack-cli": "^4.4.0"
}
}
|