Add hook after all files have been processed?
See original GitHub issueFor typecheck.macro, I am trying to support the following feature:
file1.ts
:
import { register } from 'typecheck.macro'
export interface Example {}
register('Example')
file2.ts
:
import createValidator from 'typecheck.macro'
import type { Example } from "./file1.ts"
createValidator<Example>()
What’s going on here is that the register
macro is being called to “register” the Example
type. Then when createValidator
is called inside “file2.ts”, it looks up the registered type and generates the validator.
This utilizes the fact that macros can have global inter-file state, like so:
let numberOfFiles = 0;
function macroHandler({ references, state, babel}) {
numberOfFiles++;
console.log(numberOfFiles)
}
export default createMacro(macroHandler)
Problem description:
The issue is that I need to wait until all files have been macro-ed. Then I can process all register paths at once (to generate a global map of all the types), and then I can process all instances of createValidator
.
This would require a hook that is called once after all files have been processed. The hook wouldn’t have to have any parameters or anything complicated.
Suggested solution:
The api could like this:
let numberOfFiles = 0;
function macroHandler({ references, state, babel}) {
numberOfFiles++;
console.log(numberOfFiles)
}
function afterAllFilesHaveBeenProcessed() {
// do something with numberOfFiles
// because we now know that all macro paths have been processed/encountered
}
export {afterAllFilesHaveBeenProcessed as hook}
export default createMacro(macroHandler)
I would be very willing to make a PR and implement this feature because it’s pretty crucial to typecheck.macro/I’m pretty sure typecheck.macro is only useful if it is a macro.
Issue Analytics
- State:
- Created 3 years ago
- Comments:6 (2 by maintainers)
Top GitHub Comments
Thought I’d mention you can actually get around this by leveraging the
process.on('exit')
hook of Node since everything runs in one process. It might be “dirty” but hey - works.A real example is here in my repo: https://github.com/heyheyhello/stayknit/blob/fbc56a9d1f9ca15e4078af1b320b9d130bcc3190/contrib/babel-style-takeout/style-takeout.macro.ts I pull out CSS-in-JS to its own CSS file and replace the node with a generated CSS classname
Works OK. The only trouble is
babel --watch
doesn’t work because the process never exits 😅 Maybe I’ll think of something… I’m hoping to not just need todebounce()
it…Yeah, this isn’t possible, which is unfortunate but inevitable due to the way Babel works.