Skip to content

Commit

Permalink
get module
Browse files Browse the repository at this point in the history
  • Loading branch information
qinjialei24 committed Jan 4, 2023
0 parents commit 723be53
Show file tree
Hide file tree
Showing 6 changed files with 1,184 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules
settings.json
13 changes: 13 additions & 0 deletions index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
hello22
</body>
<script type="module" src="/src/main.js"></script>
</html>
53 changes: 53 additions & 0 deletions my-vite.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
const koa = require("koa")
const fs = require("fs")
const path = require("path")

const app = new koa()

function getModule(url) {
const moduleName = url.replace('/@modules/', '')
const prefix = path.join(__dirname, './node_modules', moduleName)
console.log("🚀 ~ file: my-vite.js:10 ~ getModule ~ prefix", prefix)
console.log('prefix', prefix);
const module = require(prefix + "/package.json").module
const filePath = path.join(prefix, module)
const ret = fs.readFileSync(filePath, 'utf-8')
return ret
}

app.use(async (ctx) => {
const { url } = ctx
console.log(url, "xxx");
if (url === '/') {``
const html = fs.readFileSync('./index.html', 'utf-8')
ctx.type = 'text/html'
ctx.body = html
}
else if (url.endsWith("js")) {
const p = path.join(__dirname, url)
const jsFile = fs.readFileSync(p, 'utf-8')
ctx.type = 'application/javascript'
ctx.body = rewriteImport(jsFile)
} else if (url.startsWith('/@modules/')) {
const module = getModule(url)
ctx.type = 'application/javascript'
ctx.body = rewriteImport(module)
}

})

function rewriteImport(content) {
return content.replace(/from ['"](.*)['"]/g, function (s1, s2) {
if (s2.startsWith('./') || s2.startsWith('/') || s2.startsWith('../')) {
return s1
} else {
return ` from '/@modules/${s2}'`
}
})

}


app.listen(3000, function () {
console.log("my vite");
})
Loading

0 comments on commit 723be53

Please sign in to comment.