João Vitor
João Vitor

Reputation: 39

__dirname error when using SerialPort on electron

I'm having some trouble using the SerialPort on my electron application. I've built it using Vite. Everytime I try to build the app, when using the SerialPort library, I get the following error:

This file is being treated as an ES module because it has a '.js' file extension and 'path-to-my-json-config-file' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension

But when I don't use it, it works perfectly. I'm running out of ideas of how to make this work out. Here's the main.ts file:

import { fileURLToPath } from 'url';
import path from 'path';

const __filename = fileURLToPath(import.meta.url);
globalThis.__dirname = path.dirname(__filename); // Cria uma variável global __dirname
import { app, BrowserWindow, ipcMain } from 'electron'
import { createRequire } from 'node:module'
import { SerialPort, ReadlineParser } from 'serialport';
import { filterData } from '../src/backend/COMdata';


// The built directory structure
//
// ├─┬─┬ dist
// │ │ └── index.html
// │ │
// │ ├─┬ dist-electron
// │ │ ├── main.js
// │ │ └── preload.mjs
// │
process.env.APP_ROOT = path.join(__dirname, '..')

// 🚧 Use ['ENV_NAME'] avoid vite:define plugin - [email protected]
export const VITE_DEV_SERVER_URL = process.env['VITE_DEV_SERVER_URL']
export const MAIN_DIST = path.join(process.env.APP_ROOT, 'dist-electron')
export const RENDERER_DIST = path.join(process.env.APP_ROOT, 'dist')

process.env.VITE_PUBLIC = VITE_DEV_SERVER_URL ? path.join(process.env.APP_ROOT, 'public') : RENDERER_DIST

let win: BrowserWindow | null
let serialPort: SerialPort | null = null;


function createWindow() {
  win = new BrowserWindow({
    width: 1280,
    height: 720,
    minHeight: 720,    
    minWidth: 1280,    
    icon: path.join(process.env.VITE_PUBLIC, 'electron-vite.svg'),
    webPreferences: {
      preload: path.join(__dirname, 'preload.mjs'),
      nodeIntegration: true,
      contextIsolation: false,
    },
  })
  

  // Test active push message to Renderer-process.
  win.webContents.on('did-finish-load', () => {
    win?.webContents.send('main-process-message', (new Date).toLocaleString())
  })

  if (VITE_DEV_SERVER_URL) {
    win.loadURL(VITE_DEV_SERVER_URL)
  } else {
    // win.loadFile('dist/index.html')
    win.loadFile(path.join(RENDERER_DIST, 'index.html'))
  }


}


// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
    win = null
  }
})


app.on('activate', () => {
  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow()
  }
})




app.whenReady().then(() => {
  createWindow()

    const serialPort = new SerialPort ("COM6", {baudRate:9600,})
    const parser = serialPort.pipe(new Readline({ delimiter: '\n' }));

    console.log('Porta serial configurada e aguardando dados.');

    // Processar dados recebidos e enviá-los ao frontend
    parser.on('data', (data) => {
        const dadosFiltrados = filterData(data); // Filtra os dados recebidos
        if (dadosFiltrados) {
            win.webContents.send('dados-filtrados', dadosFiltrados); // Envia ao frontend
        }
    });

    serialPort.on('error', (err) => {
        console.error('Erro na porta serial:', err.message);
    });
})

Here's the package.json content:

    {
  "name": "telemetry-viewer",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "tsc && vite build && electron-builder",
    "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
    "preview": "vite preview"
  },
  "dependencies": {
    "@radix-ui/colors": "^3.0.0",
    "@radix-ui/react-dialog": "^1.1.2",
    "@radix-ui/react-icons": "^1.3.0",
    "@radix-ui/react-menubar": "^1.1.2",
    "@radix-ui/react-navigation-menu": "^1.2.1",
    "@radix-ui/react-progress": "^1.1.0",
    "@radix-ui/react-select": "^2.1.2",
    "@radix-ui/react-separator": "^1.1.0",
    "@radix-ui/react-slot": "^1.1.0",
    "@radix-ui/react-toggle": "^1.1.0",
    "@radix-ui/react-toggle-group": "^1.1.0",
    "@radix-ui/react-tooltip": "^1.1.3",
    "@react-google-maps/api": "^2.20.3",
    "class-variance-authority": "^0.7.0",
    "classnames": "^2.5.1",
    "clsx": "^2.1.1",
    "common-es": "^1.0.1",
    "cors": "^2.8.5",
    "esbuild": "^0.24.0",
    "express": "^4.21.1",
    "leaflet": "^1.9.4",
    "lucide-react": "^0.453.0",
    "node-loader": "^2.1.0",
    "react": "^18.1.0",
    "react-circular-gauge": "^1.1.1",
    "react-dom": "^18.2.0",
    "react-leaflet": "^4.2.1",
    "react-speedometer": "^0.1.2",
    "serialport": "^12.0.0",
    "tailwind-merge": "^2.5.4",
    "tailwindcss-animate": "^1.0.7",
    "vite-tsconfig-paths": "^5.0.1"
  },
  "devDependencies": {
    "@types/leaflet": "^1.9.14",
    "@types/node": "^22.7.6",
    "@types/react": "^18.3.12",
    "@types/react-dom": "^18.2.21",
    "@types/react-leaflet": "^3.0.0",
    "@types/serialport": "^10.2.0",
    "@typescript-eslint/eslint-plugin": "^7.1.1",
    "@typescript-eslint/parser": "^7.1.1",
    "@vitejs/plugin-react": "^4.2.1",
    "autoprefixer": "^10.4.20",
    "electron": "^30.0.1",
    "electron-builder": "^24.13.3",
    "eslint": "^8.57.0",
    "eslint-plugin-react-hooks": "^4.6.0",
    "eslint-plugin-react-refresh": "^0.4.5",
    "postcss": "^8.4.47",
    "prettier": "^3.4.2",
    "prettier-plugin-tailwindcss": "^0.6.9",
    "tailwindcss": "^3.4.14",
    "typescript": "^5.2.2",
    "vite": "^5.1.6",
    "vite-plugin-electron": "^0.28.6",
    "vite-plugin-electron-renderer": "^0.14.5",
    "vite-plugin-externals": "^0.6.2"
  },
  "main": "dist-electron/main.js"
}

Upvotes: 0

Views: 39

Answers (0)

Related Questions