【问题标题】:Cannot use import after adding Typescript添加 Typescript 后无法使用 import
【发布时间】:2023-02-17 22:22:39
【问题描述】:

所以我正在尝试对现有项目实施打字稿。

但是,我停下来,收到错误消息:SyntaxError: Cannot use import statement outside a module

这里,是我的辅助类,省略了。但是,您可以看到我使用的是import,而不是require

index.ts

// const axios = require('axios');
// const {includes, findIndex} = require('lodash');
// const fs = require('fs');
import { includes, findIndex } from "lodash";
import fs from 'fs';

type storeType = {
  [key: string]: string | boolean
}

class CMS {
  _store;

  constructor(store: storeType) {
    this._store = store;

<omitted code>


export default CMS;
  }

然后,我将 index.ts 文件导入到 server.js 文件:

const { CMS, getCookie, checkLang, getLangByDomain, handleRoutes } = require('./src/utils/cms/index.ts');

不幸的是,当我启动服务器时,出现错误:SyntaxError: Cannot use import statement outside a module

我使用的是默认的tsconfig.json,它是在创建文件并运行开发环境后生成的。

【问题讨论】:

    标签: node.js reactjs typescript next.js


    【解决方案1】:

    编辑您的tsconfig.json并将"module": "esnext"更改为"module": "commonjs"

    【讨论】:

    • 已经做了。甚至尝试更改"target" 属性。仍然没有成功。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-05
    • 2022-06-11
    • 1970-01-01
    • 2018-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多