Search code examples
javascriptcordovacapacitor

Import Capacitor Community plugin into a vanilla js script


I have a basic app written in pure javascript (index.html, script.js) which i put into a CapacitorJs project to let me create ios/android apps. which work perfectly fine even on my phone.

But now i'm trying to use a capacitor community plugin (@capacitor-community/contacts) but i need to import it in my script.js like this

import { Contact, Contacts, NewContact } from '@capacitor-community/contacts';

Since i'm not using typescript it obviously throw an error.

How can i manage to make it work ?

  • I have tried to import it through a <script type="module"> on my index.html and assign it to the js global window variable to access it in my script.js but it doesn't work.

  • I have also tried to convert my scripts.js to a typescript and compile it with the following config:

{
  "target":"es5",
  "module":"es2015",
  "moduleResolution:"node"
}

And to make it work, had to change the import string to: import { Contact, Contacts, NewContact } from '../../nodes_modules/@capacitor-community/contacts';

But then i get an error on the console saying TypeError: 'text/html' is not a valid Javascript MIME type

  • I ve tried also with the following config
  "target":"commonjs",

But got error with "define" not being recognized in the browser.

  • I am also aware of "bundledWebRuntime": true, that basically compile capacitor core files into a .js that you import in your index.html. But it doesn't include community packages so it's not a solution.

Solution

  • It has nothing to do with typescript. Your project must be declared to use ES modules, in order to use features such as import. I'm a bit unclear on your exact setup, but if you have a package.json, then try adding this to it:

    {
      ...
      type: "module",
    }
    

    If you just have a basic setup, i.e. html page with a js file in a script tag, you should be able to get it to work by declaring your js file as a module like this:

    <script type="module" src="main.js"></script>