Jud*_*ta 4 express typescript ts-node
我对这一切都很陌生,我正在尝试将 Node + Typescript 后端添加到我的 Angular 项目中。但是导入express后总是报错。
[ERROR] SyntaxError: Cannot use import statement outside a module.
Run Code Online (Sandbox Code Playgroud)
{
"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"
},
}
Run Code Online (Sandbox Code Playgroud)
{
"compilerOptions": {
"target": "ESNEXT",
"module": "commonjs",
"strict": false,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
}
}
Run Code Online (Sandbox Code Playgroud)
import * as express from 'express';
const app = express();
app.listen(4201, '127.0.0.', function() {
console.log('Server is listening on port 4201');
});
Run Code Online (Sandbox Code Playgroud)
我查了一下,最常见的解决方案是将“type”:“module”添加到我所做的package.json中。我还知道这仅适用于节点 13 及更高版本,并且我的节点为:14.15.5。
小智 7
导入节点模块的最佳实践是使用 require()。您可以使用 require() 函数导入内置核心节点模块、npm 模块以及本地模块。在您的情况下,请使用const express = require( "express" )而不是import * as express from 'express'从 package.json 中删除“type”:“module”。让我知道这是否适合您。
| 归档时间: |
|
| 查看次数: |
16046 次 |
| 最近记录: |