【问题标题】:JavaScript: I Can't import anything [duplicate]JavaScript:我无法导入任何东西[重复]
【发布时间】:2019-10-23 12:07:20
【问题描述】:

如何在我的代码中导入 lit-html? 我有这个代码:

js 文件夹中的index.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 "../".

【问题讨论】:

  • 也许错误信息说的是什么?在 lit-html 前面加上 /./../
  • 为什么需要一个库来创建 HTML?
  • 你可能还没有安装它。
  • @Nicolas 因为我想在 JavaScript 文件中为我的 html 代码着色。

标签: javascript import lit-html


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

【讨论】:

    猜你喜欢
    • 2012-03-21
    • 1970-01-01
    • 2020-12-11
    • 2021-02-07
    • 1970-01-01
    • 1970-01-01
    • 2019-08-07
    • 1970-01-01
    • 2013-06-29
    相关资源
    最近更新 更多