svelte: require is undefined: how do you setup?

Hi, new to svelte, trying to switch to svelte, but I’ve got this big barrier, the elephant in the room that is not explained very clearly for beginners in the tutorials: how do you build a svelte component that uses an npm package?

So far, I’ve followed this guide: https://svelte.dev/blog/svelte-for-new-developers, and from there I could make my first rollup config:

import svelte from 'rollup-plugin-svelte';
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import livereload from 'rollup-plugin-livereload';
import { terser } from 'rollup-plugin-terser';
import { sass } from 'svelte-preprocess-sass';
import copy from 'rollup-plugin-copy'




const production = !process.env.ROLLUP_WATCH;

export default {
	input: 'src/main.js',
	output: {
		sourcemap: true,
		format: 'iife',
		name: 'app',
		file: 'public/build/bundle.js'
	},
	plugins: [
		svelte({
			// 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: css => {
				css.write('public/build/bundle.css');
			},
			preprocess: {
				style: sass(),
			},
		}),

		// 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']
		}),
		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(),
		copy({
			targets: [
				{
					src: 'src/assets/*',
					dest: 'public/build/assets',
					flatten: true,

				},
			]
		}),
	],
	watch: {
		clearScreen: false
	}
};

function serve() {
	let started = false;

	return {
		writeBundle() {
			if (!started) {
				started = true;

				require('child_process').spawn('npm', ['run', 'start', '--', '--dev'], {
					stdio: ['ignore', 'inherit', 'inherit'],
					shell: true
				});
			}
		}
	};
}

That’s nice, but now if in one of my svelte file I try to add a line like this:

const myvar = require("some-npm-package");

I’ve got this js error (in the browser):

ReferenceError: require is not defined

So my question is: how do you configure rollup to make the npm dependencies (in my svelte files) be bundled?

To me it’s a fundamental topic (as if I can’t configure svelte easily, I probably won’t use svelte at all). Therefore I believe this question should be answered somewhere obvious in the svelte documentation (tutorial, FAQ).

I mean this guide was a good initiative: https://svelte.dev/blog/svelte-for-new-developers, and should be more visible/accessible for svelte newcomers.

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Comments: 17

Most upvoted comments

Did you guys find a solution? Some libraries (like axios for example) need the require function to work.

Agreed, I made the same mistake. You should use import/export instead of require. commonjs plugin is just there to transform CommonJS modules.

@dnna2610 @lingtalfi I’m having a similar issue working with this package:

https://github.com/tomassedovic/etherpad-lite-client-js

Here’s a set-up example:

api = require('etherpad-lite-client')
etherpad = api.connect({
  apikey: 'UcCGa6fPpkLflvPVBysOKs9eeuWV08Ul',
  host: 'localhost',
  port: 9001,
})

etherpad.createGroup(function(error, data) {
  if(error) console.error('Error creating group: ' + error.message)
  else console.log('New group created: ' + data.groupID)
})

So it instructs to include api = require('etherpad-lite-client')at the top of the file. When I include that at the top of a .js file in my Svelte app, I’m getting this error:

Uncaught ReferenceError: require is not defined

I tried troubleshooting with import * as api from 'etherpad-lite-client'

And that gets me this error:

Uncaught ReferenceError: require$$0$1 is not defined

Any thoughts on other possible fixes?

Why is this closed? I’m having this issue with external libraries that need require

I see. Moduls should be resolved automatically, so there’s no need for the path to node_modules to be included. This should work if you import it like this import * as jsx from 'js-extension-ling'.

any solutions yet? I’m getting the same error when using objection.js in an endpoint.

I had a similar problem but using vite. The fix in my case was to add “global” the following into the vite.config.js file as follows:


export default defineConfig({

  define: {

    "global": {},   /* define this entry here */

  },

  plugins: [svelte()],

  css: {

    postcss,

  },

});



I presume it would be similar if you are using rollup?

What I did is use node’s createRequire method which can be found in the docs! https://nodejs.org/api/module.html#modulecreaterequirefilename