WebStormer
WebStormer

Reputation: 256

What it means "require is not defined" in JS and how the libraries are available for the browser?

I installed through npm in WebStorm this library

npm install basicscroll

The IDE highlights the words of the package, and everything seems fine until I try to see the project in the browser:

The console gives me this issue:

applicative.js:15 Uncaught ReferenceError: basicScroll is not defined
    at applicative.js:15
    at NodeList.forEach (<anonymous>)
    at applicative.js:6

So I added at the beginning of my JS file this statement:

const basicScroll = require('basicscroll')

The result this time is that the library remains highlighted, but the method called on it not. And in browser this is the error prompt by the console:

Uncaught ReferenceError: require is not defined

I checked my node_modules directory, I can see the sub-directory, so I think the installation process went right. I also checked the package.json file:

"dependencies": {
    "basicscroll": "^3.0.2",
    [...]

I honestly don't know where the problem is. I'm new to web development and online I found that the webpack module-bounder could help me, but I don't even know where to start. What is wrong ? Thank'you !

Upvotes: 0

Views: 1485

Answers (1)

Chris Hughes
Chris Hughes

Reputation: 342

It seems like you are trying to use server-side code in a client-side environment. As far as I know require is a NodeJS thing and doesn't exist in the browser.

Your easiest solution would be to use a <script> tag in your html to import the files you need. Something like <script src="dist/basicScroll.min.js"></script>

This answer mentions some other tools you could use to manage that sort of thing: https://stackoverflow.com/a/19059825/1801137

Upvotes: 3

Related Questions