Home > Software design >  Importing a JS npm library in Svelte
Importing a JS npm library in Svelte

Time:01-06

I don't understand how to import a random npm library in Svelte.

Take the scrapegoat library for example, a library to read CalDAV objects. I created a brand new Svelte project:

$ npx degit sveltejs/template my-svelte-project
$ cd my-svelte-project/
$ npm install
$ npm install -D scrapegoat

Not sure if it should be added to the devDependencies but it doesn't seem to make a lot of difference if it is not. Now, in the src/App.svelte I add this singe line in the existing <script> tag.

import scrapegoat from 'scrapegoat'

Running npm run dev throws the following error:

[!] Error: Unexpected token (Note that you need @rollup/plugin-json to import JSON files)
node_modules/scrapegoat/package.json (2:9)
1: {
2:   "_from": "scrapegoat@^2.0.0",
            ^
3:   "_id": "[email protected]",
4:   "_inBundle": false,
Error: Unexpected token (Note that you need @rollup/plugin-json to import JSON files)
    at error (node_modules/rollup/dist/shared/rollup.js:158:30)
    at Module.error (node_modules/rollup/dist/shared/rollup.js:12420:16)
    at Module.tryParse (node_modules/rollup/dist/shared/rollup.js:12823:25)
    at Module.setSource (node_modules/rollup/dist/shared/rollup.js:12726:24)
    at ModuleLoader.addModuleSource (node_modules/rollup/dist/shared/rollup.js:22197:20)

This is what I understood from Rich Harris' reply but I am clearly missing something.

CodePudding user response:

The package you’re importing imports its own package.json. Rollup won’t handle JSON imports by default, so you will need to install the json plugin and add it to your Rollup config.

  •  Tags:  
  • Related