html5 opendatabase is not defined,【前端】webpack 打包库时出现 window is not defined

按照官网的步骤进行库的打包 创建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

// webpack.config.js

module.exports = {

...

output: {

path: path.resolve(__dirname, 'dist'),

filename: 'webpack-numbers.js',

library: 'webpackNumbers',

globalObject: 'this', // 添加这个选项

libraryTarget: 'umd'

}

...

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值