javascript-how to solve 'ReferenceError: Cant find variable: require when import a javascript library using require within HTML?
1. Purpose
In this post , I would demo how to solve the below problem when trying to import a javascript library using require
within HTML:
ReferenceError: Can't find variable: require
2. The code that caused the error
We want to display current date and time in our page, so I imported a library named moment.js, which is a javascript library for date and time processing.
Moment. js is a free and open source JavaScript library that removes the need to use the native JavaScript Date object directly. The library is a wrapper for the Date object (in the same way that jQuery is a wrapper for JavaScript) making the object a whole lot easier to work with.
I installed the library using the npm install
as follows:
$ npm install moment
Then I created a html file to do the job, this is the code:
<html>
<head>
<title>Vue.js Message List</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
crossorigin="anonymous">
</head>
<body>
<script>
var moment = require("moment");
console.log(moment().format('HH:mm:ss DD/MM/YYYY');
</script>
</body>
</html>
When I test the above html in browser , I got this error in browser console:
ReferenceError: Can't find variable: require
3. Why I get this problem?
After googling a lot, I found that this problem is caused by the misunderstanding of the require
in javascript.
The require
is used in node.js module loading process, require()
, module.exports
and exports
are APIs of a module system that is specific to Node.js. Browsers do not implement this module system, so I got the above errors.
4. How to solve this problem?
4.1 Step 1: Remove the require
statement from your script
We should remove the require(moment)
statement in the script block, and then we can import the moment.js in such two ways.
4.2 Step 2 : Load js library from internet CDN using the
Here is the code that import the moment.js into our html file:
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ==" crossorigin="anonymous"></script>
Then use the moment.js as follows:
///var moment = require("moment"); //comment this line out
this.message = moment().format('HH:mm:ss DD/MM/YYYY');
console.log(this.message)
Then everything works~
5. Summary
In this post, I have demonstrated how to solve the “ReferenceError: Can’t find variable: require” error when trying to load javascript modules by using the require
statement, If we test the html in browser, not using node.js, you should use the