简体   繁体   English

意外的令牌导入/导出 - 打字稿

[英]unexpected token import/export - typescript

I'm trying out typescript for the first time and am confused about the import/export procedures that I am used to using with es6.我第一次尝试打字稿,对我习惯于与 es6 一起使用的导入/导出过程感到困惑。

this is an interface I am trying to export in a file called transformedRowInterface.ts :这是一个接口,我试图在一个名为transformedRowInterface.ts的文件中导出:

export interface TransformedRow  {
  id: number;
  title: string;
  summary: string;
  body: string;
  synopsis: string;
  author: object;
  impressions: number;
  created: number;
  updated: number;
}

and this is my attempt to import, in a file called newsArticleModel.ts :这是我尝试在名为newsArticleModel.ts的文件中newsArticleModel.ts

const appRoot = require("app-root-path");

import { TransformedRow } from "./transformedRowInterface";
//throws the error below:
// [Node] /newsArticleModel.ts:2
// [Node] import { TransformedRow } from "./transformedRowInterface";
//SyntaxError: Unexpected token import
// also tried a require below, which also throws an error:
// const transformedRow = require(appRoot + "/src/controllers/transformedRowInterface.ts");
// throws this error: 
// [Node] (function (exports, require, module, __filename, __dirname) { export interface TransformedRow  {
//   [Node]                                                               ^^^^^^
//   [Node]
//   [Node] SyntaxError: Unexpected token export

this is my tsconfig:这是我的 tsconfig:

    {
  "compilerOptions": {
    "module": "commonjs",
    "target": "es2017",
    "noImplicitAny": false,
    "moduleResolution": "node",
    "sourceMap": true,
    "outDir": "dist",
    "baseUrl": ".",
    "paths": {
      // "*": ["node_modules/*", "src/types/*"]
    }
  },
  "include": ["src/**/*"]
}

What am I doing wrong?我做错了什么?

I'm pretty sure this is because you are targeting ES2017, which supports the syntax for imports "out of the box", ie your output would literally contain:我很确定这是因为您的目标是 ES2017,它支持“开箱即用”的导入语法,即您的输出将包含:

import { thing } from './wotsit';

If your runtime doesn't support this kind of import, you will need to use down-level compilation (ie target ES5) so the import gets converted into the commomjs require call.如果您的运行时不支持这种导入,您将需要使用下层编译(即目标 ES5),以便将导入转换为 commomjs require 调用。

You can test my theory by looking at the JavaScript output to see what the import looks like.您可以通过查看 JavaScript 输出来测试我的理论,看看导入是什么样的。

(function (exports, require, module, __filename, __dirname) { export})

SyntaxError: Unexpected token export.

If you are getting same problem.如果你遇到同样的问题。 May be you are doing 'node .ts' , it should be node .js可能是你在做 'node .ts' ,它应该是 node .js

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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