获取“模块解析失败:'import'和'export'只能与'sourceType: module'一起出现”

3
我遇到了一个问题
错误:./index.js 1:0 模块解析失败:'import'和'export'只能与'sourceType:module'一起使用(1:0) 文件已使用以下加载器进行处理: * ./node_modules/babel-loader/lib/index.js 您可能需要一个额外的加载器来处理这些加载器的结果。 >从"./server"导入{ startServer }; |导入_ from 'lodash';
在执行npx webpack创建NodeJS应用程序的构建时。 这是我的webpack.config.js和package.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 loader的依赖项。请分享您的建议,如何修复这个错误。


你修好了吗?我在尝试使用React + Webpack + Typescript + Cesium时遇到了同样的问题。 - MaylorTaylor
2个回答

2
如果你的 package.json 文件中有 "type": "commonjs",请将其删除 帮助我解决了相同的错误

2
在 .eslintrc 文件中,指定类型:
{
    "parserOptions": {
        "ecmaVersion": 6,
        "sourceType": "module",
        "ecmaFeatures": {
            "jsx": true
        }
    }
}

谢谢您的回复。在我的代码中,没有.eslintrc文件。我正在使用webpack。您能否就此提供建议? - rishu rathaur

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接