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

dev*_*r87 6 javascript typescript

我是第一次尝试打字稿,对使用es6的导入/导出过程感到困惑。

这是我尝试在名为的文件中导出的接口transformedRowInterface.ts

export interface TransformedRow  {
  id: number;
  title: string;
  summary: string;
  body: string;
  synopsis: string;
  author: object;
  impressions: number;
  created: number;
  updated: number;
}
Run Code Online (Sandbox Code Playgroud)

这是我尝试导入的文件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
Run Code Online (Sandbox Code Playgroud)

这是我的tsconfig:

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

我究竟做错了什么?

Fen*_*ton 5

我非常确定这是因为您的目标是ES2017,它支持“开箱即用”的导入语法,即您的输出实际上包含:

import { thing } from './wotsit';
Run Code Online (Sandbox Code Playgroud)

如果运行时不支持这种导入,则需要使用下层编译(即目标ES5),以便将导入转换为commomjs require调用。

您可以通过查看JavaScript输出来查看导入,以检验我的理论。