3

I am trying to use swiper from swiperjs.com on my website. I installed node and added swiper as a dependency with the npm install swiper command. I created a swiper.js file where I am trying to import swiper:

import Swiper from "swiper";
const swiper = new Swiper(".swiper");

In the head of my HTML I added this line to load the swiper.js file:

<script type="text/javascript" src="http://localhost:8000/js/swiper.js"></script>

This is my package.json file:

{
  "name": "sasstheme",
  "version": "1.0.0",
  "scripts": {
    "watch": "sass --watch src/scss/style.scss style.css"
  },
  "devDependencies": {
    "sass": "^1.49.9"
  },
  "dependencies": {
    "swiper": "^8.0.7"
  }
}

When I load the page I am getting the following error in the console:

Uncaught SyntaxError: Cannot use import statement outside a module
István
  • 127
  • 10
  • You have to bundle it with some bundler (ex.: _Webpack_ or _Vite_) or use bundled version (_swiper-bundle.min.js_). – Jax-p Mar 14 '22 at 09:23
  • `import Swiper from 'swiper/bundle';` and `import Swiper from "swiper-bundle.min.js";` gives me the same error. @Jax-p – István Mar 14 '22 at 09:40
  • 1
    Yes. Because you are still using [import statement outside a module](https://stackoverflow.com/questions/58211880/uncaught-syntaxerror-cannot-use-import-statement-outside-a-module-when-import). Use some bundler or include your script as module (modern browsers only) or include swiper script solo ` – Jax-p Mar 14 '22 at 09:43
  • I used parcel as the bunder as you suggested and the `import` works fine now, thank you! However I am confused now what is the point of using a bundler to import the script and style and then load these in the HTML instead of just including it from swipers CDN. Is there any benefit of using a bundler? – István Mar 15 '22 at 01:09

0 Answers0