-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmyViteApp.js
92 lines (83 loc) · 3.14 KB
/
myViteApp.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
const fs = require('fs')
const path = require('path')
const Koa = require('koa')
const compilerSfc = require('@vue/compiler-sfc');
const compilerDom = require('@vue/compiler-dom');
const myViteApp = new Koa()
myViteApp.use(async ctx => {
const {request: {url, query}} = ctx
// 首页
if (url === '/') {
ctx.type = "text/html"
let content = fs.readFileSync('./index.html', 'utf-8')
content = content.replace('<script ', `
<script>
window.process = {'env':{ NODE_ENV:'dev'}}
</script>
<script
`)
ctx.body = content
} else if (url.endsWith('.js')) {
// js文件
const p = path.resolve(__dirname, url.slice(1))
ctx.type = 'application/javascript'
const content = fs.readFileSync(p, 'utf-8')
ctx.body = rewriteImport(content)
} else if (url.startsWith('/@module/')) {
// 这是一个node_module里的东西
const prefix = path.resolve(__dirname, 'node_modules', url.replace('/@module/', ''))
const module = require(prefix + '/package.json').module
const p = path.resolve(prefix, module)
const ret = fs.readFileSync(p, 'utf-8')
ctx.type = 'application/javascript'
ctx.body = rewriteImport(ret)
} else if (url.indexOf('.vue') > -1) {
// vue单文件组件
const p = path.resolve(__dirname, url.split('?')[0].slice(1))
const {descriptor} = compilerSfc.parse(fs.readFileSync(p, 'utf-8'))
if (!query.type) {
ctx.type = 'application/javascript'
// 借用vue自导的compile框架 解析单文件组件,其实相当于vue-loader做的事情
ctx.body = `
// option组件
${rewriteImport(descriptor.script.content.replace('export default ', 'const __script = '))}
import { render as __render } from "${url}?type=template"
__script.render = __render
export default __script
`
} else if (query.type === 'template') {
// 模板内容
const template = descriptor.template
// 要在server端吧compiler做了
const render = compilerDom.compile(template.content, {mode: 'module'}).code
ctx.type = 'application/javascript'
ctx.body = rewriteImport(render)
}
} else if (url.endsWith('.css')) {
const p = path.resolve(__dirname, url.slice(1))
const file = fs.readFileSync(p, 'utf-8')
const content = `const css = "${file.replace(/\n/g, '')}"
let link = document.createElement('style')
link.setAttribute('type', 'text/css')
document.head.appendChild(link)
link.innerHTML = css
export default css
`
ctx.type = 'application/javascript'
ctx.body = content
}
})
myViteApp.listen(3001, () => {
console.log('听我口令,3001端口,起~~')
})
function rewriteImport(content) {
return content.replace(/from ['"]([^'"]+)['"]/g, (s0, s1) => {
// . ../ /开头的,都是相对路径
if (s1[0] !== '.' && s1[1] !== '/') {
// 绝对路径,统统加前缀
return `from '/@module/${s1}'`
} else {
return s0
}
})
}