How to fix SyntaxError: Cannot use import statement outside a module?
How to fix SyntaxError: Cannot use import statement outside a module?
我对这一切都不熟悉,我正在尝试将 Node + Typescript 后端添加到我的 Angular 项目中。但是在导入express后我总是报错。
[ERROR] SyntaxError: Cannot use import statement outside a module.
package.json
{
"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"
},
}
tsconfig.json
{
"compilerOptions": {
"target": "ESNEXT",
"module": "commonjs",
"strict": false,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
}
}
server.ts
import * as express from 'express';
const app = express();
app.listen(4201, '127.0.0.', function() {
console.log('Server is listening on port 4201');
});
我查了一下,最常见的解决方案是将 "type": "module" 添加到 package.json 中,我也这样做了。我也知道这仅适用于 Node 13 及更远的节点,并且我有 Node: 14.15.5.
导入节点模块的最佳做法是使用 require()。您可以使用 require() 函数导入内置核心节点模块、npm 模块以及本地模块。在你的情况下,使用 const express = require( "express" )
而不是 import * as express from 'express'
并从你的 package.json 中删除“type”:“module”。让我知道这是否适合你。
我对这一切都不熟悉,我正在尝试将 Node + Typescript 后端添加到我的 Angular 项目中。但是在导入express后我总是报错。
[ERROR] SyntaxError: Cannot use import statement outside a module.
package.json
{
"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"
},
}
tsconfig.json
{
"compilerOptions": {
"target": "ESNEXT",
"module": "commonjs",
"strict": false,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
}
}
server.ts
import * as express from 'express';
const app = express();
app.listen(4201, '127.0.0.', function() {
console.log('Server is listening on port 4201');
});
我查了一下,最常见的解决方案是将 "type": "module" 添加到 package.json 中,我也这样做了。我也知道这仅适用于 Node 13 及更远的节点,并且我有 Node: 14.15.5.
导入节点模块的最佳做法是使用 require()。您可以使用 require() 函数导入内置核心节点模块、npm 模块以及本地模块。在你的情况下,使用 const express = require( "express" )
而不是 import * as express from 'express'
并从你的 package.json 中删除“type”:“module”。让我知道这是否适合你。