I try to learn Node.js (ES6) but fail on require
This is my structure:
baseModel.js
"use strict";
class BaseModel {
constructor(options = {}, data = []) { // class constructor
this.name = 'Base'
this.url = 'http://azat.co/api'
this.data = data
this.options = options
}
getName() { // class method
console.log(`Class name: ${this.name}`)
}
}
AccountModel.js
"use strict";
require('./baseModel.js');
class AccountModel extends BaseModel {
constructor(options, data) {
super({private: true}, ['32113123123', '524214691']) //call the parent method with super
this.name += 'Account Model'
this.url +='/accounts/'
}
get accountsData() { //calculated attribute getter
// ... make XHR
return this.data
}
}
main.js
"use strict";
require('./AccountModel.js');
let accounts = new AccountModel(5)
accounts.getName()
console.log('Data is %s', accounts.accountsData);
Now I run: node --harmony-default-parameters main.js
and get error:
ReferenceError: BaseModel is not defined
at Object. (/Users/tamirscherzer/POC/projects/NodeJS/tutorials/classes/AccountModel.js:5:28)
at Module._compile (module.js:397:26)
at Object.Module._extensions..js (module.js:404:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Module.require (module.js:353:17)
at require (internal/module.js:12:17)
at Object. (/Users/tamirscherzer/POC/projects/NodeJS/tutorials/classes/main.js:5:1)
at Module._compile (module.js:397:26)
at Object.Module._extensions..js (module.js:404:10)
Really strange, if I change require('./baseModel.js'); to other name, I get error that file not found so the path is written properly.
Also defined permissions 777 - same thing, BaseModel is not defined
Any Ideas?
When you define a variable in Node, it isn't added to the global scope like it would be in a browser - it's local to that one file/module. Therefore, you can't simply import a file and expect the things you defined inside it to be available - you explicitly have to export and import them.
BaseModel.js:
class BaseModel {
constructor(options = {}, data = []) { // class constructor
this.name = 'Base'
this.url = 'http://azat.co/api'
this.data = data
this.options = options
}
getName() { // class method
console.log(`Class name: ${this.name}`)
}
}
module.exports = BaseModel;
AccountModel.js:
"use strict";
let BaseModel = require('./baseModel.js');
class AccountModel extends BaseModel {
constructor(options, data) {
super({private: true}, ['32113123123', '524214691']) //call the parent method with super
this.name += 'Account Model'
this.url +='/accounts/'
}
get accountsData() { //calculated attribute getter
// ... make XHR
return this.data
}
}
module.exports = AccountModel;
main.js:
"use strict";
let AccountModel = require('./AccountModel.js');
let accounts = new AccountModel(5)
accounts.getName()
console.log('Data is %s', accounts.accountsData);
Related
I am trying to not make connection between world/customworld and step definitions to keep it neutral.
My Hooks
import { Before, setWorldConstructor } from '#cucumber/cucumber';
setWorldConstructor(CustomWorld);
Before(async function (scenario) {
this.init(scenario);
});
Custom World
import { World } from '#cucumber/cucumber';
import { Builder } from 'selenium-webdriver';
export default class extends World {
public driver = null;
constructor(options: any) {
super(options);
}
async init(scenario: any) {
const thisScenario = scenario;
this.driver = await new Builder().forBrowser('chrome').build();
}
}
Browser/chromedriver
import customWorld from './CustomWorld';
export default class driver_functions extends customWorld {
constructor(options: any) {
super(options);
}
async aa() {
await this.driver.navigate().to('https://google.com').then((value) => {console.log(value);});
}
}
I am getting errors like undefined when I call from step
import driver_functions from '../../utils/driver_functions';
import { Given } from '#cucumber/cucumber';
const df = new driver_functions();
Given('Home_Page: I have a simple maths calculator', async function () {
await driver_functions.aa();
});
at /Users/user.current/Projects/JS_Test/cucumber6-ts-starter-master/node_modules/#cucumber/cucumber/src/runtime/parallel/run_worker.ts:22:9
at processTicksAndRejections (node:internal/process/task_queues:96:5)
caused by: TypeError: Cannot destructure property 'attach' of 'undefined' as it is undefined.
at new World (/Users/user.current/Projects/JS_Test/cucumber6-ts-starter-master/node_modules/#cucumber/cucumber/src/support_code_library_builder/world.ts:21:17)
at new default_1 (/Users/user.current/Projects/JS_Test/cucumber6-ts-starter-master/src/utils/CustomWorld.ts:30:5)
at new driver_functions (/Users/user.current/Projects/JS_Test/cucumber6-ts-starter-master/src/utils/driver_functions.ts:36:5)
at Object.<anonymous> (/Users/user.current/Projects/JS_Test/cucumber6-ts-starter-master/src/step_definitions/maths/simple-maths-steps.ts:6:12)
at Module._compile (node:internal/modules/cjs/loader:1097:14)
at Module.m._compile (/Users/user.current/Projects/JS_Test/cucumber6-ts-starter-master/node_modules/ts-node/src/index.ts:1459:23)
I am trying to use #nguniversal/express-engine and I have installed and trying to run it but its giving error in main.js file.
This is the error I am getting
C:\Folder\ssr\dist\ssr\server\main.js:179450
})(window, function() {
^
ReferenceError: window is not defined
at Object.rdXg (C:\Folder\ssr\dist\ssr\server\main.js:179450:4)
at __webpack_require__ (C:\Folder\ssr\dist\ssr\server\main.js:26:30)
at Module.+PDj (C:\Folder\ssr\dist\ssr\server\main.js:133:66)
at __webpack_require__ (C:\Folder\ssr\dist\ssr\server\main.js:26:30)
at Module.xCqK (C:\Folder\ssr\dist\ssr\server\main.js:198481:92)
at __webpack_require__ (C:\Folder\ssr\dist\ssr\server\main.js:26:30)
at Module.xLoe (C:\Folder\ssr\dist\ssr\server\main.js:200042:86)
at __webpack_require__ (C:\Folder\ssr\dist\ssr\server\main.js:26:30)
at Module.Mm/0 (C:\Folder\ssr\dist\ssr\server\main.js:89135:105)
at __webpack_require__ (C:\Folder\ssr\dist\ssr\server\main.js:26:30)
A server error has occurred.
node exited with 1 code.
connect ECONNREFUSED 127.0.0.1:59195
I have tried many thing but nothing working.
print function causing the issue and the print function is been used by print-js library
const contentToConvert = document.getElementById('content');
this.selectedFunctionCode = htmlToImage.toPng;
const debugBase64 = this.debugBase64;
this.selectedFunctionCode(contentToConvert)
.then((dataUrl) => {
print(dataUrl, 'image');
})
.catch((error) => {
console.error('oops, something went wrong!', error);
});
because some object like localstorage, window use in client side are not defined in server side you must first check your browser platform is ready then work with these objectes
for this you can do like:
at first generate check-is-browserService.service.ts like this:
export class CheckIsBrowserService {
private isBrowser = new BehaviorSubject<boolean>(null);
constructor() {}
getIsBrowser(): Observable<any> {
return this.isBrowser;
}
setIsBrowser(value: any) {
this.isBrowser.next(value);
}
}
app.component.ts
constructor(
#Inject(PLATFORM_ID) private platformId: any,
private checkIsBrowserService: CheckIsBrowserService
){
this.checkIsBrowserService.setIsBrowser(isPlatformBrowser(platformId));
}
then generate service for example window.service.ts
class Window implements Window {
readonly innerWidth: number;
}
#Injectable({
providedIn: 'root',
})
export class WindowService {
private config: Window;
constructor(private checkIsBrowserService: CheckIsBrowserService) {
this.config = new Window();
this.checkIsBrowserService.getIsBrowser().subscribe((isBrowser) => {
if (isBrowser) {
this.config = window;
}
});
}
innerWidth() {
return this.config.innerWidth;
}
}
and when in your component use window.innerwidth you must change it to
x.component.ts:
constructor(private window: WindowService) {
if (this.window.innerWidth() <= 1024) {
//your code
}
}
I want to test a js file where it has a reference of a const coming from another import (parser.js)
const { cp } = CML
How can I mock this and only this and not the rest of functions?. It is throwing this error:
ReferenceError: CML is not defined
at Object.<anonymous> (src/state/lib/parser.js:2:16)
at Object.<anonymous> (src/state/reducers/stateReducer.js:2:1)
at Object.<anonymous> (src/state/reducers/index.js:4:1)
at Object.<anonymous> (src/state/store/index.js:4:1)
at Object.<anonymous> (src/state/store/store.spec.js:4:1)
CML is a var defined in other js resource file.
This is the parser.js file:
/* global CML */
const { cp } = CML;
// Massaging approvals array data
// Adding status and trimming unused values
export default {
approvals: (approvals = [], globalActions = []) => (
approvals.map(approval => {
let status = 'default';
let rejected = false;
let reviewed = 0;
...
And in stateReducer class this is the import of the parser:
import parser from '../lib/parser';
jest.mock('./state/lib/parser', function() { // Put the exact path you've imported in your file
return {
CML: 123,
};
});
I am trying to use a grunt rollup plugin, grunt-rollup, to compile two es6 files into Javascript that can be run from node and eventually the browser. Currently, it compiles, but rollup seems to be creating an undefined variable from one of my class names. Here is my current configuration.
Imported ES6 File (src/base.js):
class Base{
constructor() {
return this;
}
}
export default Test;
Rollup Entrypoint ES6 File (src/test.js):
import Base from "./base";
class Test extends Base{
constructor() {
super();
return this;
}
}
export default Test;
Gruntfile.js
module.exports = function(grunt) {
var babel = require('rollup-plugin-babel');
var resolve = require('rollup-plugin-node-resolve');
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
rollup: {
options: {
sourceMap: true,
format: 'cjs',
plugins: function () {
return [
resolve({
// pass custom options to the resolve plugin
customResolveOptions: {
moduleDirectory: 'node_modules'
}
}),
babel({
exclude: './node_modules/**',
presets: ['es2015-rollup']
}),
];
},
},
main: {
dest: 'dest/bundle.js',
src: 'src/test.js'
}
},
uglify: {
main: {
options: {
sourceMap: true,
sourceMapName: 'dest/bundle.min.js.map'
},
files: {
'dest/bundle.min.js': ['dest/bundle.js']
}
}
}
});
grunt.loadNpmTasks('grunt-rollup');
grunt.loadNpmTasks('grunt-contrib-uglify');
// Default task(s).
grunt.registerTask('default', ['rollup', 'uglify']);
};
Output file (dest/bundle.js)
'use strict';
var classCallCheck = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
var inherits = function (subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
};
var possibleConstructorReturn = function (self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return call && (typeof call === "object" || typeof call === "function") ? call : self;
};
var Test$1 = function (_Base) {
inherits(Test$$1, _Base);
function Test$$1() {
var _ret;
classCallCheck(this, Test$$1);
var _this = possibleConstructorReturn(this, (Test$$1.__proto__ || Object.getPrototypeOf(Test$$1)).call(this));
return _ret = _this, possibleConstructorReturn(_this, _ret);
}
return Test$$1;
}(Test);
module.exports = Test$1;
//# sourceMappingURL=bundle.js.map
Terminal output
Output after running node dest/bundle.js.
/Users/christianjuth/Desktop/mb-problems/dest/bundle.js:67
}(Test);
^
ReferenceError: Test is not defined
at Object.<anonymous> (/Users/christianjuth/Desktop/mb-problems/dest/bundle.js:67:3)
at Module._compile (module.js:569:30)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:503:32)
at tryModuleLoad (module.js:466:12)
at Function.Module._load (module.js:458:3)
at Function.Module.runMain (module.js:605:10)
at startup (bootstrap_node.js:158:16)
at bootstrap_node.js:575:3
The problem seems to be with the very end of bundle.js where }(Test); is looking for an undefined variable. As far as I can tell this is not a bug with my code. It seems to be an issue with how rollup is compiling the ES6.
That's because you have an undefined variable in your code. Take a second look at base.js:
class Base{
constructor() {
return this;
}
}
export default Test;
...where have you defined Test? Did you mean export default Base?
I have the following files: gist
The index.js attempts instantiate a base "Auth" class but in it's constructor the auth class acts as an object factory and passes back a subclass of Auth instead.
'use strict';
import Auth from './Auth';
let o = new Auth({type:'Oauth1'});
console.log(o);
o.getToken();
The Auth.js class definition is as follows:
'use strict';
import Oauth1 from './Oauth1';
export default class Auth {
constructor(config) {
if (this instanceof Auth) {
return new Oauth1(config);
} else {
this.config = config;
}
}
getToken() {
console.log('Error: the getToken module must be implemented in the subclass');
}
}
And the Oauth1.js class definition is:
'use strict';
import Auth from './Auth';
export default class Oauth1 extends Auth {
getToken() {
console.log('Auth: ', Auth);
}
}
When running with babel-node index.js I get the following error:
TypeError: Super expression must either be null or a function, not undefined
at _inherits (/repos/mine/test-app/Oauth1.js:1:14)
at /repos/mine/test-app/Oauth1.js:4:28
at Object.<anonymous> (/repos/mine/test-app/Oauth1.js:4:28)
at Module._compile (module.js:434:26)
at normalLoader (/usr/local/lib/node_modules/babel/node_modules/babel-core/lib/api/register/node.js:199:5)
at Object.require.extensions.(anonymous function) [as .js] (/usr/local/lib/node_modules/babel/node_modules/babel-core/lib/api/register/node.js:216:7)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Module.require (module.js:365:17)
at require (module.js:384:17)
If I remove the extends expression from the Oauth1 class it executes but then I am not getting the inheritance I want.
Your issue has nothing to do with babel. The real problem is that you have circular dependencies in your code.
To resolve this issue you should remove Oauth1 dependency from its parent Auth class:
'use strict';
export default class Auth {
constructor(config) {
this.config = config;
}
getToken() {
console.log('Error: the getToken module must be implemented in the subclass');
}
}
'use strict';
import Auth from './Auth';
export default class Oauth1 extends Auth {
getToken() {
console.log('Auth: ', Auth);
}
}
If you don't want to remove this instanceof Auth check from your base class, you could require your Oauth1 subclass in run-time instead of importing it during module initialization:
constructor(config) {
if (this instanceof Auth) {
let Oauth1 = require('./Oauth1');
return new Oauth1(config);
}
this.config = config;
}