按照官网的步骤进行库的打包 创建library
webpack.config.js
var path = require('path');
module.exports = {
entry: './src/index.js',
mode: 'production',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'webpack-numbers.js',
library: 'webpackNumbers', // 支持多种模式的导出
libraryTarget: 'umd'
},
externals: {
lodash: {
commonjs: 'lodash',
commonjs2: 'lodash',
amd: 'lodash',
root: '_'
}
},
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.toLowerCase() === word.toLowerCase()) ? ref.num : accum;
}, -1);
}
使用 test.js 测试导出的包在 node 环境能否使用
const _ = require('lodash')
const webpackNmuners = require('../dist/webpack-numbers')
console.log(webpackNmuners.numToWord(4))
console.log(webpackNmuners.wordToNum('four'))
运行时报错
ReferenceError: window is not defined
查看打包出来的模块,发现确实存在 window 对象
如果存在 window 对象,那么这个模块就不能在 node 环境中使用
但是我现在的配置和官网都是一致的,不应该出现这种情况啊
现在要使库生效,我得手动进入打包后的文件把 window 改为 this
请问一下这是哪里出了问题,webpack 版本是 webpack 4.29.6
你需要在
output
里面设置globalObject
output.globalObject