How to properly use nodejs modules on a capacitor aplication. Testing on welcome build

161 Views Asked by At

I've being trying to build an application that would run on capacitor and would also supports nodejs modules, so I could eventually use some of them on android. But first I'm trying to make them working on a desktop.

To test an initial build, I've read the getting-started section of the capacitor documentation. And modify it slightly to work with two modules that I'll probably used in the future, those are json5 and path.

Following the documentation, I've used the welcome build available by typing:

npm init @capacitor/app

Then I modified the file created at src/js/capacitor-welcome.js. Since require() wasn't working I used the import keyword

import { SplashScreen } from '@capacitor/splash-screen';
import { Camera } from '@capacitor/camera';
import json5 from 'json5'
// import path from 'path' // will broke the page

window.customElements.define(
  'capacitor-welcome',
  class extends HTMLElement {
    constructor() {
      super();

      console.log("json5 is building normally")
      console.log(json5)
      console.log("path isn't")
      // console.log(path)

// ... rest of the code

Import the necessary modules:

npm i json5
npm i path

And then proceed to build and previewing it on my browser:

npx vite build
npx vite preview

By removing the comment of the path import, you can see how it breaks the page.

Is there a way to universally build all modules just like a require('path') would do in the context of nodejs? Should I differ my strategy entirely?

0

There are 0 best solutions below