webpack之创建library
webpack之创建library
假设我们用webpack打包一个我们编写的JavaScript库,并在项目中引用
demo
项目目录
index.js
import _ from "lodash";
import numRef from "./ref.json";
export function numToWord(num){
return _.reduce(numRef,(accum,ref) => {
return ref.num === num ? ref.word : accum;
},'')
};
export function wordToNum(word){
return _.reduce(numRef,(accum,ref) => {
return ref.word === word && word.toLowerCase()? ref.num : accum
},-1);
}
ref.json
[
{
"num":1,
"word":"One"
},
{
"num":2,
"word":"Two"
},
{
"num":3,
"word":"Three"
},
{
"num":4,
"word":"Four"
},
{
"num":5,
"word":"Five"
},
{
"num":0,
"word":"Zero"
}
]
webpack.library1.js
const path = require("path");
module.exports = {
entry:path.resolve(__dirname,"src/index.js"),
output:{
filename:"[name].js",
path:path.resolve(__dirname,"library")
}
}
在package.json中加入字段
"webpackLibaray1":"webpack --config demo/webpack-library/webpack-library1/webpack.library1.js"
执行npm run webpackLibaray1
将打包的结果引入到index.html中
在console控制台中显示的结果如下
由结果我们可以看出当我们访问引的js文件,调用内部方法时候报错,这是为什么呢?
webpack的打包是基于模块来打包的,也就是说经过打包的文件代码是被打包到一个函数里,此时所有的变量或者方法已变成局部的。这样就访问不到引用文件内部的方法
解决方法
如果生成的输出文件,是在HTML页面中作为一个script标签引入,则可以通过设置webpack配置文件output.library和output.libraryTarget
output.libraryTarget
- 变量:作为一个全局变量,通过script标签来访问(
libraryTarget:'var'
) - this :通过this对象访问(
libraryTarget:'this'
) - window:通过window对象访问,在浏览器中(
libraryTarget:'window'
) - UMD:在AMD或CommonJs的require之后可访问(
libraryTarget:'umd'
)
修改webpack配置文件如下
const path = require('path');
module.exports = {
mode: 'production',
entry:path.resolve(__dirname,"src/index.js"),
output: {
path: path.resolve(__dirname, './dist'),
filename: 'webpack-numbers.js',
libraryTarget: 'umd',
globalObject: 'this',
// libraryExport: 'default',
library: 'webpackNumbers'
},
externals: {
'lodash': {
commonjs: 'lodash',
commonjs2: 'lodash',
amd: 'lodash',
root: '_'
}
},
}