我正在尝试使用 Require 将 PubNub 加载到我的项目中。但是当我尝试初始化“PubNub”时,它返回为未定义。
我已经下载了当前的 pubnub.4.20.1.js 并将其包含在我的项目的脚本文件夹中。这是我的需要代码:
require.config({
paths: {
jquery: '../../jquery-2.2.3.min',
bootstrap: '../../bootstrap.min',
underscore: '../../underscore.min',
backbone: '../../backbone.min',
marionette: '../../backbone.marionette.min',
handlebars: '../../handlebars.min',
pubnub: '../../pubnub.4.20.1'
},
shim: {
underscore: {
exports: '_'
},
backbone: {
deps: ["underscore", "jquery"],
exports: "Backbone"
},
marionette: {
deps: ["backbone"],
exports: "Marionette"
},
pubnub: {
exports: "PubNub"
}
}});
require(
["marionette",
"handlebars",
"bootstrap",
"pubnub"], function (Marionette, PubNub) {
window.App = new Marionette.Application();
// Initialize Pubnub
App.pubnub = PubNub.init({
publish_key: 'pub-c-0d5593f5-bf33-4d4a-b3a7-70a941b2282b',
subscribe_key: 'sub-c-e4b4d296-1bd4-11e8-a9da-22fca5d72012'
});
);
任何帮助将不胜感激!
最佳答案
PubNub 和 Require JS
Update: See Louis's answer on this page.
PubNub SDK is WebPacked. You have to do extra steps to make it work with RequireJS. See answer from @Louis PubNub and Require JS on this page.
- 问题:Webpack 不会 bundle 含 requireJS/AMD 语法的文件。
- 问题:有没有办法让 webpack 与 requireJS 配合良好?
- 答案:参见 Louis 的答案 https://stackoverflow.com/a/49040241/524733
RequireJS 和 Webpack 会自动很好地协同工作。在这种情况下,@SingingSmitty 发布的原始问题表明 shim
的使用是错误的。根据路易斯的说法:
You should use
shim
only for code that does not register itself as a proper AMD module. Code that calls define registers itself as a proper AMD module, so you don't use shim for such code. You should remove the shim for PubNub because it calls define (look in the source code, at the start of the file). Unless you are using antiquated versions of Underscore, Backbone and Marionette, you should also remove the shim entries for them because they are proper AMD modules. Read full answer from Louis on this page.In the problem provided by the OP ( @SingingSmitty ), they do in fact play well together. The OP went and did something they should not have done: defining erroneous shim. The usage of shim is entirely orthogonal to whether Webpack is involved. Webpack can produce bundles that require shim and can produce bundles that don't. Moreover, whether to use shim or not is entirely independent on whether Webpack is part of the toolchain that produced the bundle.
这篇博文描述了这段旅程http://devalias.net/devalias/2017/08/05/unexpected-journey-webpack-requirejs/使用 Webpack 和 RequireJS。
下面还有一些链接。
https://gist.github.com/xjamundx/b1c800e9282e16a6a18e https://www.npmjs.com/package/requirejs-to-webpack-cli
关于requirejs - 使用 Require.js 加载 PubNub,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49018398/