使用require.js加载非amd模块

9

目前我正在使用require.js进行一个有趣的副业项目,除了一个名为prism.js的代码语法高亮插件外,一切都正常工作。我可以看到该插件通过chrome的网络选项卡被拉取,但插件没有初始化。

我不确定是require的问题还是插件的问题,想知道是否有人可以帮忙解决。

这是我的main.js:

require.config({
  // 3rd party script alias names
  paths: {
    // Core Libraries
    modernizr: "libs/modernizr",
    jquery: "libs/jquery",
    underscore: "libs/lodash",
    backbone: "libs/backbone",
    handlebars: "libs/handlebars",

    text: "libs/text",
    prism: "plugins/prism",

    templates: "../templates"
  },
  // Sets the configuration for your third party scripts that are not AMD compatible
  shim: {
    "backbone": {
      "deps": ["underscore", "jquery", "handlebars"],
      "exports": "Backbone"  //attaches "Backbone" to the window object
    }
  }
});

// Include Specific JavaScript
require(['prism', 'modernizr', 'jquery', 'backbone', 'routers/router', 'views/AppVIew' ],
  function(Prism, Modernizr, $, Backbone, Router, App) {
    this.router = new Router();
    this.App = new App();
  }
);
3个回答

11
将 shim 部分更改为包含 Prism,并确保它导出 "Prism":
shim: {
  "backbone": {
      "deps": ["underscore", "jquery", "handlebars"],
      "exports": "Backbone"  //attaches "Backbone" to the window object
  },
  "prism": {
      "exports": "Prism"
  }
}

一旦它被“垫片”了,我该如何使用它? - Tri Nguyen
2
就像任何其他模块一样:require('prism');或在参数中将其包含为依赖项define - Chris Salzberg
我正在使用three.js和OrbitControls.js,其中OrbitControls是非AMD。我尝试按照此处建议的设置进行操作,但无法使其正常工作。OrbitControls中是否有需要不同设置的内容?OrbitControls在内部使用three.js,但这就是我所知道的全部。我收到的错误消息是“Uncaught TypeError:THREE.OrbitControls不是构造函数。”感谢您能提供的任何帮助。 - luenib

3

Handlebars和Prism不兼容AMD(异步模块定义),因此您需要像下面这样自己编写shim

requirejs.config({
    shim: {
        'backbone': {
            "deps": ["underscore", "jquery", "handlebars"],
            "exports": "Backbone"  //attaches "Backbone" to the window object
        },
        'handlebars': {
            "exports": 'Handlebars'
        },
        'prism': {
            "exports": "Prism"
        }
    }
});

您可以查看 require.js 的 shim 文档站点:http://requirejs.org/docs/api.html#config-shim。希望这能有所帮助。

1

Prism也应该添加到shim中。就像backbone一样,它不符合AMD规范,因此必须以相同的方式声明。


即使插件没有依赖关系,也是这样吗? - Lawrence
是的,我的错。我以为你所说的“插件”是指 jquery 插件,并且它依赖于 jquery。 - yakxxx

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接