如何使用RequireJS加载依赖于d3的脚本?

hob*_*es3 4 javascript requirejs d3.js

我正在尝试d3-path使用RequireJS 加载.看看缩小的d3-path源代码,看起来它符合AMD标准,因为我在第一行看到了这一点:

!function(t,s){"object"==typeof exports&&"undefined"!=typeof module?s(exports):"function"==typeof define&&define.amd?define(["exports"],s):s(t.d3=t.d3||{})}
Run Code Online (Sandbox Code Playgroud)

我的index.html样子

<script>
    require.config({
        paths: {
            "d3": "https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min",
            "d3-path": "https://d3js.org/d3-path.v1.min",
            "underscore": "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min",
            "jquery": "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"
        }
    });
</script>
Run Code Online (Sandbox Code Playgroud)

而我正在尝试加载的JS文件d3.path()看起来像

require([
    "d3",
    "d3-path",
    "underscore"
],
function(
    d3,
    d3_path,
    _
) {
    // d3, d3_path, and _ are defined
    // but d3.path() isn't defined 
});
Run Code Online (Sandbox Code Playgroud)

我可以d3-path通过这样做来使用,d3_path.path()但理想情况下我喜欢这样做d3.path().但是,如果我同时设置d3d3-pathd3d3-path覆盖d3,我失去了主要d3的功能.

我也对RequireJS最佳实践持开放态度,因为我不确定我是否使用了最好的方法.谢谢!

nik*_*shr 5

初步说明:您正在尝试使用V4模块加载d3 V3,这不会很好地融合.

在您的问题上:这是您使用微模块时的工作方式.您加载孤立的功能并将它们组合在一起.

d3当您使用文档中所述的vanilla环境时,您只能获得全局:尝试

require.config({
    paths: {
        "d3": "https://d3js.org/d3.v4.min"
    }
});

require(['d3'], function(myd3) {
    console.log(window.d3); // undefined
    console.log(myd3); // d3 object
});
Run Code Online (Sandbox Code Playgroud)

请注意,如果您加载整个d3 v4库,您将获得d3.path:

require(['d3'], function(myd3) {
    console.log(myd3.path); // function
});
Run Code Online (Sandbox Code Playgroud)

最后,如果您打算使用多个微模块,则可以使用映射配置:

require.config({
    paths: {
        d3src: 'https://d3js.org'
    },
    map: {
        '*': {
            'd3':  'd3src/d3.v4.min',
            'd3-selection':  'd3src/d3-selection.v1.min',
            'd3-path': 'd3src/d3-path.v1.min',
        }
    }
});


// if you want to load the selection and the path modules
require(['d3-selection', 'd3-path'], function(selection, path) {
    // ...
});

// if you want to load d3
require(['d3'], function(d3) {
    // ...
});
Run Code Online (Sandbox Code Playgroud)