How to solve the famous issue "Cannot use import statement outside a module"
in an Electron-React-Typescript app?
//const { app, BrowserWindow } = require('electron');
import { app, BrowserWindow } from 'electron';
Error :
import { app, BrowserWindow } from 'electron';
^^^^^^
SyntaxError: Cannot use import statement outside a module
in package.json I added :
"type": "module",
devDependencies in package.json :
"@types/node": "^14.14.28",
"@types/react": "^17.0.2",
"electron": "^11.2.3",
"typescript": "^4.1.5",
"webpack": "^5.21.2"
tsconfig.json :
{
"compilerOptions": {
"target": "ES2018",
"module": "CommonJS",
"lib": ["dom", "esnext"],
"outDir": "dist",
"declaration": true,
"declarationMap": true,
"noEmit": true,
"jsx": "react",
"strict": true,
"pretty": true,
"sourceMap": true,
"skipLibCheck": true,
"noImplicitAny": false,
"noImplicitThis": false,
/* Additional Checks */
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
/* Module Resolution Options */
"moduleResolution": "node",
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"resolveJsonModule": true,
"allowJs": true
},
"include": ["src/**/*"],
"exclude": [
"src/index.js",
"dist",
]
}
I also added in babel.config.json 's plugins :
["@babel/plugin-transform-modules-commonjs", {
"allowTopLevelThis": true
}],
and in package.json :
"scripts": {
"babel": "babel ./src/**/* -d dist",
"start": "yarn run babel && electron .",
- electron : 11.2.3
- typescript : 4.1.5
- node: v14.5.0
- O.S. : Ubuntu 18.04.4 Desktop
What do I have to add / modify in order to be able to use "import" ?