Webpack和外部库 [英] Webpack and external libraries

查看:315
本文介绍了Webpack和外部库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用webpack( http://webpack.github.io/ )并且它看起来非常好,但是我有点卡在这里。

I’m trying out webpack (http://webpack.github.io/) and it looks really nice, however I’m kind of stuck here.

假设我正在使用CDN作为库,f.ex jQuery。然后在我的代码中,我希望 require('jquery')自动指向全局jquery实例,而不是尝试从我的模块中包含它。

Say that I’m using a CDN for a library, f.ex jQuery. Then in my code, I want the require('jquery') to automatically point to the global jquery instance, instead of trying to include it from my modules.

我尝试过使用像 IgnorePlugin 这样的插件:

I’ve tried using plugins like the IgnorePlugin:

new webpack.IgnorePlugin(new RegExp("^(jquery|react)$"))

这适用于忽略库,但它仍然表示当我运行webpacker时所需的模块丢失。

This works for ignoring the library, but it still says that the required module is "missing" when I run the webpacker.

不知何故我需要告诉webpack应该从全局上下文中选择 jquery 。看起来像是一个常见的用例,所以我很惊讶文档没有专门针对这个。

Somehow I need to tell webpack that jquery should be picked up from the global context instead. Seems like a common use case, so I’m kind of surprised that the docs doesn’t target this specifically.

推荐答案

根据到 Webpack文档,您可以使用 externals 属性指定库的依赖关系,这些依赖关系不是由webpack解析的,而是成为输出的依赖关系。这意味着它们是在运行时[sic]从环境导入的。

According to the Webpack documentation, you can use the externals property on the config object "to specify dependencies for your library that are not resolved by webpack, but become dependencies of the output. This means they are imported from the enviroment while runtime [sic]."

该页面上的示例使用jQuery很好地说明了这一点。简而言之,您可以使用正常的CommonJS样式的jQuery:

The example on that page illustrates it really well, using jQuery. In a nutshell, you can require jQuery in the normal CommonJS style:

var jQuery = require('jquery');

然后,在您的配置对象中,使用 externals 将jQuery模块映射到全局 jQuery 变量的属性:

Then, in your config object, use the externals property to map the jQuery module to the global jQuery variable:

{
    externals: {
        // require("jquery") is external and available
        //  on the global var jQuery
        "jquery": "jQuery"
    }
}

由Webpack创建的结果模块将只需导出现有的全局变量(为简洁起见,我在这里遗漏了很多东西):

The resulting module created by Webpack will simply export the existing global variable (I'm leaving out a lot of stuff here for brevity):

{
    1: function(...) {
        module.exports = jQuery;
    }
}

我试过这个,它的工作方式与描述一样。

I tried this out, and it works just as described.

这篇关于Webpack和外部库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆