javascript - 在 webpack 中使用带有全局变量的 NPM 模块

标签 javascript node.js webpack babeljs web-component

我正在尝试使用 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/

相关文章:

angularjs - 当 Loopback find() 的子级为空时,从第一级过滤器中排除项目

node.js - “AWSCognito”未定义

javascript - 浏览器可能不使用缓存

javascript - 使用 jQuery 添加/删除多个输入类型文本

javascript - 如何在浏览器历史记录中找到当前位置索引

javascript - 我的 html 表单验证不起作用

javascript - 滑动窗口根据内部元素改变大小

node.js - 从 npm : no such option --no-parallel 安装 ctags

webpack - 错误 : Should not import the named export 'version' (imported as 'version' )

npm - 开发时如何使用Webpack避免React加载两次