回顾vite的使用:
pnpm install vite
pnpm create vite my-vue--app --template vue
//pnpm create 实际上等于在安装create-vite脚手架(pnpm install create-vite),然后使用脚手架指令去构建项目
cd ny-vue-app
pnpm install
pnpm dev
模拟vite开发服务器
- 明确pnpm dev之后干了什么事情
- 对开发服务器的原理层面有一个基础的简单的认识
//index.js
//koa: node端的一个框架
const Koa = require( "koa"); //不能用esmodule必须使用commonjs
const fs = require( "fs" );//node赋予js的能力放在执行环境中,node的原生模块内容不去node_modules下寻找,会把这些模块记录下来,在node中找
// 不写绝对路径,相对路径./ /的情况下会在node_modlues下寻找(npm install ,yarn add)
const path = require( "path" );
//当我们安装了node以后node文件路径(node index执行xxx文件)
// document.getElementById(id名)--→>是浏览器环境注入给JS的特殊能力
//不同的宿主环境会给JS赋予一些不同的能力
const app = new Koa( ); // const vue = new Vue( ) ;
// node最频繁做的事情就是在处理请求和操作文件
//当请求来临以后会直接进入到use注册的回调函数中
app.use(async (ctx) => { // context 上下文request --> 请求信息响应信息get请求 url:'/'
console.log ( "ctx", ctx.request, ctx.response) ;
if ( ctx.request.url === "/") {
//这意味着其他人在找我们要根路径的东西,比如你访问baidu.com
console.logpath.resolve(__dirname,'./index.html'))//生成一个绝对路径
const indexContent = await fs.promises.readFile(path.resolve(__dirname,'./index.html'));//在服务端一般不会这么用
console.log('indexContent',indexContent.toString())
ctx.response.body = indexContent;//作为响应体发给对应的请求的人
//你响应体是填充好了,那你要以什么形式发给他呢﹖你希望对方拿到你的东西的时候以什么方式去解析呢
//json ---> application/json text/ html text/javascript
ctx.response.set ( "Content-Type" , "text/ html" );
}
//比如后台给我们一个获取用户信息的接口api/getUserInfo post
if ( ctx.request.url === " /api/getUserInfo" ) {
//去数据库找到用户信息然后返回给前端
}
if ( ctx.request.url === " /main.js" ) {
const mainJSContent = await fs.promises.readFile(path.resolve(__dirname,'./main.js'));
ctx.response.body = mainJSContent;
ctx.response.set ( "Content-Type" , "text/javascript" );
}
if ( ctx.request.url === " /app.vue" ) {
const appVueContent = await fs.promises.readFile(path.resolve(__dirname,'./app.vue'));
//如果是Vue文件,会做一个字符串替换:mainvueContent.tostring( ) .find ("<temolate>")如果匹配到了就直接全部进行字符串替换
//AST语法分析·==>Vue. createElement( ) -->构建原生的dom
ctx.response.body = appVueContent;
//获取的是.vue文件,以js 文件的形式解析——在浏览器和服务器眼里你的文件都是字符串
ctx.response.set ( "Content-Type" , "text/javascript" );
}
})
})
//main.js
import 'app.vue'
console.log('mainjs 123')
//app.vue
//给到浏览器时app.vue里的东西是已经经过编译了的