从本地脚本导入ES6模块 [英] Import ES6 Module from local script

查看:133
本文介绍了从本地脚本导入ES6模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我说我用

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

和somefile.html看起来像这样:

and the somefile.html looks like this:

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

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

通常我会像这样导入es6模块

Normally I would import a es6 module like so

import MyVariable from 'somefile.js'

,但是在这种情况下,我无法指向html文件,并且我不知道如何导入通过链接导入的模块.甚至有可能还是我需要用全局变量替换导出默认值?

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?

推荐答案

浏览器中的模块支持非常新,并且只需要一点点即可完成.据我从知道的内容到目前为止,我们已经有了规范,目前唯一支持的模块规范是引用JavaScript资源的URL.您显示的导出当前无法导入.根据该链接的规范:

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:

要解析给定脚本脚本和JavaScript字符串说明符的模块说明符,请执行以下步骤.它将返回URL记录或失败.

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. 将URL解析器应用于说明符.如果结果不是失败,则返回结果.

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

如果说明符不是以字符U + 002F SOLIDUS(/)开头,则两个字符序列U + 002E FULL STOP,U + 002F SOLIDUS(./)或三个字符序列U + 002E FULL STOP,U + 002E FULL STOP,U + 002F SOLIDUS(../),返回失败.

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.

此限制已经到位,以便将来我们可以允许自定义模块加载程序为裸"导入说明符赋予特殊含义,例如,导入"jquery"或导入"web/crypto".目前,任何此类导入都将失败,而不是被视为相对URL.

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.

返回将URL解析器应用于以脚本的基本URL作为基本URL的说明符的结果.

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.

这篇关于从本地脚本导入ES6模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆