pull/1/head
yutent 2022-09-28 18:56:47 +08:00
parent cd9f780212
commit c2f7afedcb
2 changed files with 178 additions and 147 deletions

30
index.js Executable file
View File

@ -0,0 +1,30 @@
#!/bin/env node
/**
* {}
* @author yutent<yutent.io@gmail.com>
* @date 2022/09/28 15:12:45
*/
import { join } from 'path'
import { createServer } from './lib/index.js'
const WORK_SPACE = process.env.INIT_CWD
let args = process.argv.slice(2)
switch (args[0]) {
case 'dev':
import(join(WORK_SPACE, 'vue.live.js'))
.then(function (conf) {
// console.log(conf)
createServer(WORK_SPACE, conf.default)
})
.catch(err => {
console.log('Import Error:', err)
})
break
case 'build':
break
}

View File

@ -8,7 +8,7 @@ import http from 'http'
import fs from 'iofs' import fs from 'iofs'
import { join, resolve } from 'path' import { join, resolve } from 'path'
import { parse } from 'url' import { parse } from 'url'
import conf from './live.config.js.js' // import conf from './live.config.js'
import { compileScss, parseJs, compileVue } from './compile-vue.js' import { compileScss, parseJs, compileVue } from './compile-vue.js'
@ -16,184 +16,185 @@ import MIME_TYPES from './mime-tpyes.js'
import { COMMON_HEADERS } from './constants.js' import { COMMON_HEADERS } from './constants.js'
const decode = decodeURIComponent const decode = decodeURIComponent
const root = resolve('./src/')
/* ------------------------------- */ /* ------------------------------- */
let pagesDir = resolve(conf.pages) export function createServer(root = '', conf = {}) {
let pages = fs.ls(pagesDir).map(it => { let pagesDir = resolve(conf.pages)
let tmp = it.slice(pagesDir.length + 1) + '.html' let pages = fs.ls(pagesDir).map(it => {
return `<li><a href="/${tmp}">${tmp}</a></li>` let tmp = it.slice(pagesDir.length + 1) + '.html'
}) return `<li><a href="/${tmp}">${tmp}</a></li>`
})
let currentPage = '' let currentPage = ''
http http
.createServer(function (req, res) { .createServer(function (req, res) {
let pathname = parse(req.url.slice(1)).pathname || 'index.html' let pathname = parse(req.url.slice(1)).pathname || 'index.html'
// console.log(req.url, pathname, parse(req.url.slice(1))) // console.log(req.url, pathname, parse(req.url.slice(1)))
let isIndex = pathname === 'index.html' let isIndex = pathname === 'index.html'
for (let k in COMMON_HEADERS) { for (let k in COMMON_HEADERS) {
res.setHeader(k, COMMON_HEADERS[k]) res.setHeader(k, COMMON_HEADERS[k])
} }
let tmp = pathname.split('.') let tmp = pathname.split('.')
let ext = tmp.pop() let ext = tmp.pop()
let page = tmp.join('.') let page = tmp.join('.')
if (isIndex) { if (isIndex) {
res.setHeader('content-type', MIME_TYPES.html) res.setHeader('content-type', MIME_TYPES.html)
res.writeHead(200, 'OK') res.writeHead(200, 'OK')
res.end('<ul>' + pages.join('') + '</ul>') res.end('<ul>' + pages.join('') + '</ul>')
} else { } else {
res.setHeader('accept-ranges', 'bytes') res.setHeader('accept-ranges', 'bytes')
let code = '' let code = ''
switch (ext) { switch (ext) {
case 'html': case 'html':
{ {
let entry = fs.cat(join(pagesDir, page, 'main.js')).toString() let entry = fs.cat(join(pagesDir, page, 'main.js')).toString()
let fixedStyle = '\n\n' let fixedStyle = '\n\n'
currentPage = page currentPage = page
res.setHeader('content-type', MIME_TYPES.html) res.setHeader('content-type', MIME_TYPES.html)
entry = entry entry = entry
.replace(/import (.*?) from (["'])(.*?)\2/g, function (m, alias, q, name) { .replace(/import (.*?) from (["'])(.*?)\2/g, function (m, alias, q, name) {
if (name.startsWith('@/')) {
name = name.replace('@/', '/aseets/js/')
}
if (!conf.imports[name]) {
if (name.startsWith('./')) {
name = name.replace('./', `/aseets/js/${currentPage}/`)
} else if (name.startsWith('/') && !name.startsWith('/aseets/js/')) {
name = name.replace(/^\//, '/aseets/js/')
}
if (!name.endsWith('.js') && !name.endsWith('.vue')) {
name += '.js'
}
}
return `import ${alias} from '${name}'`
})
.replace(/import (["'])(.*?)\1/g, function (m, q, name) {
if (name.endsWith('.css') || name.endsWith('.scss')) {
if (name.startsWith('@/')) {
name = name.replace('@/', '/aseets/css/')
}
let tmp = `style${Date.now()}`
fixedStyle += `document.adoptedStyleSheets.push(${tmp})\n`
return `import ${tmp} from '${name}' assert { type: 'css' }`
} else {
if (name.startsWith('@/')) { if (name.startsWith('@/')) {
name = name.replace('@/', '/aseets/js/') name = name.replace('@/', '/aseets/js/')
} }
// console.log(name, conf.imports[name])
if (!conf.imports[name]) { if (!conf.imports[name]) {
if (!name.startsWith('/') && !name.startsWith('./')) { if (name.startsWith('./')) {
name = '/' + name name = name.replace('./', `/aseets/js/${currentPage}/`)
} else if (name.startsWith('/') && !name.startsWith('/aseets/js/')) {
name = name.replace(/^\//, '/aseets/js/')
} }
if (!name.endsWith('.js') && !name.endsWith('.vue')) { if (!name.endsWith('.js') && !name.endsWith('.vue')) {
name += '.js' name += '.js'
} }
} }
return `import '${name}'` return `import ${alias} from '${name}'`
} })
}) .replace(/import (["'])(.*?)\1/g, function (m, q, name) {
if (name.endsWith('.css') || name.endsWith('.scss')) {
if (name.startsWith('@/')) {
name = name.replace('@/', '/aseets/css/')
}
let tmp = `style${Date.now()}`
fixedStyle += `document.adoptedStyleSheets.push(${tmp})\n`
entry += fixedStyle return `import ${tmp} from '${name}' assert { type: 'css' }`
} else {
if (name.startsWith('@/')) {
name = name.replace('@/', '/aseets/js/')
}
// console.log(name, conf.imports[name])
if (!conf.imports[name]) {
if (!name.startsWith('/') && !name.startsWith('./')) {
name = '/' + name
}
code = fs.cat('./index.html').toString() if (!name.endsWith('.js') && !name.endsWith('.vue')) {
code = code name += '.js'
.replace( }
'</head>', }
"<script>window.process = {env: {NODE_ENV: 'development'}}</script></head>" return `import '${name}'`
) }
.replace('{{importmap}}', JSON.stringify({ imports: conf.imports })) })
.replace(
'<script src="main.js"></script>',
`<script type="module">\n${entry}\n</script>`
)
}
break entry += fixedStyle
case 'vue': code = fs.cat('./index.html').toString()
{ code = code
pathname = pathname.replace(/^aseets\/js\//, '') .replace(
let file '</head>',
"<script>window.process = {env: {NODE_ENV: 'development'}}</script></head>"
if (pathname.startsWith(currentPage)) { )
file = join(conf.pages, pathname) .replace('{{importmap}}', JSON.stringify({ imports: conf.imports }))
} else { .replace(
file = join(root, pathname) '<script src="main.js"></script>',
`<script type="module">\n${entry}\n</script>`
)
} }
if (!fs.isfile(file)) { break
file = file.replace(/\.vue$/, '/index.vue')
case 'vue':
{
pathname = pathname.replace(/^aseets\/js\//, '')
let file
if (pathname.startsWith(currentPage)) {
file = join(conf.pages, pathname)
} else {
file = join(root, pathname)
}
if (!fs.isfile(file)) {
file = file.replace(/\.vue$/, '/index.vue')
}
// console.log('>>>>', file)
code = compileVue(file)
res.setHeader('content-type', MIME_TYPES.js)
}
break
case 'scss':
case 'css':
{
let file = join(root, pathname.replace(/^aseets\/css\//, ''))
code = compileScss(file)
res.setHeader('content-type', MIME_TYPES.css)
}
break
case 'js':
{
pathname = pathname.replace(/^aseets\/js\//, '')
let file
if (pathname.startsWith(currentPage)) {
file = join(conf.pages, pathname)
} else {
file = join(root, pathname)
}
if (fs.isfile(file)) {
code = fs.cat(file)
} else {
file = file.replace(/\.js$/, '/index.js')
code = fs.cat(file)
}
console.log(req.url, '>>>>', file)
code = parseJs(code + '')
res.setHeader('content-type', MIME_TYPES.js)
} }
// console.log('>>>>', file) break
code = compileVue(file)
res.setHeader('content-type', MIME_TYPES.js) default:
} res.setHeader('content-type', MIME_TYPES[ext] || MIME_TYPES.other)
break break
}
case 'scss': res.setHeader('content-length', Buffer.byteLength(code))
case 'css': res.writeHead(200, 'OK')
{ res.end(code + '')
let file = join(root, pathname.replace(/^aseets\/css\//, ''))
code = compileScss(file)
res.setHeader('content-type', MIME_TYPES.css)
}
break
case 'js':
{
pathname = pathname.replace(/^aseets\/js\//, '')
let file
if (pathname.startsWith(currentPage)) {
file = join(conf.pages, pathname)
} else {
file = join(root, pathname)
}
if (fs.isfile(file)) {
code = fs.cat(file)
} else {
file = file.replace(/\.js$/, '/index.js')
code = fs.cat(file)
}
console.log(req.url, '>>>>', file)
code = parseJs(code + '')
res.setHeader('content-type', MIME_TYPES.js)
}
break
default:
res.setHeader('content-type', MIME_TYPES[ext] || MIME_TYPES.other)
break
} }
})
res.setHeader('content-length', Buffer.byteLength(code)) .listen(conf.port)
res.writeHead(200, 'OK') .on('error', err => {
res.end(code + '') console.log(`${conf.port}端口被占用~~~`)
} conf.port++
}) createServer()
.listen(conf.port) })
.on('error', err => { .on('listening', _ => {
console.log(`${conf.port}端口被占用~~~`) console.log('启动成功, 请访问', 'http://127.0.0.1:' + conf.port)
conf.port++ })
createServer() }
})
.on('listening', _ => {
// console.log('启动成功, 请访问', 'http://127.0.0.1:' + conf.port)
})