获取"Module parse failed: 'import' and 'export' may appear only with 'sourceType: module' "



我正面对着

ERROR in ./index.js 1:0
模块解析失败:'import'和'export'可能只出现在'sourceType: Module ' (1:0)
文件被这些加载器处理:
* ./node_modules/babel-loader/lib/index.js
你可能需要一个额外的加载器来处理这些
加载器的结果。
在import {startServer} from "./server"
| import _ from 'lodash';

在执行npx webpack为NodeJS应用程序创建构建时。这是我的webpack.config.jspackage.json文件。

webpack.config.js

const path = require('path');
module.exports = {
mode: 'production',
target: 'node',
entry: './index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [
{
test: /.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets:  [
['@babel/preset-env']
],
},
},
},
],
},
};

package.json

{
"name": "restapi-ts",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "commonjs",
"scripts": {
"compile": "tsc",
"start": "npm run compile && node ./dist/index.js",
"build": "webpack"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.18.2",
"lodash": "^4.17.21",
"pg": "^8.10.0",
"pgtools": "^0.1.1"
},
"devDependencies": {
"@babel/cli": "^7.21.0",
"@babel/core": "^7.21.4",
"@babel/node": "^7.20.7",
"@babel/preset-env": "^7.21.4",
"@types/express": "^4.17.17",
"@types/pg": "^8.6.6",
"babel-loader": "^9.1.2",
"typescript": "^4.9.5",
"webpack": "^5.77.0",
"webpack-cli": "^5.0.1"
}
}

server.ts

import express from 'express';
import Route from './src/routes'
const bodyParser = require('body-parser');
const app = express();
// Parse JSON data
app.use(bodyParser.json());
//app.use(express.json());

app.get("/", (req, res) => {
res.send("Hi World");
});

app.use("/api/v1/order", Route);

// Start the server
export function startServer()
{
app.listen(3000, () => {
console.log('Server started on port 3000');
});
}

index.js

import { startServer } from "./server";
//const { startServer } = require("./server");
import _ from 'lodash';
startServer();

我已经下载了所有的webpack依赖,也有babel加载器依赖。请分享你的建议如何解决这个错误。

.eslintrc中指定类型:

{
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module",
"ecmaFeatures": {
"jsx": true
}
}
}

如果您的包中有"type": "commonjs",。Json,删除它帮助我解决了同样的错误

相关内容

最新更新