What is the process for importing module functions in Svelte when utilizing npm?

I'm having trouble understanding how to properly use imports in Svelte with npm. I have a Svelte component that I can't seem to get working. Uncommenting

"//import { Configuration, OpenAIApi } from "openai";"
leads to the error message:
[!] (plugin commonjs--resolver) RollupError: Unexpected token (Note that you need @rollup/plugin-json to import JSON files)

If I don't uncomment it, I get

Uncaught ReferenceError: Configuration is not defined
in the browser console.

<script>
//import { Configuration, OpenAIApi } from "openai";
const OpenAiConfiguration = new Configuration({
  organization: "my-org-key", 
  apiKey: "my-api-key",
});
$: gptRespons = "";
const questionQuery = "Do you agree with the sentiment and conclusion of the following article? "


async function FetchNews(link) {
  try {
    let brukSak = await AiSummarize(link);
    gptRespons = brukSak["data"]["choices"][0]["message"]["content"]
    console.log("Ferdig å hente og oppsummere nyheter");
  } catch (error) {
    alert("Error");
    console.error(error);
  }
  return;
}
async function AiSummarize(newsStoryUrl) {

  const openai = new OpenAIApi(OpenAiConfiguration);

  try {
    const result = await openai.createChatCompletion({
      model: "gpt-3.5-turbo",
      messages: [{role:"user", "content":`Skriv en oppsummering av ${newsStoryUrl} Oppsumeringen skal være morsom og glad`}]
    
    });

    return result;
  } catch (error) {
    alert("Error summarizing news story");
    console.error(error);
    throw error;
  }
}
FetchNews(insertlink")

</script>

<h2>
    GPT:Respons
</h2>
<p>
    {gptRespons}
</p>

How can I fix this? Is there any particular parts or concepts of Svelte and npm that I may have misunderstood?

I expected the code to correctly access the Configuration class. I tried using openai.Configuration, running npm install openai again, and executing

npm install @rollup/plugin-json --save-dev
in the terminal.

Thank you for your time and attention<3

Here is my rollup.config file:

import { spawn } from 'child_process';
import svelte from 'rollup-plugin-svelte';
import commonjs from '@rollup/plugin-commonjs';
import terser from '@rollup/plugin-terser';
import resolve from '@rollup/plugin-node-resolve';
import livereload from 'rollup-plugin-livereload';
import css from 'rollup-plugin-css-only';

const production = !process.env.ROLLUP_WATCH;

function serve() {
    let server;

    function toExit() {
        if (server) server.kill(0);
    }

    return {
        writeBundle() {
            if (server) return;
            server = spawn('npm', ['run', 'start', '--', '--dev'], {
                stdio: ['ignore', 'inherit', 'inherit'],
                shell: true
            });

            process.on('SIGTERM', toExit);
            process.on('exit', toExit);
        }
    };
}

export default {
    input: 'src/main.js',
    output: {
        sourcemap: true,
        format: 'iife',
        name: 'app',
        file: 'public/build/bundle.js'
    },
    plugins: [
        svelte({
            compilerOptions: {
                // enable run-time checks when not in production
                dev: !production
            }
        }),
        // we'll extract any component CSS out into
        // a separate file - better for performance
        css({ output: 'bundle.css' }),

        // If you have external dependencies installed from
        // npm, you'll most likely need these plugins. In
        // some cases you'll need additional configuration -
        // consult the documentation for details:
        // https://github.com/rollup/plugins/tree/master/packages/commonjs
        resolve({
            browser: true,
            dedupe: ['svelte'],
            exportConditions: ['svelte']
        }),
        commonjs(),

        // In dev mode, call `npm run start` once
        // the bundle has been generated
        !production && serve(),

        // Watch the `public` directory and refresh the
        // browser on changes when not in production
        !production && livereload('public'),

        // If we're building for production (npm run build
        // instead of npm run dev), minify
        production && terser()
    ],
    watch: {
        clearScreen: false
    }
};

Answer №1

To incorporate the JSON plugin into your configuration, simply follow these steps:

import json from '@rollup/plugin-json';

plugins: [
    // include the JSON plugin
    json(),

    // other plugins
  ]

If you are starting a new project, I recommend using Vite for easier development.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The art of combining arrays of objects while eliminating duplicates

I am in need of a solution to compare two object arrays, remove duplicates, and merge them into a single array. Although I am relatively new to javascript/Typescript, I have come across some blogs suggesting the use of Map, reduce, and filter methods for t ...

How can this be happening? It's expected that items will be printed, but for some reason

I'm struggling to figure out why the console.logs aren't showing up. import { GenericRepository, getGenericRepository } from '../src/database/repository/GenericRepository'; import { start, stop } from '../src/index'; import r ...

Adjust the height setting of the React-Highcharts viewport

My initial configuration for highcharts looks like this:- function getInitialHighChartsConfig(chartType) { return { credits: false, chart: { type: chartType, height: 325, }, title: { text: '', useHTML: tr ...

What is the best way to prevent a draggable div from moving past the edge of the viewport?

My situation involves a draggable div that functions as a popup window when a specific button is clicked. However, I noticed that dragging the div to the end of the viewport allows me to drag it out of the visible area, causing the body of the page to expa ...

I'm looking for a way to retrieve an object from a select element using AngularJS. Can

I am working with a select HTML element that looks like this: <select required="" ng-model="studentGroup"> <option value="" selected="">--select group--</option> <option value="1">java 15-1</option> <option value="2">ja ...

Eliminate rows with empty values in a specific column from a CSV file using Node.js

I am struggling with removing rows from a CSV file that have missing values. Can anyone assist me in solving this issue? ...

Vue email validation is failing to return a valid email address

I'm relatively new to Vue and have implemented email validation using the reg expression in my Vue script data for this project. By utilizing console.log(this.reg.test(this.email)) and observing the output while users input their email, the validation ...

Top method for creating consecutive Canvas animations using Javascript

Currently, I am working on animating a canvas element (specifically PaperJs Path/Text) along a path using PaperJs. The process involves user-created frames containing paths drawn by the user, where each frame consists of multiple paths and corresponding ca ...

What is the best way to prevent a strikethrough from appearing on the delete button in my JavaScript TO-Do application?

I'm working on coding a to-do app using JavaScript, HTML, and CSS. The issue I'm facing is that when I add the text-decoration: line-through property to the list items, it also affects the X icon used for deleting tasks. I suspect this problem ar ...

Scheduled tasks on Google Cloud Platform's App Engine are failing to run over the weekend

I am facing an issue with running a cron job in my node/express application using the node-cron library. The application is hosted on Google Cloud App Engine. My aim is to automate sending emails every day at 9 AM, but the cron seems to only work from Mon ...

How can a producer know when it's time to send a message in NodeJS using ZeroMQ?

After conducting some research on patterns supported by zeromq, I have encountered an issue with the PUB/SUB pattern in my recent project as well as the PUSH/PULL pattern. I am using NodeJS for the zeromq implementation. In my examples (server.js & client ...

Troubleshooting Date Problems in Angular

When using the HTML5 date picker, I have encountered an issue where after choosing a date, the ng-model displays an older date instead of the current one selected. <input type="date" ng-model="dateModel" /> For example, when selecting the current d ...

Is it secure to transmit Tenant ID's as GET parameters to the API in a Multi-Tenant database environment?

When working with a Multi-Tenant database, is it secure to pass Tenant ID's as query string parameters to the API while using popular JavaScript-based UI platforms like Angular or Vue and ensuring both the site and the API are HTTPS? For example, let ...

What steps are involved in creating a circular shape on canvas?

I am trying to create a circular shape in the canvas using the code below. The code involves moving an object with keyboard keys, and I need help making the canvas shape into a circle without affecting the functionality of the code. I attempted to modify t ...

Set up a personal build using NPM version 8 on your local machine

I am transitioning from Node 14 (with NPM 6) to Node 16 (with NPM 8) for my Angular application. This particular application consists of a project that we bundle as an NPM package. During local development, we utilize a script to build this project loca ...

When invoking a JavaScript method, the context variable 'this' is lost

I have developed a basic pointer to a method like this: export class SmbwaService { getExistingArsByLab(labId: number): Observable<SmwbaAr[]> { this.otherMethod(); } otherMethod(): void { } } let method: (x: number) => ...

Is the behavior of passing node-gyp flags to packages the same with yarn's "yarn add package --build-from-source" as it is with npm's "

It appears that yarn does not pass node-gyp flags to native packages in the same way as npm. For instance, when trying to install [email protected] using: npm install <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="186b69 ...

In order to successfully utilize Node.js, Async.js, and Listeners, one must ensure

Here is the log output from the code below, I am unsure why it is throwing an error. It seems that the numbers at the end of each line represent line number:char number. I will highlight some important line numbers within the code. Having trouble with t ...

Passing a single item from a list as a prop in Vue.js

Imagine having the following set of information in data: data: { todos: [ { id: 1, title: "Learn Python" }, { id: 2, title: "Learn JS" }, { id: 3, title: "Create WebApp" } ] } Now, I aim to send only the item with an id of 2 t ...

Strategies for consistently receiving updates of Iframe content body within a react useEffect hook

When loading html into an iframe using srcDoc with the sandbox="allow-same-origin", I face a challenge. Despite the content displaying properly, the property frameRef.contentDocument.body.innerHTML remains empty. This issue persists even after s ...