Coder Social home page Coder Social logo

d3-require's Introduction

d3-require

A minimal, promise-based implementation to require asynchronous module definitions (AMD). This implementation is small and supports a strict subset of AMD. It is designed to work with browser-targeting libraries that implement one of the recommended UMD patterns. The constraints of this implementation are:

  • The define method must be called synchronously by the library on load.

  • Only the built-in exports and module dependencies are allowed; no require as in CommonJS. The module entry only contains an exports property.

  • Named module definitions (e.g., jQuery) are treated as anonymous modules.

By default, d3.require loads modules from jsDelivr; the module name can be any package (or scoped package) name optionally followed by the at sign (@) and a semver range. For example, d3.require("d3@5") loads the highest version of D3 5.x. Relative paths and absolute URLs are also supported. You can change this behavior using d3.requireFrom.

Installing

If you use NPM, npm install d3-require. Otherwise, download the latest release. You can also load directly from jsDelivr. AMD, CommonJS, and vanilla environments are supported. In vanilla, d3 and define globals are exported:

<script src="https://cdn.jsdelivr.net/npm/d3-require@1"></script>
<script>

d3.require("d3-array").then(d3 => {
  console.log(d3.range(100));
});

</script>

API Reference

# d3.require(names…) <>

To load a module:

d3.require("d3-array").then(d3 => {
  console.log(d3.range(100));
});

To load a module within a version range:

d3.require("d3-array@1").then(d3 => {
  console.log(d3.range(100));
});

To load two modules and merge them into a single object:

d3.require("d3-array", "d3-color").then(d3 => {
  console.log(d3.range(360).map(h => d3.hsl(h, 1, 0.5)));
});

Note: if more than one name is specified, the promise will yield a new object with each of the loaded module’s own enumerable property values copied into the new object. If multiple modules define the same property name, the value from the latest module that defines the property is used; it is recommended that you only combine modules that avoid naming conflicts.

If a module’s property value is null or undefined on load, such as d3.event, the value will be exposed via getter rather than copied; this is to simulate ES module-style live bindings. However, property values that are neither null nor undefined on load are copied by value assignment, and thus are not live bindings!

# d3.requireFrom(resolver) <>

Returns a new require function which loads modules from the specified resolver, which is a function that takes a module name and returns the corresponding URL. For example:

const myRequire = d3.requireFrom(async name => {
  return `https://unpkg.com/${name}`;
});

myRequire("d3-array").then(d3 => {
  console.log(d3.range(100));
});

The returned require function exposes the passed in resolver as require.resolve. See also resolveFrom.

# require.resolve(name[, base]) <>

Returns a promise to the URL to load the module with the specified name. The name may also be specified as a relative path, in which case it is resolved relative to the specified base URL. If base is not specified, it defaults to the global location.

# require.alias(aliases) <>

Returns a require function with the specified aliases. For each key in the specified aliases object, any require of that key is substituted with the corresponding value. The values can be strings representing the name or URL of the module to load, or a literal non-string value for direct substitution. For example, if React and ReactDOM are already in-scope, you can say:

const myRequire = d3.require.alias({
  "react": React,
  "react-dom": ReactDOM
});

myRequire("semiotic").then(Semiotic => {
  console.log(Semiotic);
});

# d3.resolveFrom(origin, mains) <>

Returns a new resolver function which loads modules from the specified origin and observes the specified mains entry points. The returned function can be passed to requireFrom. For example:

const myResolve = d3.resolveFrom(`https://unpkg.com/${name}`);
const myRequire = d3.requireFrom(myResolve);

# d3.RequireError

The class of error that may be thrown by require.

d3-require's People

Contributors

domoritz avatar jashkenas avatar jsdelivrbot avatar mbostock avatar mootari avatar plmrry avatar tmcw avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

d3-require's Issues

requireFrom + defines

Having declared a "myRequire":

        const myRequire = d3.requireFrom(async name => {
            if (/^[.]{0,2}\//i.test(name)) {
                return d3.require(name + ".js");
            }
            return d3.require(name);
        });

I would expect that when it loads a module:

myRequire("./lib-umd/index").then(function (indexMod) {
});

That the define function call in that module would re-use myRequire.

(In my case I want to auto append ".js" to local files being imported...)

Using d3-require with RequireJS fails to merge d3-selection-multi

I have the following code producing this issue:

requirejs.config({
    paths: {
        "d3-require": "//cdn.jsdelivr.net/npm/d3-require@1?"
    }
});

requirejs(["d3-require"], d3 => {
    d3.require("d3-selection", "d3-selection-multi").then(d3 => {
        console.log(d3);
    });
});

It appears that d3-selection loads, however the content of d3-selection-multi is not properly merged into the d3 object. Notably the selection.attrs() and selection.styles() methods are inaccessible.

self

self is undefined and causes problems when requiring from node.

require('d3-require')
ReferenceError: self is not defined

Any reason it is used in this way?

Convenience require.alias for pinning versions.

Currently to pin versions, you need to do something like this:

require.alias({
  "vega": "vega@5", 
  "vega-lite": "vega-lite@3", 
  "vega-embed": "vega-embed@4",
  "vega-transform-omnisci-core": "[email protected]"
})

It’d be swell if you could use shorthand with a leading at-sign:

require.alias({
  "vega": "@5", 
  "vega-lite": "@3", 
  "vega-embed": "@4",
  "vega-transform-omnisci-core": "@0.0.8"
})

Dependency version resolution?

Per observablehq/stdlib#27, we need require to support version resolution for dependencies rather than always loading the latest version. While this is theoretically possible by passing in a resolver function, there are some issues:

First, the resolver function is currently synchronous; we need it to be asynchronous to allow it to load the package.json and resolve the dependency version. (We’d also want multiple async calls to the resolver to be canonicalized so as to avoid fetching the same package.json more than once, though possibly that could happen inside the resolver.)

Second, we should provide a default resolver that understands the module[@range][/path] supported by unpkg. It would fetch the package.json to resolve the exact version of the requested module, and resolve the entry point if a path was not specified. For example, if you said:

require("d3@5")

This would fetch the package.json here:

https://unpkg.com/d3@5/package.json

The resolver could then identify the exact requested version (such as 5.3.0) and the desired entry point (such as dist/d3.min.js). The resolved URL would then be:

https://unpkg.com/[email protected]/dist/d3.min.js

This would be loaded as a script as normal. This would also ensure that any other equivalent request for d3, such as

would resolve to the same exact module (without loading it again).

Third, we may want this default resolver to support an amd entry point. This would allow the d3 default bundle to provide an AMD-specific entry point that would then load the thirty D3 modules separately rather than loading a monolithic bundle. This would allow you to use the d3 default bundle in conjunction with non-core D3 modules such as d3-geo-projection without duplicate loading.

(As an alternative to the third issue, we could support named module definitions like the RequireJS optimizer, so that the d3 default bundle could define the D3 modules from a single file, but this seems questionable because you don’t want to allow any module to define the contents of any other module! In theory if the thirty modules are cached, it should be fast to load…)

Support live bindings?

When multiple arguments are passed to require, it breaks variables like d3.event from d3-selection. Unsure what heuristic would work for identifying values that should be defined as getters rather than copied though.

No longer resolves against 'browser' field

Noticed that including simple-statistics is broken with d3-require 1.0.1 - this appears to be a result of simple-statistics relying on the browser field. I'll shortly add an unpkg field to simple-statistics to nail this down, but nothing that this is technically a regression from unpkg's (admittedly undocumented) behavior: it redirects

https://unpkg.com/simple-statistics -> https://unpkg.com/[email protected]/dist/simple-statistics.min.js

whereas d3-require currently doesn't use unpkg's auto-resolution of a main file, and instead loads

https://unpkg.com/[email protected]/dist/simple-statistics.js

From the main field in package.json, which is not browser-compatible.

Allow paths (not just names) by default?

The default d3.require only supports loading by name from unpkg.

function resolve(name) {
  if (!name.length || /^[\s._]/.test(name) || /\s$/.test(name)) throw new Error("illegal name");
  return "https://unpkg.com/" + name;
}

It’d be nice to support loading by absolute and relative path as well. For example, require("./foo.js") and require("https://wzrd.in/standalone/delaunator").

requireFrom pollutes the module cache.

Say you have a module foo that depends on bar. If you

require("foo")

And then you

require.alias({bar: 42})("foo")

It won’t give you a new module foo whose value of bar is 42; it’ll return the previously-loaded module foo with its natural dependency on bar because foo is already in the modules cache.

This was broken by a6859e9 to fix #8. But this was misguided—even though foo resolves to the same URL in both cases above, the returned module should be different because its dependencies (bar) are different. Possibly we could be clever and try to include the transitive closure of dependencies in the cache key, but it’s much simpler to just have each requireFrom use separate caches.

Support live bindings?

When multiple arguments are passed to require, it breaks variables like d3.event from d3-selection. Unsure what heuristic would work for identifying values that should be defined as getters rather than copied though.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.