如何服务静态HTML文件与香草javascript包括子模块?



我想提供一个静态html文件,在javascript文件中使用从子模块导入定义的元素。这怎么可能与香草JS?或者我是否需要一些捆绑工具和/或其他框架?示例代码结构来说明我的意图:

index . html

<html>
<div id="screen">
<div id="grid"></div>
</div>
<h1>Example</h1>
<body>
<script type="module" src="index.js"></script>
</body>
</html>

index.js

import { buildGrid } from "./buildGrid.js"
var http = require("http");
http
.createServer(function (req, res) {
fs.readFile(__dirname + req.url, function (err, data) {
if (err) {
res.writeHead(404);
res.end(JSON.stringify(err));
return;
}
res.writeHead(200);
res.header("Content-Type", "application/javascript");
res.end(data);
});
})
.listen(8080);
buildGrid();

buildGrid.js

export function buildGrid() {
let grid = document.getElementById("grid");
let cell = document.createElement("div");
cell.className = "cell";
cell.textContent = "test;
grid.appendChild(cell);
}

style.css

body,
html {
background: #111;
color: white;
}
#screen {
display: flex;
flex-direction: column;
}
.cell {
width: 30px;
height: 30px;
background: #2d2f34;
}

将代码拆分为服务器部分和客户端部分解决了我的问题,正如在评论中正确指出的那样。

所以所有的服务器处理被放在一个server.js文件中,而客户端特定的内容(将被注入到index.html文件中)被放在index.js文件中。

此外,我还使用子模块来分离index.js文件的不同部分。因此需要在index.html文件的导入中指定<script type="module" src="./index.js"></script>。在server.js文件中,通过根据请求中的文件类型设置头来处理不同的文件类型。希望以下内容能对使用nodejs的JS模块提供HTML服务的其他人有所帮助。

结束文件结构是这样的

  • server.js
  • index.js
  • buildGrid.mjs
  • style.css
  • index.html

server.js

"use strict";
var http = require("http");
var fs = require("fs");
function readFile(req, res) {
var filePath = __dirname + req.url;
fs.readFile(filePath, (error, data) => {
if (error) {
res.setHeader("Content-Type", "text/html");
res.writeHead(404);
res.write("Not found error 404");
res.end();
} else {
const url = req.url === "/" ? "/index.html" : req.url;
if (req.url.includes("js"))
res.setHeader("Content-Type", "application/javascript");
if (req.url.includes("css")) res.setHeader("Content-Type", "text/css");
if (req.url.includes("html")) res.setHeader("Content-Type", "text/html");
res.writeHead(200);
res.write(data);
res.end();
}
});
}
http
.createServer(function (req, res) {
readFile(req, res);
})
.listen(8080);

index . html

<html>
<h1>Example</h1>
<div id="screen">
<div id="grid"></div>
</div>
<head>
<link rel="stylesheet" href="./style.css" />
</head>
<body>
<script type="module" src="./index.js"></script>
</body>
</html>

index.js

import { buildGrid } from "./buildGrid.mjs"
export function main {
buildGrid()
}

buildGrid.mjs

export function buildGrid() {
let grid = document.getElementById("grid");
let cell = document.createElement("div");
cell.className = "cell";
cell.textContent = "test;
grid.appendChild(cell);
}

style.css

body,
html {
background: #111;
color: white;
font-family: sans-serif;
}
#screen {
display: flex;
flex-direction: column;
}
.cell {
width: 30px;
height: 30px;
}

最新更新