webpack学习第十八步—— 生成库文件

写一些基本文件

// math.js
export function add(a,b) {
    return a + b
}
export function minus(a,b) {
    return a - b
}
export function multi(a,b) {
    return a * b
}
export function div(a,b) {
    return a / b
}
// string.js
export function join(a,b) {
    return a + ' ' + b
}
// index.js
import * as math from './math'
import * as string from './string'

export default {
    math,
    string
}

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变量
        library: 'library',
        libraryTarget: "umd" //通用引入方式
    }

}
  • umd代表支持以下引入方式
import library from 'library'
const library = require('library')
requrie(['library'],function() {
})
  • 在全局变量里增加library变量
library.math
  • 如果注释掉library: 'library',则无法使用library
  • libraryTarget为this,library则会挂载到this上(挂载this/window或者node环境下挂载到global)
library: 'library'
// 不支持commonjs、amd的引入方式,全局变量挂载到this上
libraryTarget: "this"

lib包引入三方库如何处理

  • 修改string.js引入lodash,此时打包会有lodash的内容
import _ from 'lodash'
export function join(a,b) {
    return _.join(a,b)
}
  • 修改webpack.config.js,增加externals
externals: ['lodash']
  • 根据配置方式引用
externals: {
    lodash: {
        root: '_',
        commonjs: 'lodash' //库在CommonJS环境被使用,lodash被引用时必须叫lodash
    }
}
  • 普通配置
externals: {
    lodash: 'lodash'// 起名叫做lodash
}

npm包发布

  • 新建.npmignore文件,我们要发布的就是dist文件夹中的内容
node_modules/
src/
webpack.config.js
  • 在npm官网注册账号
  • npm adduser添加账号密码
username: dingsusu
password: 同QQ密码
  • npm publish发布到仓库上
  • 撤销npm包 npm --force unpublish

你可能感兴趣的:(webpack学习第十八步—— 生成库文件)