JavaScript:我什么也不能导入

时间:2019-10-23 12:07:20

标签: javascript import lit-html

如何在代码中导入lit-html? 我有以下代码:

index.js文件夹中的js文件:

import { html } from "lit-html";
myDiv = html`
    <div>
        <a href="">Hello, Click Me!</a>
    </div>
`;
document.body.innerHTML += myDiv;

index.html文件:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>JS Tests</title>
</head>
<body>
    <script type="module" src="js/index.js"></script>
</body>
</html>

我收到这样的错误:

Uncaught TypeError: Failed to resolve module specifier "lit-html". Relative references must start with either "/", "./", or "../".

1 个答案:

答案 0 :(得分:1)

您可以尝试

import {render, html } from "https://unpkg.com/lit-html@0.7.1/lit-html.js"

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>JS Tests</title>
</head>
<body>
    <script type="module" src="js/index.js"></script>
</body>
</html>

JS

import {render, html } from "https://unpkg.com/lit-html@0.7.1/lit-html.js";
const myDiv = html`
  <div>
    <a href="">Hello, Click Me!</a>
  </div>
`;

render(myDiv,document.body);

请注意,如果您正在浏览器上使用模块(如上述),则每次导入都会进行网络调用。在将代码交付给浏览器之前,您可以使用诸如webpack之类的模块捆绑器来构建单个JS文件(具有所有依赖项)。