写一些基本文件
// 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" //通用引入方式
}
}
import library from 'library'
const library = require('library')
requrie(['library'],function() {
})
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