Skip to main content

Command Palette

Search for a command to run...

Fixing "Cannot use import statement outside a module" in Svelte PopperJs

Updated
Fixing "Cannot use import statement outside a module" in Svelte PopperJs

When working with Svelte and PopperJs, you may encounter the error: Cannot use import statement outside a module. This issue arises because PopperJs uses ES modules, and the environment might not correctly identify the module type. This post provides a simple fix for this error.

The Issue

The error usually occurs when trying to import PopperJs in a Svelte project. The root cause is that the Node.js environment doesn't recognize the ES module syntax due to the missing type: "module" in the package.json of the PopperJs package.

The Solution

To resolve this, you need to modify the package.json file in the PopperJs package. Follow these steps:

  1. Navigate to the PopperJs Core Directory: Go to the node_modules/@popperjs/core directory in your project.

  2. Edit the package.json File: Open the package.json file and locate the JSON object.

  3. Add the type Field: Add "type": "module" to the JSON object. It should look something like this:

     jsonCopy code{
       "name": "@popperjs/core",
       "version": "2.x.x",
       "main": "lib/index.js",
       "type": "module"
       // other configurations...
     }
    
  4. Save the File: Save the changes and restart your development server.

Conclusion

By adding "type": "module" to the package.json file, you instruct the Node.js environment to treat the PopperJs code as an ES module. This simple fix should resolve the import error and allow you to continue developing your Svelte project without any issues.

Feel free to share this solution with anyone facing the same problem, and happy coding!

Resources:

https://stackoverflow.com/questions/68039848/syntaxerror-cannot-use-import-statement-outside-a-module-from-dependency

https://github.com/sveltejs/kit/issues/4504

More from this blog

M

Makeinfo Blog | Tech Guides, SEO Tips, and Marketing Automation

127 posts

Blogging helpful tech tips, how-to tutorials since 2020