Skip to content

CLI usage

GoogleFeud edited this page Sep 24, 2023 · 2 revisions

The new ts-macros CLI allows you to transform your project by expanding all macros while keeping all other typescript features. It's meant to be used alongside other tools that do not use the tsc transpiler such as esbuild.

The CLI features a more specialized watch mode that should be used over other tools - when a macro in one file is changed, all files that use the macro are also considered to be changed, and get re-transpiled. You can also use the function that powers the watch mode (createMacroTransformerWatcher) alongside other tools (webpack, esbuild, vite, etc.) for complete integration.

CLI help command:

Commands:
* transform [OUT] - Expand all macros and write transformed files to the selected OUT directory.
    Example: ts-macros transform ./transformed --noComptime
    -- noComptime   - Disable usage of $$raw and $$comptime macros.
    -- emitjs       - Emits javascript instead of typescript.
    -- exec=[CMD]   - Execute a command after writing the transformed typescript files to disk.
    -- cleanup      - Delete the OUT directory after executing CMD.
    -- tsconfig     - Point the transformer to a different tsconfig.json file.
    -- watch        - Transform your files on changes. If the exec option is also provided, it will be run only after the first transform.

Example usage with esbuild

If you have the following file structure:

src/
   - index.ts
package.json
tsconfig.json

You can run the following command:

npx ts-macros transform ./transformed --emitjs --cleanup --exec="npx esbuild ./transformed/src/index.js --bundle --outfile=out.js"

The CLI will generate .js files from your project, put them into the temporary ./transformed directory, then esbuild will take those files and create a bundle from them, called out.js. Finally, the CLI will delete the ./transformed directory as it's no longer needed.

Using watch mode is very similar - add the --watch flag to both the ts-macros command and the esbuild command. This way, the ts-macros watcher will be transforming your source files to ./transformed, and then esbuild's watcher is gonna pick up the changes and update the bundle. Essentially we're hotwiring the two watchers together.

The same method can be used for all other tools out there - webpack, vite, rollup, browserify, parcel, etc.