Import ES6 Module from local script

2019-08-23 07:17发布

问题:

Lets say I import the following html file with

<link rel="import" href="somefile.html">

and the somefile.html looks like this:

<template>
    <some-tags>...</some-tags>
</template>

<script type="module">
    export default { some object }
</script>

Normally I would import a es6 module like so

import MyVariable from 'somefile.js'

but in this case I cannot point to the html file and I don't know how to import the module I imported through the link. Is that even possible or do I need to replace the export default with a global variable?

回答1:

Module support in browsers is very new and being done in small bites. As far as I can tell from what specification we have for this so far, the only module specifiers currently supported are URLs that refer to a JavaScript resource. The export you've shown can't currently be imported. From that linked spec:

To resolve a module specifier given a script script and a JavaScript string specifier, perform the following steps. It will return either a URL record or failure.

  1. Apply the URL parser to specifier. If the result is not failure, return the result.

  2. If specifier does not start with the character U+002F SOLIDUS (/), the two-character sequence U+002E FULL STOP, U+002F SOLIDUS (./), or the three-character sequence U+002E FULL STOP, U+002E FULL STOP, U+002F SOLIDUS (../), return failure.

    This restriction is in place so that in the future we can allow custom module loaders to give special meaning to "bare" import specifiers, like import "jquery" or import "web/crypto". For now any such imports will fail, instead of being treated as relative URLs.

  3. Return the result of applying the URL parser to specifier with script's base URL as the base URL.

Instead, move that export into its own file and import it with a module specifier referring to the file.



回答2:

You might extract the code into a another file, e.g. somefile.js :

export default {
 //...
};

Then you can import that in your template:

<template>
    <some-tags>...</some-tags>
</template>

<script type="module">
    import somefile from "somefile.js";
    //... Whatever
</script>

And in any other code... Note that you should use webpack or a similar system to convert your code to ES3. Html modules are not well supported yet.