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

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

问题描述

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

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

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

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

这适用于忽略库,但是当我运行 webpacker 时它仍然说所需的模块丢失".

不知何故,我需要告诉 webpack 应该从全局上下文中获取 jquery .似乎是一个常见的用例,所以我有点惊讶文档没有专门针对这个.

解决方案

根据 Webpack 文档

a>,您可以使用 config 对象上的 externals 属性为您的库指定依赖项,这些依赖项不会被 webpack 解析,而是成为输出的依赖项.这意味着它们是从环境中导入的,而运行时 [原文如此]."

该页面上的示例使用 jQuery 很好地说明了这一点.简而言之,您可以使用普通的 CommonJS 风格的 jQuery:

var jQuery = require('jquery');

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

{外部:{//require("jquery") 是外部可用的//在全局变量 jQuery 上"jquery": "jQuery"}}

Webpack 创建的结果模块将简单地导出现有的全局变量(为了简洁,我在这里省略了很多东西):

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

我试过了,它和描述的一样工作.

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

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.

I’ve tried using plugins like the IgnorePlugin:

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

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

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.

解决方案

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]."

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');

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"
    }
}

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天全站免登陆