I am trying to run a html file in Firebase staging environment. I have used Firebase npm package in the js code. But while running in the browser it throws error “require is not defined”.
HTML Code:
JavaScript
x
7
1
<html>
2
<body>
3
<h1>Hello World</h1>
4
</body>
5
<script type="text/javascript" src="./js/test.js"></script>
6
</html>
7
JS Code:
JavaScript
1
5
1
var Firebase = require('firebase');
2
var dataRef = new Firebase('firebase url');
3
console.log("Firebase : "+Firebase+" -- dataRef :: "+dataRef)
4
dataRef.set("Firebase Require");
5
Please suggest me some solution.
Advertisement
Answer
You need to setup a tool (such as webpack) to manage your dependencies. In this way you will be able to require
(or import
es6 sintax) libraries directly in your .js
files.
A possible setup could be the following:
in webpack.config.js
JavaScript
1
7
1
module.exports = {
2
entry: './index.js',
3
output: {
4
filename: 'bundle.js'
5
}
6
}
7
To tell webpack which is the entry
file of your app and let it build the bundle
for you.
Then in index.js
you can use:
JavaScript
1
5
1
import Firebase from 'firebase';
2
var dataRef = new Firebase('firebase url');
3
console.log("Firebase : "+Firebase+" -- dataRef :: "+dataRef)
4
dataRef.set("Firebase Require");
5
Refer to https://webpack.js.org/configuration/ for a more complete guide.
p.s. that will be valid for every node dependecies with frontend support