简体   繁体   中英

Syntax error: Unexpected token { on executing a TS app

I have the following code in TypeScript:

import { Document, Schema, Model, model } from "mongoose";
import { IUser } from "../interfaces/IUser";

export interface IUserModel extends IUser, Document {
}

var UserSchema: Schema = new Schema({
    name: String,
    username: String,
    password: String,
    email: String
});

export const User: Model<IUserModel> = model<IUserModel>("User", UserSchema);

Then I use it in a controller. When I compile my TS app (tsc app.ts) it compiles fine. Then when I type "node app.js" in the terminal I get this error:

..\BlocG\models\user.ts:1
(function (exports, require, module, __filename, __dirname) { import { Document, Schema, Model, model } from "mongoose";
                                                                     ^

SyntaxError: Unexpected token {
    at new Script (vm.js:79:7)
    at createScript (vm.js:251:10)
    at Object.runInThisContext (vm.js:303:10)
    at Module._compile (internal/modules/cjs/loader.js:656:28)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:699:10)
    at Module.load (internal/modules/cjs/loader.js:598:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:537:12)
    at Function.Module._load (internal/modules/cjs/loader.js:529:3)
    at Module.require (internal/modules/cjs/loader.js:636:17)
    at require (internal/modules/cjs/helpers.js:20:18)
    at Object.<anonymous> (E:\Business\Cevian\CevianPrep\BlocG\data\db.ts:26:1)
    at Module._compile (internal/modules/cjs/loader.js:688:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:699:10)
    at Module.load (internal/modules/cjs/loader.js:598:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:537:12)
    at Function.Module._load (internal/modules/cjs/loader.js:529:3)

What makes it even stranger is that I have such imports in the controller:

import { Router, Request, Response } from 'express';
import { IUserModel } from '../models';

...and it compiles with no problem. I used to execute the logic without any problems.

Please note that the error is not pointed at the import keyword but rather the curly bracket.

Please help me with this issue! Thanks in advance!

Then when I type "node app.js" in the terminal I get this error:

Change your tsconfig module option to be something that will work both in node (natively) and browser (using eg webpack):

"module": "commonjs"

As it turns out, the basic problem was that I was compiling like this:

tsc app

Instead of just writing

tsc

This caused my compilation types to mix with the js ones in the same folder.

Also, I had imports directly from [name].ts files, where I should've used file names only.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM