es6-module

es6提供了module,以此支持web端app的模块化建设,但是这个module只能在服务器生效,下面是一个完整的测试。

plugin.js

 1 export default function a() {
 2     return "通过default暴露的内容";
 3 }
 4 
 5 export function b() {
 6     return "通过自定义名字单独暴露的内容";
 7 }
 8 
 9 export { c };
10 
11 function c() {
12     return "通过自定义名字集体暴露的内容";
13 }

index.html

 1 <!DOCTYPE html>
 2 <html lang="en">
 3     <head>
 4         <meta charset="UTF-8" />
 5         <meta http-equiv="X-UA-Compatible" content="IE=edge" />
 6         <meta name="viewport" content="width=device-width, initial-scale=1.0" />
 7         <title>es6-module</title>
 8     </head>
 9     <body>
10         <div id="html">html文件已加载</div>
11         <div id="plugin">plugin模块未加载</div>
12         <script type="module">
13             import a, { b, c } from "./plugin";
14             const text = [a(), b(), c()].join("\n");
15             document.getElementById("plugin").innerText = text;
16         </script>
17     </body>
18 </html>

server.js

 1 const http = require("http"), // node内部模块,用来创建http服务器
 2     fs = require("fs"), // node内部模块,用来阅读服务器文件
 3     { exec } = require("child_process"); // node内部模块,用来执行一段node命令
 4 
 5 const server = new http.Server();
 6 
 7 server.on("request", (req, res) => {
 8     const url = req.url.replace(/(?<=\/\w+$)\b/, ".js"); // 补全文件后缀
 9     const suffix = url.match(/(?<=\.)\w+$/)[0]; // 获取文件后缀
10     let mimeType = "";
11     switch (suffix) {
12         case "html":
13             mimeType = "text/html";
14             break;
15         case "ico":
16             mimeType = "image/x-icon";
17             break;
18         default:
19             mimeType = "text/javascript";
20     }
21 
22     fs.readFile(__dirname + url, (err, data) => {
23         res.writeHead(200, {
24             "Content-Type": mimeType,
25         });
26         if (data) {
27             res.write(data);
28         }
29         res.end();
30     });
31 });
32 
33 server.listen(80);
34 
35 exec("start http://localhost/index.html");

用node运行server.js

posted @ 2022-11-17 01:22  万物有序  阅读(7)  评论(0编辑  收藏  举报