It's tricky to have ts-node scripts alongside client scripts in a vite project
Describe the bug
Launching a node typescript file with ts-node
in a vite project takes a lot of tweaking to make it work with multiple confusing rounds of errors.
Reproduction
I tried to create a node script in my vite folder to generate an asset map. E.g.
import * as fs from 'fs';
function main() {
const files = fs.readdirSync('src');
console.log(files);
}
main();
And in my package.json
I had:
"build-assets": "ts-node src/assets-builder.ts"
I went through a few errors, the last of which told me to add "type": "module",
to my package.json
. Then I got ERR_UNKNOWN_FILE_EXTENSION
. The solution that eventually worked thanks to this stackoverflow answer was:
"build-assets": "node --loader ts-node/esm src/assets-builder.ts"
System Info
System:
OS: Windows 10 10.0.19043
CPU: (8) x64 Intel(R) Core(TM) i7-4770K CPU @ 3.50GHz
Memory: 15.75 GB / 31.94 GB
Binaries:
Node: 15.4.0 - C:\Program Files\nodejs\node.EXE
npm: 7.0.15 - C:\Program Files\nodejs\npm.CMD
Browsers:
Chrome: 93.0.4577.82
Edge: Spartan (44.19041.1023.0), Chromium (93.0.961.52) Internet Explorer: 11.0.19041.1202
Used Package Manager
npm
Logs
No response
Validations
-
Follow our Code of Conduct -
Read the Contributing Guidelines. -
Read the docs. -
Check that there isn't already an issue that reports the same bug to avoid creating a duplicate. -
Make sure this is a Vite issue and not a framework-specific issue. For example, if it's a Vue SFC related bug, it should likely be reported to https://github.com/vuejs/vue-next instead. -
Check that this is a concrete bug. For Q&A open a GitHub Discussion or join our Discord Chat Server. -
The provided reproduction is a minimal reproducible example of the bug.