Angular 9 and SSR - window is not defined - node.js

I am using Angular 9 and SSR and I am getting the error on one of the packages.
const DragEvevent = window.DragEvent
ReferenceError: window is not defined
On the ngx-chips package
We already tried adding to the nodeJs the variables:
const domino = require('domino');
const fs = require('fs');
const template = fs.readFileSync(join(join(process.cwd(), 'dist/emaua-front/browser'), 'index.html')).toString();
console.log(template);
const win = domino.createWindow(template);
// mock
global['window'] = win;
global['document'] = win.document;
global['DOMTokenList'] = win.DOMTokenList;
global['Node'] = win.Node;
global['Text'] = win.Text;
global['HTMLElement'] = win.HTMLElement;
global['navigator'] = win.navigator;
But still the error persists.
Update
After updating all packages I got the error:
ERROR in multi ./src/assets/css/ripple.min.scss ./src/assets/css/lounge.scss ./src/assets/css/discovery.scss ./src/assets/css/main.scss ./src/styles.scss ./node_modules/roboto-fontface/css/roboto/roboto-fontface.css ./node_modules/material-design-icons/iconfont/material-icons.css ./node_modules/bootstrap/dist/css/bootstrap.min.css ./node_modules/bootstrap/dist/css/bootstrap-theme.min.css ./node_modules/ng-bootstrap-to-bootstrap-3/dist/ng-bootstrap-to-bootstrap-3.min.css ./node_modules/jquery-ui-dist/jquery-ui.min.css ./node_modules/jquery-ui-dist/jquery-ui.theme.min.css ./node_modules/ag-grid-community/dist/styles/ag-grid.css ./node_modules/ag-grid-community/dist/styles/ag-theme-balham.css ./node_modules/slick-carousel/slick/slick.scss ./node_modules/slick-carousel/slick/slick-theme.scss ./src/assets/css/animate.css ./node_modules/cookieconsent/build/cookieconsent.min.css
Module not found: Error: Can't resolve '/Users/vinh/learning/front-end/node_modules/bootstrap/dist/css/bootstrap-theme.min.css' in '/Users/vinh/learning/front-end'
this.debug is not a function
After that I applied the fix as said in here
And again I am getting the same error like:
const DragEvent = window.DragEvent;
^
ReferenceError: window is not defined
On the ngx-chips package
UPDATE
The problems we have in ngx-chips is something that was happening before.
https://github.com/Gbuomprisco/ngx-chips/issues/740
https://github.com/Gbuomprisco/ngx-chips/issues/786
Does anyone knows a way of overcoming this problem?

I upgraded to Angular 10 and I had the same problem with ngx-chips on the server.
I solved this problem as follows:
I, probably like many, do not really need this component when rendering on the server.
Too lazy to create a separate project to exclude this module.
So I just disabled this component.
In template:
<div *ngIf="isBrowser()">
<tag-input [(ngModel)]=...
</tag-input>
</div>
In typescript:
isBrowser() {
if (window) {
return true;
}
return false;
}

Related

Node unable to find local module

I was testing a very simple module to see if it works and keep on getting an error stating that node cannot find my module.
//mymodule.js
greeting = 'hello'
module.exports = greeting;
// main.js
const s = require('exportsPractice\mymodule.js');
console.log(s);
The error I get is shown here
Try using:
const s = require('./exportsPractice/mymodule.js');
And make sure the path is correct.

What does require('..') mean?

I am new to node.js and have been trying to test some code using yarn. At the moment I am using the following code:
const assert = require('assert')
const username = process.env.HDFS_USERNAME || 'webuser'
const endpoint1 = process.env.HDFS_NAMENODE_1 || 'namenode1.lan'
const endpoint2 = process.env.HDFS_NAMENODE_2 || 'namenode2.lan'
const homeDir = `/user/${username}`
const basePath = process.env.HDFS_BASE_PATH || homeDir
const nodeOneBase = `http://${endpoint1}:9870`
const nodeTwoBase = `http://${endpoint2}:9870`
const webhdfs = require('..')
const should = require('should')
const nock = require('nock')
describe('WebHDFSClient', function () {
const oneNodeClient = new (require('..')).WebHDFSClient({
namenode_host: endpoint1
});
})
that I've got from this repo:
https://github.com/ryancole/node-webhdfs/blob/master/test/webhdfs.js
and when I try to run yarn test I get the following error:
Cannot find module '..'
Require stack:
- myrepo/test/lib/hdfs.js
- myrepo/test/tests.js
- myrepo/node_modules/mocha/lib/mocha.js
- myrepo/node_modules/mocha/index.js
- myrepo/node_modules/mocha/bin/_mocha
Error: Cannot find module '..'
As you can see, require('..') is used couple of times in the code and I can not figure out what it means. I've found posts on require('../') which I think is not exactly the same as this one.
The inbuilt node.js require function uses a quite complex package resolution algorithm. So there are lots of things that may influence it.
A. Defaulting to index.js
node.js implicitly requires a file named index.js if no file name is specified.
So require("..") translates to require("../index.js")
B. The main package property.
If you require is inside a module and points to the root of the module it will read the main property from the packages package.json and require the file specified there.
So given this package definition (package.json)
{
"main": "./fileA.js"
}
The call to require("..") will be translated to require("../fileA.js")
Resources
Good explanatory blog entry
Official Docs

Emailjs - Mime Builder

I'm facing an issue with emailjs-mime-builder
Code
var MimeBuilder = require('emailjs-mime-builder')
var rootNode = new MimeBuilder("multipart/mixed"),
childNodeTxt = rootNode.createChild("text/plain").setContent("Text");
childNodeHtml = rootNode.createChild("text/html").setContent("<h1>HTML</h1>");
rootNode.build()
Error
MimeBuilder is not a constructor
The emailjs-mime-builder package is an ES6 Module. Meaning that if you can't use import like for example within a node.js enviornment, you have to require it like this instead:
const { default: MimeBuilder } = require( 'emailjs-mime-builder' );

jspdf module crashing every time with ReferenceError: window is not defined

I am working on a small project that works with generating pdf's in node and express, and been trying to use the jspdf npm module but somehow whenever I install that package and require it its crashing my sever. Here in how I am requiring in my server.js file:
var jsPDF = require('jspdf')
And this is the response that it is giving me when l try to run my server:
(window.AcroForm=function(t){var n=window.AcroForm;n.scale=function(t) {return t*(r.internal.scaleFactor/1)},n.antiScale=function(t){return 1/r.internal.scaleFactor*t};var r={fields:[],xForms:[],acroFormDictionaryRoot:null,printedOut:!1,internal:null};e.API.acroformPlugin=r;var i=function(){for(var t in this.acroformPlugin.acroFormDictionaryRoot.Fields){var e=this.acroformPlugin.acroFormDictionaryRoot.Fields[t];e.hasAnnotation&&a.call(this,e)}},o=function(){if(this.acroformPlugin.acroFormDictionaryRoot)throw new Error("Exception while creating AcroformDictionary");this.acroformPlugin.acroFormDictionaryRoot=new n.AcroFormDictionary,this.acroformPlugin.internal=this.internal,this.acroformPlugin.acroFormDictionaryRoot._eventID=this.internal.events.subscribe("postPutResources",l),this.internal.events.subscribe("buildDocument",i),this.internal.events.subscribe("putCatalog",c),this.internal.events.subscribe("pos
ReferenceError: window is not defined
The jsPDF library is for the client side (web browser) which is why it's expecting a window variable to be present. Luckily someone has already answered how to make this work server side here. Taken from that answer:
global.window = {document: {createElementNS: () => {return {}} }};
global.navigator = {};
global.btoa = () => {};
var fs = require('fs');
var jsPDF = require('jspdf');
var doc = new jsPDF();
doc.text("Hello", 10, 10);
var data = doc.output();
fs.writeFileSync('./document.pdf', data);
delete global.window;
delete global.navigator;
delete global.btoa;

Weird RequireJS Uncaught ReferenceError

this is very weird to me when I hit this error
Uncaught ReferenceError: css is not defined
and here is the code
define(function (require) {
"use strict";
var $ = require("jquery")
_ = require("underscore"),
Backbone = require("backbone"),
Marionette = require("backbone.marionette"),
css = require("css!style/toggle-switch"),
tpl = require("text!tpl/ViewPlan/listOut_instrument.html");
return Marionette.ItemView.extend({
});
});
what is wrong with my approach?
RequireJS intentionally doesn't support loading style-sheets since a number of mainstream browsers don't notify when a style sheet is loaded. See this.
You can however roll your own (as found in the link above):
function loadCss(url) {
var link = document.createElement("link");
link.type = "text/css";
link.rel = "stylesheet";
link.href = url;
document.getElementsByTagName("head")[0].appendChild(link);
}

Resources