Search code examples
javascriptnode.jsscrollreveal.js

scrollreveal ReferenceError: document is not defined after requiring const ScrollReveal = require("scrollreveal");


I am trying to use the scrollreveal javascript. Installed it via npm and use it in my NodeJS code (see below). Also, I'm including it in my HTML as well.

Now when I run nodemon app.js in hyper terminal I get this error:

C:\Users\Admin\Desktop\My Projects\test\node_modules\scrollreveal\dist\scrollreveal.js:33 container: document.documentElement, ^

ReferenceError: document is not defined

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <h1>Hello</h1>
    <script src="https://unpkg.com/[email protected]/dist/scrollreveal.min.js"></script>
  </body>
</html>

app.js

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const ScrollReveal = require('scrollreveal');

app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public'));

app.get('/', function (req, res) {
  res.sendFile(__dirname + '/index.html');
});

app.listen(3000, function () {
  console.log('server start on port 3000');
});


Solution

  • I think you misunderstood the way to use dependencies

    First, NodeJS and the JavaScript that runs in the browser are completely different.

    The problem you're facing here is that you're including a package that only works in the browser environment in NodeJS file. And since NodeJS doesn't have the concept of "document", therefore the error.

    To fix this, you can simply remove the require statement from your NodeJS and just use "scrollreveal" in your HTML file. And since you're using a CDN link in your HTML, you don't need to install the dependency via npm. (You can use npm to manage your dependencies but that would require a modern Frontend setup, I would recommend you start with something like: Modern JavaScript Explained For Dinosaurs