The Problem:
When running npx webpack
to build a Node.js application, an error is encountered stating that 'import' and 'export' may appear only with 'sourceType: module'
. This error is observed despite having the necessary webpack and babel loader dependencies installed and configured in the webpack.config.js
file. The application uses a mix of JavaScript and TypeScript files, and the index.js
file attempts to import a function from the server.ts
file using the import
syntax.
The Solutions:
Solution 1: Remove “type” from “package.json”
If you have "type": "commonjs"
in your package.json
, remove it. This setting is not compatible with ES modules and can cause the “Module parse failed: ‘import’ and ‘export’ may appear only with ‘sourceType: module'” error when using webpack.
Solution 2: Specify Source Type
In the .eslintrc
file, specify the sourceType
as "module"
under the parserOptions
object. This will instruct the parser to treat the code as a module, allowing for the use of import
and export
statements.
{
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module",
"ecmaFeatures": {
"jsx": true
}
}
}
Q&A
How to fix Module parse failed: “import” and “export” may appear only with “sourceType: module” in Node.js?
When you remove the “type”: “commonjs” from package.json then also facing this error?
.eslintrc
, set sourceType: “module” in parserOptions