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 .",
What do I have to add / modify in order to be able to use "import"?
Thanks to and Electron's expert I discovered two errors which caused that issue:
I modified the main's path in package.json
"main": "./src/main/main.ts"
---> "main": "./dist/main/main.js"
because electron can understand only the compiled file
I removed in package.js on
"type": "module"
which otherwise wuold require to change .js to
.cjs files
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.