Skip to content
This repository was archived by the owner on Jul 6, 2025. It is now read-only.

Commit a2ed082

Browse files
committed
refactor: use env to set dev port
1 parent 2d639e0 commit a2ed082

File tree

5 files changed

+61
-53
lines changed

5 files changed

+61
-53
lines changed

cli.ts

Lines changed: 48 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { listenAndServe, path, walk } from './deps.ts'
22
import { Request } from './server/api.ts'
33
import { getContentType } from './server/mime.ts'
44
import { createHtml } from './server/util.ts'
5-
import { existsDirSync, existsFileSync } from './shared/fs.ts'
5+
import { existsDirSync } from './shared/fs.ts'
66
import type { LevelNames } from './shared/log.ts'
77
import log from './shared/log.ts'
88
import util from './shared/util.ts'
@@ -118,47 +118,57 @@ async function main() {
118118
}
119119
}
120120

121+
// load .env
122+
for await (const { path: p, } of walk(Deno.cwd(), { exts: ['env'], maxDepth: 1 })) {
123+
const text = await Deno.readTextFile(p)
124+
text.split('\n').forEach(line => {
125+
let [key, value] = util.splitBy(line, '=')
126+
key = key.trim()
127+
if (key) {
128+
Deno.env.set(key, value.trim())
129+
}
130+
})
131+
log.debug('load env from', path.basename(p))
132+
}
133+
121134
// proxy https://deno.land/x/aleph for aleph.js dev
122-
if (['dev', 'start', 'build'].includes(command) && existsFileSync('./import_map.json')) {
123-
const { imports } = JSON.parse(Deno.readTextFileSync('./import_map.json'))
124-
if (imports['https://deno.land/x/aleph/']) {
125-
const match = String(imports['https://deno.land/x/aleph/']).match(/^http:\/\/localhost:(\d+)\/$/)
126-
if (match) {
127-
const cwd = Deno.cwd()
128-
const port = parseInt(match[1])
129-
listenAndServe({ port }, async (req: ServerRequest) => {
130-
const url = new URL('http://localhost' + req.url)
131-
const resp = new Request(req, util.cleanPath(url.pathname), {}, url.searchParams)
132-
const filepath = path.join(cwd, url.pathname)
133-
try {
134-
const info = await Deno.lstat(filepath)
135-
if (info.isDirectory) {
136-
const r = Deno.readDir(filepath)
137-
const items: string[] = []
138-
for await (const item of r) {
139-
if (!item.name.startsWith('.')) {
140-
items.push(`<li><a href='${path.join(url.pathname, encodeURI(item.name))}'>${item.name}${item.isDirectory ? '/' : ''}<a></li>`)
141-
}
142-
}
143-
resp.send(createHtml({
144-
head: [`<title>aleph.js/</title>`],
145-
body: `<h1>&nbsp;aleph.js/</h1><ul>${Array.from(items).join('')}</ul>`
146-
}), 'text/html')
147-
return
148-
}
149-
resp.send(await Deno.readFile(filepath), getContentType(filepath))
150-
} catch (err) {
151-
if (err instanceof Deno.errors.NotFound) {
152-
resp.status(404).send('file not found')
153-
return
135+
const p = Deno.env.get('ALEPH_DEV_PORT')
136+
if (p && !/^\d+$/.test(p)) {
137+
log.fatal('invalid ALEPH_DEV_PORT:', p)
138+
}
139+
if (p) {
140+
const cwd = Deno.cwd()
141+
const port = parseInt(p)
142+
listenAndServe({ port }, async (req: ServerRequest) => {
143+
const url = new URL('http://localhost' + req.url)
144+
const resp = new Request(req, util.cleanPath(url.pathname), {}, url.searchParams)
145+
const filepath = path.join(cwd, url.pathname)
146+
try {
147+
const info = await Deno.lstat(filepath)
148+
if (info.isDirectory) {
149+
const r = Deno.readDir(filepath)
150+
const items: string[] = []
151+
for await (const item of r) {
152+
if (!item.name.startsWith('.')) {
153+
items.push(`<li><a href='${path.join(url.pathname, encodeURI(item.name))}'>${item.name}${item.isDirectory ? '/' : ''}<a></li>`)
154154
}
155-
resp.status(500).send(err.message)
156155
}
157-
})
158-
Object.assign(globalThis, { __ALEPH_DEV_PORT: port })
159-
log.info(`Proxy https://deno.land/x/aleph on http://localhost:${port}`)
156+
resp.send(createHtml({
157+
head: [`<title>aleph.js/</title>`],
158+
body: `<h1>&nbsp;aleph.js/</h1><ul>${Array.from(items).join('')}</ul>`
159+
}), 'text/html')
160+
return
161+
}
162+
resp.send(await Deno.readFile(filepath), getContentType(filepath))
163+
} catch (err) {
164+
if (err instanceof Deno.errors.NotFound) {
165+
resp.status(404).send('file not found')
166+
return
167+
}
168+
resp.status(500).send(err.message)
160169
}
161-
}
170+
})
171+
log.info(`Proxy https://deno.land/x/aleph on http://localhost:${port}`)
162172
}
163173

164174
const { default: cmd } = await import(`./cli/${command}.ts`)

import_map.json

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
11
{
22
"imports": {
3-
"https://deno.land/x/aleph/": "http://localhost:9006/",
4-
"aleph": "http://localhost:9006/mod.ts",
5-
"aleph/": "http://localhost:9006/",
3+
"aleph": "https://denopkg.com/alephjs/aleph.js/mod.ts",
4+
"aleph/": "https://denopkg.com/alephjs/aleph.js/",
65
"react": "https://esm.sh/[email protected]",
76
"react-dom": "https://esm.sh/[email protected]"
87
}

server/app.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -280,12 +280,12 @@ export class Application {
280280

281281
/** inject HMR code */
282282
injectHMRCode({ url, loader }: Module, content: string): string {
283-
const { __ALEPH_DEV_PORT: devPort } = globalThis as any
284-
const alephModuleLocalUrlPreifx = devPort ? `http_localhost_${devPort}` : `deno.land/x/aleph@v${VERSION}`
283+
const DEV_PORT = Deno.env.get('ALEPH_DEV_PORT')
284+
const alephModuleLocalUrlPrefix = DEV_PORT ? `http_localhost_${DEV_PORT}` : `deno.land/x/aleph@v${VERSION}`
285285
const localUrl = this.fixImportUrl(url)
286286
const hmrImportPath = getRelativePath(
287287
path.dirname(localUrl),
288-
`/-/${alephModuleLocalUrlPreifx}/framework/core/hmr.js`
288+
`/-/${alephModuleLocalUrlPrefix}/framework/core/hmr.js`
289289
)
290290
const lines = [
291291
`import { createHotContext } from ${JSON.stringify(hmrImportPath)};`,
@@ -295,7 +295,7 @@ export class Application {
295295
if (reactRefresh) {
296296
const refreshImportPath = getRelativePath(
297297
path.dirname(localUrl),
298-
`/-/${alephModuleLocalUrlPreifx}/framework/react/refresh.js`
298+
`/-/${alephModuleLocalUrlPrefix}/framework/react/refresh.js`
299299
)
300300
lines.push(`import { RefreshRuntime, performReactRefresh } from ${JSON.stringify(refreshImportPath)};`)
301301
lines.push('')

server/config.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -157,9 +157,9 @@ export async function loadConfig(workingDir: string): Promise<[Config, ImportMap
157157
}
158158

159159
// update import map for alephjs dev env
160-
const { __ALEPH_DEV_PORT: devPort } = globalThis as any
161-
if (devPort) {
162-
const alias = `http://localhost:${devPort}/`
160+
const DEV_PORT = Deno.env.get('ALEPH_DEV_PORT')
161+
if (DEV_PORT) {
162+
const alias = `http://localhost:${DEV_PORT}/`
163163
const imports = {
164164
'https://deno.land/x/aleph/': alias,
165165
[`https://deno.land/x/aleph@v${VERSION}/`]: alias,

server/util.ts

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -43,12 +43,11 @@ export const AlephRuntimeCode = `
4343

4444
/** get aleph pkg url. */
4545
export function getAlephPkgUrl() {
46-
let url = `https://deno.land/x/aleph@v${VERSION}`
47-
const { __ALEPH_DEV_PORT: devPort } = globalThis as any
48-
if (devPort) {
49-
url = `http://localhost:${devPort}`
46+
const DEV_PORT = Deno.env.get('ALEPH_DEV_PORT')
47+
if (DEV_PORT) {
48+
return `http://localhost:${DEV_PORT}`
5049
}
51-
return url
50+
return `https://deno.land/x/aleph@v${VERSION}`
5251
}
5352

5453
/** get relative the path of `to` to `from`. */

0 commit comments

Comments
 (0)