Skip to content

bug: Running "vanilla JS" project with Vite fails #24252

Closed

Description

@raymondboswel

Prerequisites

Ionic Framework Version

  • v4.x
  • v5.x
  • v6.x

Current Behavior

I want to use Ionic in a Svelte application using Vite as build system. I know that Svelte isn't officially supported, but everything I need seems to work fine. The issue I'm having, is being able to bundle Ionic along with my application, instead of fetching from the CDN, so that the application can work offline when built with Capacitor.

My current strategy of including Ionic from node_modules is adding this line to index.html:
<script type="module" src="node_modules/@ionic/core/dist/ionic/ionic.esm.js"></script>
This however causes vite to fail with:


  node_modules/@ionic/core/dist/ionic/ionic.esm.js (imported by /home/raymond/git/svelte-capacitor/index.html)```

If I add the file after starting the dev server, Ionic starts working. 

Building the application fails with the same error. 




### Expected Behavior

As stated in the Ionic V6 announcement, Vite should be able to bundle Ionic. The packages intro also mentions that Ionic can be run without using any framework, but doesn't provide a clear way to do that other than using a CDN. Since Ionic is aimed at building mobile applications, it stands to reason that it should include the dependencies at build time, and not runtime.

I'm sure this is quite a niche use case, but I think it would make Ionic useable in more contexts if greater clarity was provided on how to use Ionic in a vanilla project using some form of a bundler. 

### Steps to Reproduce

Clone this repo: https://github.com/raymondboswel/svelte-capacitor
* npm i
* npm run dev:start

### Code Reproduction URL

https://github.com/raymondboswel/svelte-capacitor

### Ionic Info

Ionic:

   Ionic CLI : 6.18.1 (/home/raymond/.nvm/versions/node/v16.13.0/lib/node_modules/@ionic/cli)

Capacitor:

   Capacitor CLI      : not installed
   @capacitor/android : 3.3.2 (/home/raymond/git/svelte-capacitor/node_modules/@capacitor/android)
   @capacitor/core    : 3.3.2 (/home/raymond/git/svelte-capacitor/node_modules/@capacitor/core)
   @capacitor/ios     : 3.3.2 (/home/raymond/git/svelte-capacitor/node_modules/@capacitor/ios)

Utility:

   cordova-res : not installed globally
   native-run  : not installed globally

System:

   NodeJS : v16.13.0 (/home/raymond/.nvm/versions/node/v16.13.0/bin/node)
   npm    : 8.1.0
   OS     : Linux 5.13

### Additional Information

_No response_

Activity

  1. raymondboswel commented on Nov 22, 2021

    @raymondboswel
    Author

    I've found a solution which seems reasonable. I added a postinstall script to package.json to copy node_modules/@Ionic to assets/@Ionic. And reference Ionic from there in index.html. It feels like the least hacky solution I could come up with.

    I still think having a solution to work with Ionic without framework bindings in a bundled context is useful, but feel free to close this ticket.

  2. liamdebeasi commented on Nov 22, 2021

    @liamdebeasi
    Contributor

    Thanks for the issue. When using Ionic components without a framework integration, you are going to need to import the components and declare them manually:

    import { IonBadge } from "@ionic/core/components/ion-badge";
    import { initialize } from "@ionic/core/components";
    
    initialize();
    
    customElements.define("ion-badge", IonBadge);

    This initialize function is needed to setup Ionic's config. From there, you should be able to reference <ion-badge> in your template and the compiler should bundle that code properly. Can you give that a shot and let me know if it resolves the issue?

  3. added
    needs: reply
    on Nov 22, 2021
  4. raymondboswel commented on Nov 23, 2021

    @raymondboswel
    Author

    Hi Liam!

    I added the following in the app's root component:

     import { initialize } from "@ionic/core";
      import { IonApp } from "@ionic/core/components/ion-app";
      import { IonButton } from "@ionic/core/components/ion-button";
      // ...<rest of imports>...
      import { IonRippleEffect } from "@ionic/core/components/ion-ripple-effect";
    
     onMount(() => {
        initialize();
    
        tryDefine("ion-app", IonApp);
        tryDefine("ion-button", IonButton);
        tryDefine("ion-buttons", IonButtons);
        tryDefine("ion-card", IonCard);
        tryDefine("ion-icon", IonIcon);
        tryDefine("ion-toolbar", IonToolbar);
        tryDefine("ion-header", IonHeader);
        tryDefine("ion-content", IonContent);
        tryDefine("ion-card-header", IonCardHeader);
        tryDefine("ion-cart-title", IonCardTitle);
        tryDefine("ion-card-subtitle", IonCardSubtitle);
        tryDefine("ion-card-content", IonCardContent);
        tryDefine("ion-ripple-effect", IonRippleEffect);
    
    
        function tryDefine(tag, impl) {
          try {
            customElements.define(tag, impl);
          } catch (error) {}
        }
      });
    

    It seems to partially work, but with some issues.

    The body tag is hidden due to this class: html:not(.hydrated) body

    If I remove the hidden attribute in dev tools, I can see the components, but styling isn't applied:
    image

    Also, if I click the button, it's supposed to open a modal and display a toast, which fails with:
    image

    The code used to display the modal is:

    import {
      modalController,
      toastController
    } from "@ionic/core";
    
    //Unused component variable to force component import at function call
    export const IonicShowModal = async (
      selector: string,
      component: new (...args: any) => SvelteComponent,
      componentProps: any
    ) => {
      const modal = await modalController.create({
        component: selector,
        componentProps,
      });
      modal.present();
      return await modal.onWillDismiss();
    };
    

    Lastly, I've also noticed some of the components have 'undefined' classes in their class list:
    image

    It seems like some additional initialization and/or config is missing. I do have a styles.scss importing the ionic styles, which is imported into my root component.

  5. added and removed
    needs: reply
    on Nov 23, 2021
  6. andreasbhansen commented on Nov 23, 2021

    @andreasbhansen

    I've found a solution which seems reasonable. I added a postinstall script to package.json to copy node_modules/@Ionic to assets/@Ionic. And reference Ionic from there in index.html. It feels like the least hacky solution I could come up with.

    I still think having a solution to work with Ionic without framework bindings in a bundled context is useful, but feel free to close this ticket.

    The downside of this approach would be the increase in app installation size (I assume?), or did you apply any clever tree shaking to the /assets/ionic folder to remove unnecessary files?

  7. raymondboswel commented on Nov 23, 2021

    @raymondboswel
    Author

    Yes, it comes in at ~18MB, though I copy the full @ionic/core package. If I only copy e.g the dist/esm directory it's ~2MB. For an app install I don't think it matters that much.

  8. liamdebeasi commented on Nov 23, 2021

    @liamdebeasi
    Contributor

    You also need to be loading from @ionic/core/components not @ionic/core. @ionic/core by default uses the lazy loaded version which is known to be incompatible with modern bundlers.

    This documentation may be helpful: https://github.com/ionic-team/ionic-framework/tree/main/core#custom-elements-build-experimental

    One thing that is missing (which I will add) is that you need to do the following too:

    document.documentElement.classList.add('ion-ce');

    Also make sure you are importing the correct CSS to get the base styles:

    /* Core CSS required for Ionic components to work properly */
    import '@ionic/core/css/core.css';
    
    /* Basic CSS for apps built with Ionic */
    import '@ionic/core/css/normalize.css';
    import '@ionic/core/css/structure.css';
    import '@ionic/core/css/typography.css';
    
    /* Optional CSS utils that can be commented out */
    import '@ionic/core/css/padding.css';
    import '@ionic/core/css/float-elements.css';
    import '@ionic/core/css/text-alignment.css';
    import '@ionic/core/css/text-transformation.css';
    import '@ionic/core/css/flex-utils.css';
    import '@ionic/core/css/display.css';

    I think it's worthwhile to add some docs to https://ionicframework.com/docs/intro/cdn to show how to use Ionic Core with other frameworks.

  9. added
    needs: reply
    on Nov 23, 2021
  10. raymondboswel commented on Nov 24, 2021

    @raymondboswel
    Author

    That worked! Everything seems to be in order now, thank you very much! 🍻

  11. added and removed
    needs: reply
    on Nov 24, 2021
  12. liamdebeasi commented on Nov 24, 2021

    @liamdebeasi
    Contributor

    Great! The original issue appears to be resolved, so I am going to close this out. I created ionic-team/ionic-docs#2105 which will track documentation changes for using @ionic/core in a non Angular/React/Vue environment.

  13. piotr-cz commented on Dec 9, 2021

    @piotr-cz

    There is one change when updating from @ionic/react 6.0.0-rc.3 as noted in the upgrade guide:

    import { setupIonicReact } from '@ionic/react'
    
    setupIonicReact()
  14. ionitron-bot commented on Jan 8, 2022

    @ionitron-bot

    Thanks for the issue! This issue is being locked to prevent comments that are not relevant to the original issue. If this is still an issue with the latest version of Ionic, please create a new issue and ensure the template is fully filled out.

  15. locked and limited conversation to collaborators on Jan 8, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions