我对这些都很陌生,但我正在尝试将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');
});
我翻阅了相关资料,最常见的解决方案是在 package.json 中添加 "type": "module"。我已经这样做了。我也知道这只适用于 Node 13 及以上版本,并且我的版本是 Node: 14.15.5。
export {app as routes};
这可能是错误的,就像我的导入一样。 - Juditamodule.exports
。例如,假设您有一个像这样的函数const func = () => console.log('hello world')
在 file.js 文件中。所以你所要做的就是module.exports = func
然后再使用require()
在任何地方导入它。如果您有多个函数或对象在一个文件中,那么您可以这样做module.exports={ function1, object1 }
。如果您需要更多的澄清,请告诉我。您也可以参考此链接。 - Roshan Kanwar