(一)一般组件库的引入方式有这样三种:
// es6 引入 import lodash from 'lodash' // commonJs 引入 const lodash = require('lodash') // cdn 引入 <script src="https://test.cn/library.js"></script>(二)配置
const path = require('path') module.exports = { entry: './src/index.js', mode: 'production', output: { path: path.join(__dirname, 'dist'), filename: 'library.js', libraryTarget: 'umd', // 不管在commonjs、AMD、CMD 引入,都能引入到 library: 'utils' // 支持script标签引入,全局变量叫 math } }src/math.js:
function add (a, b) { return a + b } function minus (a, b) { return a - b } function multiply (a, b) { return a * b } function division (a, b) { return a / b } export { add, minus, multiply, division }src/string.js
function join (a, b) { return a + b } export { join }src/index.js:
导入,最后作为出口文件统一导出:
import * as math from './math' import * as string from './string' export { math, string }package.json:
"scripts": { "build": "webpack --config webpack.config.js" },然后 npm run build 打包~生成 dist/library.js
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script src="./dist/library.js"></script> <script type="module"> console.log(utils.math.add(1, 2)) // 3 console.log(utils.math.minus(1, 2)) // -1 console.log(utils.string.join('1', '2')) // 12 </script> </body> </html>utils 相当于引入后挂载到了window下~
(三) libraryTarget的参数
library是指定义一个全局使用的名称变量
libraryTarget是指设置 library的暴露方式,是commonjs、commonjs2、umd 或者 this、window等
注意:libraryTarget 是 library 的暴露方式
对象定义:
libraryTarget:“window”,在window对象上定一个library设置的变量。在node环境下不支持。libraryTarget:“global”,在global对象上定义一个library设置的变量。受target属性影响,当target为默认值web时,会在window上注册,如果你想在global上注册,必须修改target为node。libraryTarget:“this”,在当前this对象上定义一个library设置的变量,如果this是window,就在window。在node的环境中,如果没指定require赋值的变量,并不会在指向global。模块定义:
libraryTarget:“commonjs”,在export对象上定义library设置的变量。在node中支持,浏览器中不支持。libraryTarget:“commonjs2”,直接用module.export导出export,会忽略library设置的变量。在node中支持,在浏览器中不支持。libraryTarget:“amd”,在define方法上定义library设置的变量,不能用script直接引用,必须通过第三方模块RequireJS来时用(四)externals 参数
const path = require('path') module.exports = { entry: './src/index.js', mode: 'production', externals: ['lodash'], // 打包忽略的库,比如utils // lodash 在 commonjs 方式加载,忽略打包 // externals: { // lodash: { // commonjs: 'lodash' // } // }, output: { path: path.join(__dirname, 'dist'), filename: 'library.js', libraryTarget: 'umd', // 不管在commonjs、AMD、CMD 引入,都能引入到 library: 'utils' // 支持script标签引入,全局变量叫 utils } }(五)修改package.json
"main": "./dist/library.js",这样就配置好了,可以发布到 npm 上了,注意:npm 仓库中库的名字是不能重复的
