Skip to content

Commit

Permalink
feat: module rewrite
Browse files Browse the repository at this point in the history
  • Loading branch information
yyx990803 committed Apr 20, 2020
1 parent 4a04d81 commit 33488fe
Show file tree
Hide file tree
Showing 8 changed files with 7,605 additions and 21 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@
node_modules
TODOs.md
playground
*.log
23 changes: 23 additions & 0 deletions lib/moduleMiddleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
const fs = require('fs')
const path = require('path')
const { sendJS } = require('./utils')

exports.moduleMiddleware = (id, res) => {
let modulePath
// try node resolve first
try {
modulePath = require.resolve(id)
} catch (e) {
res.setStatus(404)
res.end()
}

// TODO resolve snowpack web_modules

if (id === 'vue') {
// modulePath = path.relative(modulePath, 'dist/vue.runtime.esm-browser.js')
modulePath = path.resolve(__dirname, 'vue.js')
}

sendJS(res, fs.readFileSync(modulePath))
}
40 changes: 40 additions & 0 deletions lib/moduleRewriter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
const { parse } = require('@babel/parser')
const ms = require('magic-string')

exports.rewrite = (source, asSFCScript = false) => {
const ast = parse(source, {
sourceType: 'module',
plugins: [
// by default we enable proposals slated for ES2020.
// full list at https://babeljs.io/docs/en/next/babel-parser#plugins
// this will need to be updated as the spec moves forward.
'bigInt',
'optionalChaining',
'nullishCoalescingOperator'
]
}).program.body

let s
ast.forEach((node) => {
if (node.type === 'ImportDeclaration') {
if (/^[^\.\/]/.test(node.source.value)) {
// module import
// import { foo } from 'vue' --> import { foo } from '/__modules/vue'
;(s || (s = new ms(source))).overwrite(
node.source.start,
node.source.end,
`"/__modules/${node.source.value}"`
)
}
} else if (node.type === 'ExportDefaultDeclaration') {
;(s || (s = new ms(source))).overwrite(
node.start,
node.declaration.start,
`let __script; export default (__script = `
)
s.appendRight(node.end, `)`)
}
})

return s ? s.toString() : source
}
27 changes: 18 additions & 9 deletions lib/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,31 +5,39 @@ const url = require('url')
const ws = require('ws')
const serve = require('serve-handler')
const vue = require('./vueMiddleware')
const { moduleMiddleware } = require('./moduleMiddleware')
const { createFileWatcher } = require('./hmrWatcher')
const { sendJS } = require('./utils')
const { rewrite } = require('./moduleRewriter')

const hmrClientCode = fs.readFileSync(path.resolve(__dirname, './hmrClient.js'))

const server = http.createServer((req, res) => {
const pathname = url.parse(req.url).pathname
if (pathname === '/__hmrClient') {
sendJS(res, hmrClientCode)
return sendJS(res, hmrClientCode)
} else if (pathname.startsWith('/__modules/')) {
return moduleMiddleware(pathname.replace('/__modules/', ''), res)
} else if (pathname.endsWith('.vue')) {
vue(req, res)
} else {
serve(req, res, {
rewrites: [
{ source: '**', destination: '/index.html' }
]
})
return vue(req, res)
} else if (pathname.endsWith('.js')) {
const filename = path.join(process.cwd(), pathname.slice(1))
if (fs.existsSync(filename)) {
const content = rewrite(fs.readFileSync(filename, 'utf-8'))
return sendJS(res, content)
}
}

serve(req, res, {
rewrites: [{ source: '**', destination: '/index.html' }]
})
})

const wss = new ws.Server({ server })
const sockets = new Set()
wss.on('connection', (socket) => {
sockets.add(socket)
socket.send(JSON.stringify({ type: 'connected'}))
socket.send(JSON.stringify({ type: 'connected' }))
socket.on('close', () => {
sockets.delete(socket)
})
Expand All @@ -39,6 +47,7 @@ createFileWatcher((payload) =>
sockets.forEach((s) => s.send(JSON.stringify(payload)))
)

// TODO customized port
server.listen(3000, () => {
console.log('Running at http://localhost:3000')
})
Loading

0 comments on commit 33488fe

Please sign in to comment.