Unable to use bootstrap with Node(express) server because DOM is not loaded outside of browser

Viewed 38

I am trying to use bootstrap from npm, but bootstrap requires document from DOM. This is an issue because I want to use const bootstrap = require('bootstrap'); so that bootstrap is loaded globally, without adding a script tag or partial to each page.

I have tried installing jsdom to add a DOM to the page but that did not work. I also tried

if (typeof window !== 'undefined') {
  require('bootstrap')
} 

but that also did not help.

here is the app.js:

const express = require('express');
const path = require('path');
const bootstrap = require('bootstrap')

var app = express();
app.set('view engine','ejs');

app.use(express.static('static'));
app.use('/script',express.static('static/script'));
app.use('/assets',express.static('static/assets'));
app.use('/styles',express.static('static/styles'));

app.listen(3000);

app.get('/', (req, res) => {
res.render('index');
});

the error (using nodemon):

ReferenceError: document is not defined
    at enableDismissTrigger (C:\path\node_modules\bootstrap\dist\js\bootstrap.js:888:21)
    at C:\path\node_modules\bootstrap\dist\js\bootstrap.js:977:3
    at C:\path\node_modules\bootstrap\dist\js\bootstrap.js:7:83
    at Object.<anonymous> (C:\path\node_modules\bootstrap\dist\js\bootstrap.js:10:3)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
[nodemon] app crashed - waiting for file changes before starting...
0 Answers
Related