NPM - Require Is Not Defined

#1

Good evening.

I’m trying to install a npm package but when I run the file, I am getting an error in my console, “require is not defined”. Which makes sense as require isn’t a JS function as far as I know.

However the instructions at https://www.npmjs.com/package/poker-hands tell me to add the following, which I do to my index file:

var poker = require('poker-hands');

<html ng-app="app">
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
  <script src="script.js"></script>
	<script>var poker = require('poker-hands');</script>
</head>
<body>
  <div ng-controller='HelloController'>
    <p>{{greeting.text}}, World</p>
  </div>
</body>
</html>

What am I doing wrong? My npm experience is limited as I rarely start new projects yet I cannot find anything on the internet to work out what I’m doing wrong.

Thanks
James

#2

You can’t use Node modules in the browser in this way. You’d need to convert them with a tool such as Browserify.

In your case, this is what it’d look like:

  • Install Node and npm on your machine. If you haven’t done this already use nvm. Tutorial here.
  • Install Browserify globally: npm i -g browserify
  • Create a folder named poker: mkdir poker
  • Change into that folder: cd poker
  • Create a package.json file: npm init -y
  • Install poker-hands: npm install poker-hands
  • Create an index.html and a poker.js file.

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Poker, innit?</title>
  </head>
  <body>

    <script src="index.js"></script>
  </body>
</html>

poker.js

const poker = require('poker-hands');
const res = poker.judgeWinner(['5H 5C 6S 7S KD', '2C 3S 8S 8D TD']);
console.log(res);
  • Run browserify: browserify poker.js -o index.js
  • Open index.html in the browser and observe the correct result output to the console.

Here’s a good tutorial for further learning:

1 Like
#3

Thanks for this. All is working now and my knowledge is expanded :slight_smile:

closed #4

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.