daz*_*raf 4 html javascript systemjs es6-modules lit-element
我想静态地为一个项目提供服务,该项目使用 webcomponents(使用 lit-html),没有任何打包工具,如 webpack 等。
示例项目由以下结构组成:
index.html
app.js
package.json
Run Code Online (Sandbox Code Playgroud)
package.json:
{
"name": "lit",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@webcomponents/webcomponentsjs": "^2.2.7",
"lit-element": "^2.0.1"
}
}
Run Code Online (Sandbox Code Playgroud)
app.js:
import { LitElement, html } from 'lit-element';
class FooElement extends LitElement {
render() {
return html`<div>hello world!</div>`;
}
}
window.customElements.define('x-foo', FooElement);
Run Code Online (Sandbox Code Playgroud)
最后,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></title>
<script src="app.js" type="module"></script>
</head>
<body>
<x-foo></x-foo>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
我使用静态 http 服务器提供此服务,当然,这不起作用。浏览器引发错误:Error resolving module specifier: lit-element。
因此,我们尝试将import指令更改为:
import { LitElement, html } from './node_modules/lit-element/lit-element.js';
然后浏览器失败:Error resolving module specifier: lit-html在lit-element.ts:14:29
我试过使用以下修改的systemjs版本3.0.1index.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></title>
</head>
<body>
<script type="systemjs-importmap" src="systemjs.map.json"></script>
<script src="./node_modules/systemjs/dist/system.min.js"></script>
<script>
System.import('app');
</script>
<x-foo></x-foo>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
和一个systemjs.map.json文件:
{
"imports": {
"app": "./app.js",
"lit-element": "./node_modules/lit-element/lit-element.js",
"lit-html": "./node_modules/lit-html/lit-html.js"
}
}
Run Code Online (Sandbox Code Playgroud)
当加载它时(再次通过静态网络服务器),我们进入 Firefox:
import declarations may only appear at top level of a module在app.js:1。
在 Chrome 中:
Uncaught SyntaxError: Unexpected token {在app.js:1
在 Safari 中:
Unexpected token '{'. import call expects exactly one argument.在app.js:1
所有这些都表明这systemjs不是app.js一个模块。
无论如何,我们可以实现对具有依赖关系树的模块的静态加载node_modules吗?
我已将代码版本推systemjs送到https://github.com/dazraf/lit-test。
谢谢。
小智 5
你也许可以在你的 app.js 中使用这样的东西
import {LitElement, html} from 'https://unpkg.com/@polymer/lit-element/lit-element.js?module';
Run Code Online (Sandbox Code Playgroud)
这在你的 HTML 代码中
<script type="module" src="./app.js">
Run Code Online (Sandbox Code Playgroud)
它对我有用。如果您不想使用 unpkg,您可以下载它并在本地提供。