一、html
script 标签要声明 type = 'module'
1 <script type="module"> 2 import behaviors, { cat, dog } from "./animals"; 3 console.log(behaviors, cat, dog); 4 </script>
二、animals.js
1 export default class behaviors {} 2 3 export function cat() {} 4 5 export { dog }; 6 7 function dog() {}
三、server.js
1 const http = require("http"), 2 fs = require("fs"); 3 4 const server = new http.Server(); 5 6 server.on("request", (req, res) => { 7 const url = req.url; 8 const suffix = url.match(/(?<=\.)\w*$/)?.[0] || "js"; // 匹配文件格式 9 const fileName = url.match(/.*(?=\.\w*$)|\/?\w*/)[0]; // 匹配文件名 10 let mime = ""; 11 switch (suffix) { 12 case "html": 13 mime = "text/html"; 14 break; 15 case "ico": 16 mime = "image/x-icon"; 17 break; 18 default: 19 mime = "text/javascript"; 20 } 21 22 fs.readFile(`.${fileName}.${suffix}`, (err, data) => { 23 res.writeHead(200, { 24 "Content-Type": mime, 25 }); 26 res.write(data); 27 res.end(); 28 }); 29 }); 30 31 server.listen(80);
五、运行
node server.js
浏览器访问:http://localhost/behaviors.html
六、补充 export 与 import
- export default class behaviors {} 对应 import behaviors from "./animals";
- export function cat() {} 和 export { dog }; function dog() {} 对应 import { cat, dog } from "./animals";
- 可以像上面的例子一样,混合使用