webpack打包组件和基础库

webpack除了打包应用,也可以用来打包js库

  • 需要打包压缩版和非压缩版本
  • 支持 AMD/CJS/ESM 模块引入

如何将库暴露出去?

  • library:指定库的全局变量
  • libraryTarget:支持库引入的方式

1、新建项目,并安装webpack和wbpack-cli

npm init -y
npm i webpack webpack-cli -D

2、新建目录 src/index.js, 此处使用大整数求和算法作为案例

export default function add(a, b) {
  let i = a.length - 1
  let j = b.length - 1
  let carry = 0
  let ret = ''
  while (i >= 0 || j >= 0) {
    let x = 0
    let y = 0
    let sum
    if (i >= 0) {
      x = a[i] - '0'
      i --
    }
    if (j >= 0) {
      y = b[j] - '0'
      j --
    }
    sum = x + y + carry
    if (sum >= 10) {
      carry = 1
      sum -= 10
    } else {
      carry = 0
    }
    ret = sum + ret
  }
  if (carry) {
    ret = carry + ret
  }
  return ret
}

// add('1', '999')
// add('999', '1')
// add('99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999', '1')

3、安装terser-webpack-plugin压缩插件

npm i terser-webpack-plugin -D

4、新建webpack.config.js文件

const TerserPlugin = require('terser-webpack-plugin') // 引入压缩插件

module.exports = {
  entry: {
    'large-number': './src/index.js',
    'large-number.min': './src/index.js'
  },
  output: {
    filename: '[name].js',
    library: 'largeNumber',
    libraryTarget: 'umd',
    libraryExport: 'default'
  },
  mode: 'none', // 设置mode为none避免默认压缩
  optimization: {
    minimize: true,
    minimizer: [
      new TerserPlugin({ // 使用压缩插件
        include: /\.min\.js$/
      })
    ]
  }
}

5、配置package.json文件

{
  "name": "large-number",
  "version": "1.0.0",
  "description": "大整数加法打包", // 包或者库的描述
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack",
    "prepublish": "webpack" // 钩子
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "terser-webpack-plugin": "^1.3.0",
    "webpack": "^4.34.0",
    "webpack-cli": "^3.3.5"
  }
}

6、设置入口文件,由于package.json的main字段为index.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')
}

7、发布(需要npm账号,且登入)

npm publish

8、README文档看情况补充,此时发布成功,可通过npm i large-number -s在其他项目中引入该库

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值