Skip to content
Advertisement

require is not defined in Firebase?

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:

<html>   
<body>
<h1>Hello World</h1>
</body>
<script type="text/javascript" src="./js/test.js"></script>
</html>

JS Code:

var Firebase = require('firebase');
var dataRef = new Firebase('firebase url');
console.log("Firebase : "+Firebase+" -- dataRef :: "+dataRef)
dataRef.set("Firebase Require");

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

module.exports = {
  entry: './index.js',
  output: {
    filename: 'bundle.js'
  }
}

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:

import Firebase from 'firebase';
var dataRef = new Firebase('firebase url');
console.log("Firebase : "+Firebase+" -- dataRef :: "+dataRef)
dataRef.set("Firebase Require");

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

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement