-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Incremental Typescript adoption? #7791
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
3c06b2d
Migrate color.js to Typescript to demonstrate mixed JS/TS build
liamdon 0c64d2a
Try to get mocha working
liamdon 8505c22
Add mocha config
liamdon 41db342
Fix mocha tests
liamdon 34306cf
Fix Mocha tests, and ESLint, and allow importing any .ts source with …
liamdon 9733a17
Merge branch 'main' into typescript
liamdon d505de7
Add custom rollup resolver
liamdon 1793390
Use correct color.js reference in float-packing.js
liamdon 462f025
Clarify that ts-node usage is only for Mocha
liamdon 6687bfd
Dev mode examples load fresh .ts files as .js
liamdon 02023d4
Merge branch 'main' into typescript
liamdon File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| { | ||
| "loader": "ts-node/esm", | ||
| "extensions": ["ts", "tsx"], | ||
| "spec": [ | ||
| "test/**/*.test.mjs" | ||
| ], | ||
| "watch-files": [ | ||
| "src" | ||
| ] | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,206 @@ | ||
| #!/usr/bin/env node | ||
|
|
||
| import { promises as fs } from 'fs'; | ||
| import http from 'http'; | ||
| import path from 'path'; | ||
| import { parse as parseUrl } from 'url'; | ||
|
|
||
| import { transformSync } from '@swc/core'; | ||
| import serveHandler from 'serve-handler'; | ||
|
|
||
| // Cache for transpiled TypeScript files | ||
| const cache = new Map(); | ||
|
|
||
| // SWC configuration matching the project's existing setup | ||
| const swcOptions = { | ||
| jsc: { | ||
| parser: { | ||
| syntax: 'typescript', | ||
| tsx: false, | ||
| decorators: false, | ||
| dynamicImport: true | ||
| }, | ||
| target: 'es2022', | ||
| loose: false, | ||
| externalHelpers: false | ||
| }, | ||
| module: { | ||
| type: 'es6', | ||
| strict: false, | ||
| strictMode: true, | ||
| lazy: false, | ||
| noInterop: false | ||
| }, | ||
| sourceMaps: 'inline', | ||
| inlineSourcesContent: true | ||
| }; | ||
|
|
||
| /** | ||
| * Check if a file exists | ||
| * @param {string} filePath - The path to the file | ||
| * @returns {Promise<boolean>} Whether the file exists | ||
| */ | ||
| async function fileExists(filePath) { | ||
| try { | ||
| await fs.access(filePath); | ||
| return true; | ||
| } catch { | ||
| return false; | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Get file modification time | ||
| * @param {string} filePath - The path to the file | ||
| * @returns {Promise<number | null>} The file modification time | ||
| */ | ||
| async function getMtime(filePath) { | ||
| try { | ||
| const stats = await fs.stat(filePath); | ||
| return stats.mtime.getTime(); | ||
| } catch { | ||
| return null; | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Transpile TypeScript file to JavaScript | ||
| * @param {string} tsPath - The path to the TypeScript file | ||
| * @param {string} jsPath - The path to the JavaScript file | ||
| * @returns {Promise<string>} The transpiled JavaScript code | ||
| */ | ||
| async function transpileTypeScript(tsPath, jsPath) { | ||
| // Check cache | ||
| const cacheKey = tsPath; | ||
| const mtime = await getMtime(tsPath); | ||
|
|
||
| if (cache.has(cacheKey)) { | ||
| const cached = cache.get(cacheKey); | ||
| if (cached.mtime === mtime) { | ||
| console.log(`[Serve] Cache hit: ${path.relative(process.cwd(), tsPath)}`); | ||
| return cached.content; | ||
| } | ||
| } | ||
|
|
||
| console.log(`[Serve] Transpiling: ${path.relative(process.cwd(), tsPath)}`); | ||
|
|
||
| try { | ||
| const tsContent = await fs.readFile(tsPath, 'utf8'); | ||
| // @ts-ignore | ||
| const result = transformSync(tsContent, { | ||
| ...swcOptions, | ||
| filename: tsPath | ||
| }); | ||
|
|
||
| // Cache the result | ||
| cache.set(cacheKey, { | ||
| content: result.code, | ||
| mtime: mtime | ||
| }); | ||
|
|
||
| return result.code; | ||
| } catch (error) { | ||
| console.error(`[Serve] Error transpiling ${tsPath}:`, error.message); | ||
| throw error; | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Custom request handler that intercepts .js requests | ||
| * @param {import('http').IncomingMessage} request - The incoming request | ||
| * @param {import('http').ServerResponse} response - The outgoing response | ||
| * @param {object} serveConfig - The serve configuration | ||
| * @param {string} rootDir - The root directory to serve | ||
| * @returns {Promise<void>} | ||
| */ | ||
| async function handleRequest(request, response, serveConfig, rootDir) { | ||
| const parsedUrl = parseUrl(request.url ?? ''); | ||
| const requestPath = parsedUrl.pathname; | ||
|
|
||
| // Only intercept .js file requests | ||
| if (requestPath?.endsWith('.js')) { | ||
| const absolutePath = path.join(rootDir, requestPath); | ||
| const jsExists = await fileExists(absolutePath); | ||
|
|
||
| // If .js file doesn't exist, check for .ts file | ||
| if (!jsExists) { | ||
| const tsPath = absolutePath.replace(/\.js$/, '.ts'); | ||
| const tsExists = await fileExists(tsPath); | ||
|
|
||
| if (tsExists) { | ||
| try { | ||
| const transpiledCode = await transpileTypeScript(tsPath, absolutePath); | ||
|
|
||
| // Send the transpiled JavaScript | ||
| response.setHeader('Content-Type', 'application/javascript; charset=utf-8'); | ||
| response.setHeader('Cache-Control', 'no-cache'); | ||
| response.statusCode = 200; | ||
| response.end(transpiledCode); | ||
| return; | ||
| } catch (error) { | ||
| // Send error response | ||
| response.setHeader('Content-Type', 'text/plain; charset=utf-8'); | ||
| response.statusCode = 500; | ||
| response.end(`Error transpiling TypeScript file: ${error.message}`); | ||
| return; | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // Pass through to serve-handler for all other requests | ||
| return serveHandler(request, response, { | ||
| ...serveConfig, | ||
| public: rootDir | ||
| }); | ||
| } | ||
|
|
||
| /** | ||
| * Start the server | ||
| */ | ||
| async function startServer() { | ||
| const port = process.env.PORT || 3000; | ||
| // Get directory to serve from command line args or environment variable | ||
| const args = process.argv.slice(2); | ||
| let rootDir = args[0] || process.env.SERVE_DIR || 'dist'; | ||
|
|
||
| // Resolve to absolute path | ||
| rootDir = path.resolve(process.cwd(), rootDir); | ||
|
|
||
| // Check if directory exists | ||
| if (!await fileExists(rootDir)) { | ||
| console.error(`[Serve] Error: Directory '${rootDir}' does not exist`); | ||
| process.exit(1); | ||
| } | ||
|
|
||
| // Load serve configuration | ||
| let serveConfig = {}; | ||
| try { | ||
| const configPath = path.join(process.cwd(), 'serve.json'); | ||
| const configContent = await fs.readFile(configPath, 'utf8'); | ||
| serveConfig = JSON.parse(configContent); | ||
| } catch { | ||
| // No serve.json found, use defaults | ||
| } | ||
|
|
||
| const server = http.createServer((request, response) => { | ||
| handleRequest(request, response, serveConfig, rootDir).catch((error) => { | ||
| console.error('[Serve] Server error:', error); | ||
| response.statusCode = 500; | ||
| response.end('Internal Server Error'); | ||
| }); | ||
| }); | ||
|
|
||
| server.listen(port, () => { | ||
| console.log(`[Serve] TS-enabled server running at http://localhost:${port}`); | ||
| console.log(`[Serve] Serving directory: ${rootDir}`); | ||
| }); | ||
| } | ||
|
|
||
| // Start the server | ||
| startServer().catch((error) => { | ||
| console.error('[Serve] Failed to start server:', error); | ||
| process.exit(1); | ||
| }); | ||
|
|
||
| export { handleRequest, transpileTypeScript }; | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ideally we would not want any custom code to auto-convert the typescript files to JS - The serve NPM script would serve the final built version of the engine which would already be in JS so this conversion would not be needed at this stage
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yeah, I generally agree - but then we have this use-case described in the README where you can use the engine source directly:
I figured this might be a common use-case for engine developers who are working on features and want to preview them live. And this feels like the kind of thing Maksims is concerned about, being able to quickly edit and preview the live engine code.
However, what we should probably do is serve the built version normally with no transformation unless they have specified the raw source ENGINE_PATH, in which case the above could still apply. We could basically check ENGINE_PATH in the handler above and early exit with the
serveunless it's../src/. We are still usingserve, it's just the library version rather than the CLI.This development case is where people often reach for Vite as an extension to Rollup, the dev server will do all the transformation for you. But there is already a heavy investment in Rollup plugins and we don't need most Vite features, so that felt like too large a change.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yea thats the only place thats its used directly - It would be better to use tsc watch to chain from the source directly instead of transformation during serving. It would be just as fast it just needs to be setup correctly.
Yea I want to use vite ngl but its the fact that we have multiple sources and outputs thats makes it difficult to migrate but vite has some nice caching and hot reloading so its something I have considered.