kgm-js-tools
v1.0.9
Published
kgm的javascript工具函数
Downloads
6
Readme
webpack打包组件和基础库
开发组件库基础
- 初始化:
npm init -y
- 安装webpack:
npm i webpack webpack-cli -D
- 修改
package.json
{ "scripts": { "build": "webpack" } }
- 安装压缩插件
- 可以指定压缩和不压缩的文件
npm i -D terser-webpack-plugin
- 设置入口文件:
package.json
的main字段为index.js - 新建:
index.js
- 发布:
npm publish
- 如果本机第一次发布包(非第一次可忽略)
- 在终端输入npm adduser,提示输入账号,密码和邮箱,然后将提示创建成功
- 非第一次发布包
- 在终端输入npm login,然后输入你创建的账号和密码,和邮箱,登陆,结果上
- 如何撤销发布的包
- 终端执行:
npm unpublish
- 删除某个版本:
npm unpublish [email protected]
- 删除整个npm市场的包:
npm unpublish z-tool --force
- 终端执行:
- 登录
npm login
- 注意
- 发包前必须取消
webpack.config.js
中的文件监听模式
- 发包前必须取消
初次发版相关代码
./src/index.js
function add(a, b) { return a + b } export default {add}
webpack.config.js
const TerserPlugin = require('terser-webpack-plugin') module.exports = { mode: "none", // production entry: { "large-number": "./src/index.js", // 开发版 "large-number.min": "./src/index.js", // 压缩版 }, output: { filename: "[name].js", library: "largeNumber", // 打包出来库的名字 libraryExport: "default", // libraryTarget: "umd", // }, // 匹配min.js文件才压缩 optimization: { minimize: true, minimizer: [ new TerserPlugin({ include: /\.min\.js$/ }) ] } }
index.js
if(process.env.NODE_ENV === 'production') { module.exports = require('./dist/large-number.min.js') } else { module.exports = require('./dist/large-number.js') }
package.json
{ "name": "large-number", // 包名 "version": "1.0.0", // 版本号 "description": "加法函数", // 包描述 "main": "index.js", // 入口文件 "scripts": { "build": "webpack", // 打包 "prepublish": "webpack", // 打包并发版 }, }
测试相关配置
- 开启文件监听
- 启动webpack命令时, 带上 --watch 参数。修改:
package.json
"scripts": { "build": "webpack", "watch": "webpack --watch" },
- 配置
webpack.config.js
module.exports = { // 默认false, 也就是不开启 watch: true, // 只有开启了监听模式,watchOptions才有意义 watchOptions: { // 默认为空, 不监听的文件或文件夹 ignored: /node_modules/, // 监听到变化后回等待300ms再去执行, 默认300ms aggregateTimeout: 300, // 判断文件是否发生变化是通过不停询问系统指定文件有没有发生变化实现的, 默认每秒询问1000次 poll: 1000 } }
- 启动webpack命令时, 带上 --watch 参数。修改:
解析ES6, react语法
- 安装插件:
npm i @babel/core @babel/preset-env babel-loader -D
// 用来编译ES6npm i -D @babel/plugin-proposal-class-properties
// 是用来编译class类的npm i -S react react-dom @babel/preset-react
// 用来编译react
- 使用babel-loader
module.exports = { module: { rules: [ { test: /\.js$/, loader: 'babel-loader', query: {compact: false} } ] } }
- 创建babel的配置文件: .babelrc
{ "presets": [ "@babel/preset-env", "@babel/preset-react" ], "plugins": [ "@babel/proposal-class-properties" ] }
使用source-map(代码追踪)
- 修改
webpack.dev.js
module.exports = { // 开启source-map(生成环境不要开启) devtool: 'inline-source-map', }