Sunday, 26 July 2020

Cannot use import outside a module, even though the import is within a module?

I'm attempting to learn Node and JavaScript for probably the fifth time, and I'm stuck on what I assume is a pretty basic error. When trying to use import instead of require() I get the following errors:import { app, shell, BrowserWindow, Menu, ipcMain } from "electron"; ^^^^^^ SyntaxError: Cannot use import statement outside a module and a little farther down:(node:13732) Warning: require() of ES modules is not supported. require() of E:\Code\scheduler\main.js from E:\Code\scheduler\node_modules\electron\dist\resources\default_app.asar\main.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules. Instead rename E:\Code\scheduler\main.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from E:\Code\scheduler\package.json. The "explanation" it gives seems a little contradictory given that I am using import instead of require, and it says that it's an ES module yet above it tells me it isn't.After researching for a bit, I updated from v12 LTS to v14.6.0 which allows support for ES modules, and I added "type": "module" to my package.json in the root of the project. From my understanding this will make every .js file within the folder tree act as an ES module. However, I still get the same error and I have no idea why. Does it have something to do with Electron not supporting the use of import, or is it something else? If it is Electron, am I able to use require just for it but use import for everything else, or is it all or nothing?Here is the relevant code from my main.js:import { app, shell, BrowserWindow, Menu, ipcMain } from "electron"; import { MainWindow } from "./src/js/mainWindow.js"; function startApp() { const mainWindow = new MainWindow(); ... and from mainWindow.js:import {BrowserWindow, Menu, app, shell } from 'electron'; export class MainWindow { #browserWindow; constructor() { ... the rest of my code works fine, the import statements are my only problem. Any help is greatly appreciated!

Submitted July 27, 2020 at 04:47AM by Nightfuse

No comments:

Post a Comment