ES6: import module from URL

前端 未结 3 1308
[愿得一人]
[愿得一人] 2020-11-29 23:43

Is it possible to import javascript module from external url in ES6?

I tried (using babel-node):

import mymodule from \'http://...mysite.../myscript.         


        
相关标签:
3条回答
  • 2020-11-30 00:07

    TL;DR:

    For now, no.

    Long answer:

    There are two different specs: the ES6 defines the syntax to exporting/importing. And there is the Loader Spec that actually defines how this modules will load.

    Spec-speak aside, the important part for us developers is:

    The JavaScript Loader allows host environments, like Node.js and browsers, to fetch and load modules on demand. It provides a hookable pipeline, to allow front-end packaging solutions like Browserify, WebPack and jspm to hook into the loading process.

    This division provides a single format that developers can use in all JavaScript environments, and a separate loading mechanism for each environment. For example, a Node Loader would load its modules from the file system, using its own module lookup algorithm, while a Browser Loader would fetch modules and use browser-supplied packaging formats.

    (...)

    The primary goal is to make as much of this process as possible consistent between Node and Browser environments. For example, if a JavaScript program wants to translate .coffee files to JavaScript on the fly, the Loader defines a "translate" hook that can be used. This allows programs to participate in the loading process, even though some details (specifically, the process of getting a particular module from its host-defined storage) will be different between environments.

    So we depend on the host environment (node, browser, babel, etc) to resolve/load the modules for us and provide hooks to the process.

    0 讨论(0)
  • 2020-11-30 00:13

    2018 Update: The module loader spec is now a part of the ES Spec - what you are describing is allowed and possible with <script type="module"> in browsers and with a custom --loader with Node.js as well as with Deno if you're into that.


    The module loader spec and the import/export syntax are separate. So this is a property of the module loader (not a part of the ES spec). If you use a module loader that supports plugins like SystemJS.

    0 讨论(0)
  • 2020-11-30 00:18

    You could also use scriptjs which in my case requires less configs.

    var scriptjs = require('scriptjs');
    
    scriptjs('https://api.mapbox.com/mapbox.js/v3.0.1/mapbox.standalone.js', function() {
        L.mapbox.accessToken = 'MyToken';
    });
    
    0 讨论(0)
提交回复
热议问题