Skip to content
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

Can't get simple script to run due to SyntaxError: Unexpected token import #313

Closed
lucastheisen opened this issue Apr 22, 2017 · 11 comments
Closed

Comments

@lucastheisen
Copy link

I hope i'm not just doing something stupid but i have created an extremely simple project just to figure out how to use ts-node properly. This is my setup:

package.json

{
  "dependencies": {},
  "devDependencies": {
    "@types/node": "^7.0.13",
    "ts-node": "^3.0.2",
    "typescript": "^2.2.2"
  },
  "name": "learn-tsnode",
  "scripts": {
    "script": "ts-node bin/script.ts"
  },
  "version": "0.0.1"
}

tsconfig.json

{
    "compilerOptions": {
        "lib": [
            "es5",
            "es2015"
        ],
        "module": "es2015",
        "moduleResolution": "node",
        "noImplicitAny": true,
        "outDir": "./dist/",
        "preserveConstEnums": true,
        "removeComments": true,
        "sourceMap": true,
        "target": "es5"
    },
    "include": [
        "./bin/**/*"
    ],
    "exclude": [
        "./node_modules"
    ]
}

bin/script.ts

import * as path from "path";
console.log(path.resolve(__dirname, ".."));

However, when I run npm run script, i get this:

PS C:\Users\ltheisen\git\learn-tsnode> npm run script

> [email protected] script C:\Users\ltheisen\git\learn-tsnode
> ts-node bin/script.ts

C:\Users\ltheisen\git\learn-tsnode\bin\script.ts:1
(function (exports, require, module, __filename, __dirname) { import * as path from "path";
                                                              ^^^^^^
SyntaxError: Unexpected token import
    at Object.exports.runInThisContext (vm.js:76:16)
    at Module._compile (module.js:542:28)
    at Module.m._compile (C:\Users\ltheisen\git\learn-tsnode\node_modules\ts-node\src\index.ts:395:23)
    at Module._extensions..js (module.js:579:10)
    at Object.require.extensions.(anonymous function) [as .ts] (C:\Users\ltheisen\git\learn-tsnode\node_modules\ts-node\src\index.ts:398:12)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Function.Module.runMain (module.js:604:10)
    at Object.<anonymous> (C:\Users\ltheisen\git\learn-tsnode\node_modules\ts-node\src\_bin.ts:177:12)

npm ERR! Windows_NT 10.0.15063
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "run" "script"
npm ERR! node v6.9.4
npm ERR! npm  v3.10.10
npm ERR! code ELIFECYCLE
npm ERR! [email protected] script: `ts-node bin/script.ts`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] script script 'ts-node bin/script.ts'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the learn-tsnode package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     ts-node bin/script.ts
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs learn-tsnode
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls learn-tsnode
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     C:\Users\ltheisen\git\learn-tsnode\npm-debug.log
@lucastheisen
Copy link
Author

Nevermind, it appears es2015 is not yet supported.

@brunolemos
Copy link

In case anyone else arrive here, this works: ts-node -O '{"module": "commonjs"}'

@RehanSaeed
Copy link

Did you manage to get webpack config written in TypeScript to work? Following the webpack documentation on the subject seems to give a Unexpected token import error. See webpack/webpack#5053 for more info.

@IS-Kuan
Copy link

IS-Kuan commented Apr 9, 2019

In case anyone else arrive here, this works: ts-node -O '{"module": "commonjs"}'

I think this should be added to README.

Did you manage to get webpack config written in TypeScript to work? Following the webpack documentation on the subject seems to give a Unexpected token import error. See webpack/webpack#5053 for more info.

Don't want to write stupidly annoying Webpack config at all for just a small script. Otherwise, why use ts-node?

@IAMtheIAM
Copy link

IAMtheIAM commented Dec 8, 2020

Prior to TypeScript v4.0.5, I didn't need any special flags to run ts-node. However, after updating today, I started , receiving "Unexpected token 'Export'".

In order to run the script successfully from within package.json as an npm script I had to escape the quotes, or the program complained about SyntaxError: Unexpected token m in JSON at position 1, using this format:

"extract-config": "ts-node -O \"{\\\"module\\\":\\\"commonjs\\\"}\" myscript.ts"

So you have to escape the escape. The first \ makes it so the next \ gets rendered out, and that makes it so the " gets rendered out. So \\\" === \". The quote is necessary for it to be considered valid JSON. It renders out to this to be evaluated at runtime:

> ts-node -O "{\"module\":\"commonjs\"}" myscript.ts

To run it from the CLI directly rather than as an npm script, use the format above

It took me about an 2 hours messing around to figure this out. Works cross platform on Windows and Linux build agents

I hope this note can help someone else.

@cspotcode
Copy link
Collaborator

cspotcode commented Dec 17, 2020

In these situations, I recommend using ts-node-script and putting all the necessary options in a tsconfig.json. ts-node-script will search for the nearest tsconfig.json by ascending one directory at a time, starting in the directory of myscript.ts

tsconfig.json can be given special, ts-node-only options.

// tsconfig.json
{
  "ts-node": {
    "transpileOnly": true, // you can specify ts-node options here
    "compilerOptions": {
      "module": "commonjs" // you can also override compilerOptions.  Only ts-node will use these overrides
    }
  },
  "compilerOptions": {
    "module": "esnext" // tsc will continue to use these options
  }
}

@forresthopkinsa
Copy link

There's experimental ES Module support now, see here

@cspotcode
Copy link
Collaborator

cspotcode commented Jul 23, 2021

Yes, native ES module support will work. Thanks for linking to the docs. However, often people actually want to enable module: commonjs, because that is more likely to work with less hassle in the majority of situations. They will still write import syntax in their TS files, but it will be transformed into CommonJS syntax before being executed by node. Not to disagree with you, but to make sure everyone has the necessary information to choose, I'll link to the relevant docs.

The docs have a breakdown of the differences and configuration examples:
https://typestrong.org/ts-node/docs/imports

Other useful tidbits:

Use ts-node --showConfig to help debug configuration issues:
https://typestrong.org/ts-node/docs/troubleshooting

The latest ts-node does not require ts-node-script; that is the default behavior.

In rare cases, moduleTypes can override module handling on a per-file basis.
https://typestrong.org/ts-node/docs/module-type-overrides

@Senseye
Copy link

Senseye commented Aug 4, 2021

ESM Support: ts-node -r esm awesomescript.ts

@cspotcode
Copy link
Collaborator

Note that the esm module used in ts-node -r esm does not fully support ESM; it lies to node and allows ESM modules to load synchronously even when they use top-level await. This will fail in certain situations. As long as you understand what those situations are, and understand how to avoid them, you should be fine.

alexrafael10 added a commit to alexrafael10/algo-journal that referenced this issue May 1, 2022
alexrafael10 added a commit to alexrafael10/algo-journal that referenced this issue May 1, 2022
commit c0b39da
Author: alex <[email protected]>
Date:   Sun May 1 12:59:12 2022 -0300

    added watch mode

commit a4b4243
Author: alex <[email protected]>
Date:   Sun May 1 12:58:54 2022 -0300

    valid number solution

commit aeac477
Author: alex <[email protected]>
Date:   Sun May 1 12:58:38 2022 -0300

    added logger

commit 760dc85
Author: alex <[email protected]>
Date:   Sun May 1 10:11:47 2022 -0300

    Fix from TypeStrong/ts-node#313
@eplarson
Copy link

eplarson commented Feb 9, 2024

For anyone finding this, I ran into the same issue and was able to fix it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

9 participants