问题
Edit : Problem solved using webpack
For the needs of an API, I needed to import MD5
and moment
. I downloaded the packages using the basic npm install
but when I try to import it on my app.js
using the code below :
const md5 = require ('./node_modules/md5/md5.js');
const moment = require ('./node_modules/moment/moment.js');
function getTimeStamp () {
return moment.utc ().format ('YYYYMMDDHHmmss');
}
let timestamp = getTimeStamp ();
function generateSignature (devId, method, authKey, timestamp) {
return md5 (`${devId}${method}${apiKey}${timestamp}`);
}
let signature = generateSignature (XXXX, "createsession", "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", getTimeStamp ());
I get this message in the console :
Uncaught ReferenceError: require is not defined
I don't know what I'm doing wrong because I used the same method for another program and it worked perfectly...
Thanks in advance
回答1:
You're probably seeing this error because require() does not exist in the browser/client-side JavaScript. If you want to use require() in the browser, then you need to use something like require.js
RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node.
PS: I agree with cptwonton. Please refer to the mentioned post for an in-depth solution with the various options available.
回答2:
try this:
const md5 = require ("md5");
const moment = require ("moment");
回答3:
require
isn't supported in a browser because Node and ES6 have their different module systems. Are you trying to call require
in a browser? In that case I suggest you to setup Babel. But if you use node, then try reistalling nodejs.
来源:https://stackoverflow.com/questions/54427002/node-require-is-not-defined