简体   繁体   中英

How to fix example javascript code; error: ReferenceError: require is not defined?

I am trying to run some example code linked here , but upon start I get this error:

ReferenceError: require is not defined

I know, require.js is some package for javascript, but it is not mentioned anywhere on the example page? It says just to throw in the javascript code in nsome html skeleton and it should work! Is there a way to fix the code so it does not that extra package?

I also downloaded require.js myself from somewere, put it in the same directory, included it in the html, and got an error

Error: Module name "colormap" has not been loaded yet for context: _. Use require([])
http://requirejs.org/docs/errors.html#notloaded

in require.js !

The code you linked is written for NodeJS

But as the readme suggests you can get it to run if you package it using browserify ( https://github.com/substack/node-browserify )

Assuming you have NodeJS installed, you need to install browserify globally using NPM (Node Package Manager that comes with NodeJS)

Open a console and run npm install -g browserify - This will add the browserify command to your console.

Next up we need to create our on Node Package

  1. Make a new directory
  2. cd into that directory and run npm init - this will start a guide that will ask you to fill in some information about your package and creates a package.json file
  3. run npm install --save bpostlethwaite/colormap this will install the colormap library you are interested in
  4. Create an index.js file (assuming you left that unchanged when you run npm init)
  5. Paste the example code from the read me in index.js
  6. Finally run browserify -s index.js > bundle.js - This will generate a bundle.js file that can run in a browser

Hope that helps

To solve the last issue that you get Use require([]) you must to define like this:

 require(['colormap'], function() {
     // colormap is now loaded
 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM