Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 如何修复SyntaxError:无法在模块外部使用导入语句?_Typescript_Express_Ts Node - Fatal编程技术网

Typescript 如何修复SyntaxError:无法在模块外部使用导入语句?

Typescript 如何修复SyntaxError:无法在模块外部使用导入语句?,typescript,express,ts-node,Typescript,Express,Ts Node,我对所有这些都是新手,我正在尝试将Node+Typescript后端添加到我的Angular项目中。但是在导入express之后,我总是会出错 [ERROR] SyntaxError: Cannot use import statement outside a module. package.json tsconfig.json server.ts 我查过了,最常见的解决方案是在package.json中添加“type”:“module”,我就是这么做的。我还知道,这只适用于节点13和更高版本

我对所有这些都是新手,我正在尝试将Node+Typescript后端添加到我的Angular项目中。但是在导入express之后,我总是会出错

[ERROR] SyntaxError: Cannot use import statement outside a module.
package.json tsconfig.json server.ts
我查过了,最常见的解决方案是在package.json中添加“type”:“module”,我就是这么做的。我还知道,这只适用于节点13和更高版本,我有节点14.15.5。

导入节点模块的最佳实践是使用require()。您可以使用require()函数导入内置的核心节点模块、npm模块以及本地模块。在您的情况下,使用
const express=require(“express”)
而不是从“express”中使用
import*as express,并从package.json中删除“type”:“module”。让我知道这是否对您有效。

谢谢,它有效。虽然我以前也试过类似的方法,但我以前一定犯过错误。不客气。请确保下次使用require导入模块。您好,很抱歉再次打扰您,但如何正确导出<代码>导出{app as routes}这可能是错误的,就像我的导入一样。您好,没问题,随时欢迎帮助。要导出,必须使用
模块.exports
。例如,假设您在file.js中有这样一个函数
const func=()=>console.log('hello world')
。因此,您所要做的就是
module.exports=func
,然后再次使用
require()
将其导入任何位置。假设您在一个文件中有多个函数或对象,那么您可以执行如下操作
module.exports={function1,object1}
。如果您需要更清晰的信息,请告诉我。你也可以参考这个。
{
  "name": "server",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "serve": "ts-node-dev server.ts",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@types/express": "^4.17.11",
    "express": "^4.17.1",
    "ts-node": "^9.1.1",
    "ts-node-dev": "^1.1.6",
    "tslint": "^6.1.3",
    "typescript": "^4.2.4"
  },
}
{
  "compilerOptions": {
    "target": "ESNEXT",                                
    "module": "commonjs", 
    "strict": false, 
    "esModuleInterop": true, 
    "skipLibCheck": true,                          
    "forceConsistentCasingInFileNames": true        
  }
}   
import * as express from 'express';

const app = express();

app.listen(4201, '127.0.0.', function() {
  console.log('Server is listening on port 4201');
});