我正在尝试使用 exif-js在 webpack+babeljs 项目中。这个库(exif-js)创建了一个全局变量“EXIF”,但我无法在 Chrome devtools 中访问它,也无法在我的 js 脚本中访问它。
我尝试使用 webpack Provide-plugin 使“EXIF”在所有页面中可见,但它不起作用。
plugins: [
new webpack.ProvidePlugin({
EXIF: 'exif-js/exif.js'
})
]
在 webpack 项目中使用这个库的最佳方式是什么?
谢谢!
最佳答案
看起来在 CommonJS 中,它导出 EXIF
var,而不是将其附加到全局范围。
这意味着使用 webpack 你可以像任何其他模块一样导入它:
var exif = require('exif-js');
要进行演示,请参阅 this webpackbin
如果您确实在全局范围内需要它,则可以在导入后手动将其附加到 window
对象:
var exif = require('exif-js');
window.EXIF = exif;
要回答有关使用设置全局变量的脚本的问题的实际标题,您通常可以使用 ProvidePlugin
(如您演示的那样),也可以使用 externals :
The externals configuration option provides a way of excluding dependencies from the output bundles. Instead, the created bundle relies on that dependency to be present in the consumer's environment. This feature is typically most useful to library developers, however there are a variety of applications for it.
例如(在您的webpack.config.js
中):
externals: {
jquery: 'jQuery'
}
但是,这与 ProvidePlugin
的工作方式不同。 ProvidePlugin
解析假定为全局的未声明变量,而 externals
将特定模块名称解析为假定存在的全局变量(例如:require('jquery')
将解析为 window.$
)。
关于javascript - 在 webpack 中使用带有全局变量的 NPM 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43708423/