I make a simple typescript file src/test.ts:
console.log('hello');
npx ts-node -O '{\"module\":\"commonjs\"}' src/test.ts, it is working.npm run test. I will get error.json
"scripts": {
"test": "ts-node -O '{\"module\":\"commonjs\"}' src/test.ts"
},
hello
Actual Behavior
undefined:1
'{module:commonjs}'
^
SyntaxError: Unexpected token ' in JSON at position 0
at JSON.parse (
at parse (C:Usersasuncode_anan_Projectsdel-ts-nodenode_modulests-nodedistindex.js:100:45)
at arg (C:Usersasuncode_anan_Projectsdel-ts-nodenode_modulesargindex.js:122:24)
at main (C:Usersasuncode_anan_Projectsdel-ts-nodenode_modulests-nodedistbin.js:34:18)
at Object.
at Module._compile (internal/modules/cjs/loader.js:1158:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
at Module.load (internal/modules/cjs/loader.js:1002:32)
at Function.Module._load (internal/modules/cjs/loader.js:901:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
Double-quotes are escaped differently in both situations.
As you can see, ts-node is receiving the following string:
{module:commonjs}
Double-quotes are missing. You'll need to modify your package.json scripts entry so that the correct JSON is passed to ts-node.
Thanks @cspotcode.
but in fact, I try a lot of ways the JSON format. for example:
'{\"module\":\"commonjs\"}'{\"module\":\"commonjs\"}{"module":"commonjs"}, it will throughout another exception.and do you try the script? it is similar to npx command in terminal:
and could you please give me an example?
npx run it working, npm run it failed
In npx, the string is being parsed by your shell. I assume it's cmd? Or PowerShell? Different shells behave differently.
When you put the same text inside your package.json, it's inside a JSON string. the JSON encoding is being parsed, and then the result is being passed to a shell by npm, which will parse it again according to the shell's rules. It is being decoded differently in your npx example compared to your npm run example, so you will need to encode the string differently in those 2 situations. Remember that npm uses a different shell on different platforms, so things may behave differently on Windows than on Mac or Linux.
You may find this test helpful:
npx node -p 'console.log(process.argv[1])' '{\"module\":\"commonjs\"}'
"scripts": {
"shell-escaping-test": "node -p 'console.log(process.argv[1])' '{\"module\":\"commonjs\"}'"
}
This will log the argv value exactly as it's being received by node. You can try that with npx, then with npm run shell-escaping-test.
Thanks a lot, @cspotcode,
According to your suggestion, I got the right format:
I use git-bash:
"test": "ts-node -O {\\\"module\\\":\\\"commonjs\\\"} src/test.ts",
now it is working.
Excellent; I'm glad it's working. I'll close the issue.
Most helpful comment
Thanks a lot, @cspotcode,
According to your suggestion, I got the right format:
I use git-bash:
now it is working.