NodeJS 添加Typescript后无法使用导入

u5rb5r59  于 2023-02-18  发布在  Node.js
关注(0)|答案(3)|浏览(130)

所以我试着在一个现有的项目中实现 typescript 。
然而,我停了下来,在那里我得到一个错误:SyntaxError: Cannot use import statement outside a module
这里是我的helper类,它被省略了。但是,您可以看到我使用的是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,它是在创建文件和运行开发环境后生成的。

k0pti3hp

k0pti3hp1#

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

anauzrmj

anauzrmj2#

这是ES型模块:

import { includes, findIndex } from "lodash";
import fs from 'fs';

但这是常见的Js类型:

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

我认为这就是问题所在。您应该使用一种类型的模块。尝试将const { CMS, getCookie, checkLang, getLangByDomain, handleRoutes } = require('./src/utils/cms/index.ts');重写为import { CMS, getCookie, checkLang, getLangByDomain, handleRoutes } from './src/utils/cms/index.ts'
或者相反,将ES重写为commonJs,但不要忘记在tsconfig中更改类型

1l5u6lss

1l5u6lss3#

您不能显式地将 typescript 文件导入到Javascript文件中,而需要使用编译后的 typescript 文件(即outDir文件夹中的Javascript文件)。
所以假设你把你的 typescript 文件编译成Javascript,那么它就会被转换成outDir/index.js,然后你就可以直接把它导入到server.js

const { CMS, getCookie, checkLang, getLangByDomain, handleRoutes } = 
  require('./path/to/index.js'); // You cannot require a ts file.

如果typescript文件和Javascript文件是同一个项目的一部分,那么你需要把js文件和ts文件一起传输,为了实现这一点,你需要在 tsconfig 中将allowJs设置为true。

{ 
  "compilerOptions": {
   ...
   "allowJs": true,
  }
}

允许JavaScript文件成为程序的一部分。使用“checkJS”选项可从这些文件获取错误。

相关问题