4

如何在我的代码中导入 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 "../".
4

1 回答 1

2

你可以试试

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 文件(包含所有依赖项)。

于 2019-10-23T13:21:52.550 回答