Import error: Unexpected token {

Hello everyone,

I would like to try Capacitor and I have started creating a new basic app using ‘npm init @capacitor/app’ tool. I can start the app on Android, but I’ve tried to add a new plugin (Device plugin for example) so I’ve added the ‘import { Device } from ‘@capacitor/device’’ in the first line of my .js file, but after that, when I try to run the app on Android I get an ‘Uncaught SyntaxError: Unexpected token {’ in the first line of my .js file, so the problem is the import sentence…

Does anybody know why the import is not working?

Thank you!

Are you running it on an Android emulator? If so, which one? If not, which physical Android device?

I know I have had issues with the Pixel 2 emulator which is running a really old webview version which doesn’t support recent ECMAScript versions. My guess that is what is happening in your case.

Hello @twestrick, thank you for answering.

I was using Pixel 2 API 28 emulator. Changing to Pixel 3 API 30 emulator I get another error: “Uncaught SyntaxError: Cannot use import statement outside a module” at the same import line.

Do you know what’s happening?

Thank you for your help!

Try updating the Web View version in the Android Play Store. Many emulators ship with an ancient web view version

1 Like

For being able to use the import { Device } from "@capacitor/device" syntax you’ll need to use a javascript bundler (webpack, browserify, parcel, rollup, etc.). The app created with npm init @capacitor/app doesn’t include one.

If not using a bundler you should use the syntax the created app uses for Camera const { Camera } = Capacitor.Plugins; but changing Camera to Device as that’s the plugin you want to use.
Note that this syntax will only work on iOS and Android native runs, but not on browser run.

I think it’s best to use Ionic CLI for creating an app as it includes bundlers and allows to use different frameworks (Angular, React, Vue)

Here you have getting started guides for all of them

Perfect @julio-ionic!

This is the problem! I’ll try using a bundler. I prefer to stay with plain javascript + HTML for the moment.

Thank you again!