如何在requirejs中添加具有子依赖项的AMD /遗留依赖项(传单)

时间:2017-05-13 14:06:35

标签: requirejs leaflet

我安装了名为leaflet的AMD模块并成功使用它作为" L"。 接下来我需要一个名为leaflet.draw的插件,但我对依赖关系感到困惑。请考虑以下代码:

requirejs.config({
    baseUrl: 'bower_components',
    paths: {
        leaflet: 'leaflet/dist/leaflet-src',
        leafletdraw: 'leaflet-draw/dist/leaflet.draw-src'
        ...

requirejs(["leaflet", "leafletdraw"], function(L, leafletdraw) {
    var map = new L.Map('map');
    ...

这给出了一个referenceError:L未在Leaflet.draw.js:4中定义。所以我想它需要传单(L)作为依赖,对吧?然后我尝试在shim配置中添加它:

shim: {
    leafletdraw: {
        deps: 'leaflet'
    }
}

这导致"无效的需求调用"。所以我的问题是:我如何正确地要求一个带有子依赖的插件?

  • 模块安装了" bower install leaflet"和"凉亭 安装传单" respectivily。但我不确定是否传单 已启用AMD。为什么repos docs中没有说明?我可以假设吗? 默认启用?

  • 这是我尝试实现的目标: http://codepen.io/osmbuildings/pen/LVJzWw,但有requirejs。

1 个答案:

答案 0 :(得分:2)

解决方案:填充传单本身,让它导出'L'。然后将deps放在插件中将起作用。我的完整配置:

requirejs.config({
    baseUrl: 'bower_components',
    paths: {
        jquery: 'jquery/dist/jquery.min',
        leaflet: 'http://cdn.leafletjs.com/leaflet-0.7.3/leaflet',
        'leaflet-draw': 'http://cdn.osmbuildings.org/Leaflet.draw/0.2.0/leaflet.draw',        
        OSMBuildings: ['http://cdn.osmbuildings.org/OSMBuildings-Leaflet']    
    },    
    shim: {
        leaflet: {
            exports: 'L'
        },
        'leaflet-draw': {
            deps: ['leaflet']
        },        
        OSMBuildings: {
            deps: ['leaflet'],
            exports: 'OSMBuildings'
        }
    }
});

requirejs(["jquery", "leaflet", "leaflet-draw", "OSMBuildings"], function($, L, dummy, OSMBuildings) {
    var map = new L.Map('map');