使用require.js加载非amd模块

时间:2012-10-31 23:18:32

标签: javascript requirejs

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

我不确定这是否是一个需求问题,或者uf插件是问题,并且想知道是否有人可以提供帮助。

以下是我的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 个答案:

答案 0 :(得分:10)

更改垫片部分以包含棱镜,并确保它导出“Prism”:

shim: {
  "backbone": {
      "deps": ["underscore", "jquery", "handlebars"],
      "exports": "Backbone"  //attaches "Backbone" to the window object
  },
  "prism": {
      "exports": "Prism"
  }
}

答案 1 :(得分:3)

Handlebars和Prism与AMD(Asyncronous Module Definition)不兼容,所以你需要自己 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

希望这会有所帮助

答案 2 :(得分:1)

棱镜也应添加到shim。就像骨干一样,它不符合AMD标准,因此必须以相同的方式声明。