bigquestionsasked
bigquestionsasked

Reputation: 21

Svelte giving me 'Uncaught ReferenceError: require is not defined'

I'm trying to use a natural language generation library called RosaeNLG with my Svelte app but whenever I import any variable from the JavaScript file that 'requires' rosaenlg I get an error saying 'Uncaught ReferenceError: require is not defined'.

Rosae is a library for node.js or client side (browser) execution, based on the Pug template engine.

I have read similar issues with Svelte that have been solved by changing the 'requires' syntax to different forms of 'import'. For instance: 'import rosaenlgPug from "rosaenlg"'; 'import * as rosaenlgPug from "rosaenlg"'; var rosaenlgPug = import("rosaenlg")'; 'import("rosaenlg")'.

All of these variations fail to rollup and eventually give the error: 'FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory'.

Edit: I have managed to get an old version of Rosae working within a svelte file using the following code:

<script>
let rendered = "Busy...";

const onRosaeNlgLoad = () => {

    let array = ['x','y','z'];
    
    let template = `
mixin variable
  | this is a Rosae template #[+syn('synonym1', 'synonym2')]`
    
    rendered = rosaenlg_en_US.render(template, {
        language: 'en_US',
        fruits: fruits
    })
}
</script>

<svelte:head>
    <script src="https://unpkg.com/[email protected]/dist/rollup/rosaenlg_tiny_en_US_1.20.2_comp.js" on:load="{onRosaeNlgLoad}"></script>
</svelte:head>

<h1>{rendered}!</h1>

However, I still haven't been able to get it working in a JS file or by linking the template from a pug file, as instructed in the Rosae examples.

I'm trying the following in a JS file:

import * as rosaenlgPug from "rosaenlg";

let array = ['x', 'y', 'z']

let result = rosaenlgPug.renderFile('tuto.pug', {
    language: 'en_US',
    element: array[0]
});
 
export { result };

But when import the 'result' variable into a svelte file I get: 'Uncaught ReferenceError: require$$0$6 is not defined'.

Any suggestions about how to render a library like this in Svelte would be hugely appreciated. Thanks a lot.

Upvotes: 2

Views: 5212

Answers (2)

cssyphus
cssyphus

Reputation: 40106

This is not an answer, just some things to try.

There are a few possibilities - the message is not terribly helpful. I've run into this with other packages and here's what I did to resolve it:

First, is there a required package that has not been installed? What does the full error message say, after the ReferenceError: require is not defined? I've seen this happen with http2-proxy or with @snowpack/plugin-webpack or etc. E.g.

npm install --save-dev @snowpack/plugin-webpack

Also, if using snowpack, you might have a snowpack.config.mjs file. Try renaming it to just snowpack.config.js

(In my case, this instantly fixed it, this 2nd step)

Another thing to try: In your config file, try swapping require for import or vice versa. For e.g.

const pkg = require('http2-proxy');

to

const pkg = import('http2-proxy');

Upvotes: 0

hk7math
hk7math

Reputation: 297

I am not familiar with rosaenlg, but below is a minimal SvelteKit project that could run after specifying CommonJS libraries in svelte.config.js as instructed by the FAQ

Folder Structure

├── sveltekit-project/        // Root
|   ├── src/
|   |   ├── routes/
|   |   |   ├── index.svelte
|   |   |   └── tuto.js
|   |   ├── app.html
|   |   ...
|   ├── svelte.config.js
|   ...

/src/routes/tuto.js

import rosaenlgPug from 'rosaenlg';

const phones = [{
  name: 'OnePlus 5T',
  colors: ['Black', 'Red', 'White'],
}, {
  name: 'OnePlus 5',
  colors: ['Gold', 'Gray'],
}, {
  name: 'OnePlus 3T',
  colors: ['Black', 'Gold', 'Gray'],
}];

const template = `
mixin colors
  | the phone's available colors are
  eachz color in phone.colors with { separator:',', last_separator:'and', end:'.' }
    | #{color}

- let phone;
each phoneElt in phones
  - phone = phoneElt;
  p #{phone.name} . #[+colors]
`;

// As an endpoint
export async function get() {
  const res = rosaenlgPug.render(template, {
    language: 'en_US',
    phones: phones
  });
  return { body: { res }};
};

/src/routes/index.svelte

<script context='module'>
  // Fetch in load for client side usage
  export const load = async ({ fetch }) => {
    const data = await fetch('/tuto').then(r => r.json())
    const { res } = data
    return { props: { res }}
  }
</script>

<script>
  export let res
</script>


<p>{@html res}</p>

/svelte.config.js

/** @type {import('@sveltejs/kit').Config} */
const config = {
    kit: {
        // hydrate the <div id="svelte"> element in src/app.html
        target: '#svelte',
        vite: {
            optimizeDeps: {
                include: ['rosaenlg']
            }
        }
    }
};

export default config;

Upvotes: 2

Related Questions