I am writing library using es6, transpiling it with babel via webpack and npm.
The problem is, that my lib is dependent on some code, that I can not change but need to use. I don't know how to load var stuff (from the following example) in my tests so that it is visible for the module.
See the example:
external-stuff.js - this one can not be changed and is loaded before my lib is loaded on prod env.
var stuff = {
get some() { return "some"; }
get stuff() { return "stuff"; }
}
some-module.js - this is one of the modules in the library
export class foo {
static get whatever() { return stuff.some; }
static get whichever() { return stuff.stuff; }
}
test
import {foo} from "../src/foo.js";
let assert = require('assert');
describe('foo', function() {
describe('#whatever()', function() {
it("should do some", function () {
assert.equals(foo.whatever(), "some");
});
});
});
If I run this I get "ReferenceError: stuff is not defined"
I already tried to define "stuff" in before() hook, but no success.
In the end I found a solution that's 'good enough'. I am not sure it would be sufficient for some advanced library though.
I have created file called globals.js
var g = typeof(window) === 'undefined' ? global : window;
// Dependencies - add as many global stuff as needed
g.stuff= typeof(stuff) === 'undefined' ? {} : stuff;
And I import this 'es6module' at the beginning of test
import * as globals from "../lib/global/globals"
import {foo} from "../src/foo.js";
And then I use node-import npm module with which I load the global to the tests in beforeEach hook.
beforeEach(function () {
global.stuff = imports.module("lib/global/stuff.js").stuff;
});
This is perfect for unit testing because I can also mock stuff. And its even more awesome because this way I have a place where I 'define' global dependencies. It would be nice to improve on it and make it per es6modul dependencies... and build on it something fancy... ya know.. dependency injection.
complete test
require('node-import'); // +
import * as globals from "../lib/global/globals"; // +
import {foo} from "../src/foo.js";
let assert = require('assert');
describe('foo', function() {
beforeEach(function () { // +
global.stuff = imports.module("lib/global/stuff.js").stuff; // +
}); // +
describe('#whatever()', function() {
it("should do some", function () {
assert.equals(foo.whatever(), "some");
});
});
});
Related
I have an old IIFE that is injected into legacy pages via <script src.
However, I want to use all these old libraries in a react app. I just need to use the global function exposed.
I figure loading dependencies that will work both via script or via react's import or nodejs require
Here is an example of an example IIFE
example.js :
var $ = $;
var geocomplete = $.fn.geocomplete;
var OtherExternalLib = OtherExternalLib;
var Example = (function() {
return {
init: function () {
// stuff
}
}
)();
Where the legacy code is calling Example.init(), and likewise the react code will call the same function.
Where $ (jQuery), $.fn.geocomplete, and OtherExternalLib are all dependencies that must be loaded, either they should be loaded on-demand or just throw a big loud error message.
I suspect if the solution loads dynamically example.js would look something like
var $ = load("\libs\jquery.js");
var geocomplete = load("\libs\$.fn.geocomplete.js");
var OtherExternalLib = load("\libs\OtherExternalLib.js");
var Example = (function() {
return {
init: function () {
// stuff
}
}
)();
And the legacy application can still use <script src=example.js and React can use
import {Example} from example
Understandably this is somewhat a round-about way to of using legacy code in new applications, so I am open to other ideas on how best to expose an IIFE (with or without dependencies) and using it in React
I am using react+typescript in my project with some limitations which is why I had to dynamically import my package (my project runs in a shell project with AMD module, not having my own startup, and change the way project files get bundled).
Since I could only use the dependent modules on the fly during the run time, I had to assume them were valid while building and bundling . Most of them were IIFE.
So I used the lazy dynamic import .
something like this
import("somePolyfill");
This would be translated by TSC
new Promise(function (resolve_3, reject_3) { require(["arrayPolyfill"], resolve_3, reject_3); });
This would call the IIFE and execute the polyfills or initializing any window or global variable, so the rest of the code is aware of that.
If it returns a module or throughs error can be handled like normal promise then and catch.
So I created a wrapper
export class DepWrap {
public static Module: any = {};
public constructor() {
this.getPI();
this.getSomeModule();
}
public async getPI() {
DepWrap.Module["PI"] = 3.14;
}
public async getSomeModule() {
await import('somepath/somemodule').then(($package) => {
DepWrap.Module["somemodule"] = $package;
}).catch(() => {
window.console.log("Some Module error");
});
}
}
this got compiled to
define(["require", "exports", "tslib"], function (require, exports, tslib_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var DepWrap = /** #class */ (function () {
function DepWrap() {
this.getPI();
this.getSomeModule();
}
DepWrap.prototype.getPI = function () {
return tslib_1.__awaiter(this, void 0, void 0, function () {
return tslib_1.__generator(this, function (_a) {
DepWrap.Module["PI"] = 3.14;
return [2 /*return*/];
});
});
};
DepWrap.prototype.getSomeModule = function () {
return tslib_1.__awaiter(this, void 0, void 0, function () {
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, new Promise(function (resolve_1, reject_1) { require(['somepath/somemodule'], resolve_1, reject_1); }).then(function ($package) {
DepWrap.Module["somemodule"] = $package;
}).catch(function () {
window.console.log("Some Module error");
})];
case 1:
_a.sent();
return [2 /*return*/];
}
});
});
};
DepWrap.Module = {};
return DepWrap;
}());
exports.DepWrap = DepWrap;
});
with this I could use all the dependency modules from my wrapper and every time i need to import a new one I would create another function to add that to my wrap module.
import { DepWrap } from "wrapper/path";
const obj = new DepWrap(); // initialize once in the beginning of project so it would import all the dependencies one by one .
Afterwards in all file, I can import my module from the wrapper
import { DepWrap } from "wrapper/path";
const { PI, somemodule} = DepWrap.Module;
I am not sure if the code will work for your scenario as well, but I guess tweaking it a bit might come in handy for your useCase .
Plus : if you are writing unit test case it will help jest to just ignore the modules and can create a mock for this so that you can test your actual code .
I am learning how to test Javascript code in Vanilla Javascript so I am following a tutorial. My project structure looks like this:
Modules/File.js,File2.js (each file contains a function I want to test)
app.js (a file for testing which works together with test.js file)
index.html
index.js (currently I keep my main code there)
test.html (I use it to run test, according to the tutorial)
test.js (this is where I describe tests)
I want to be able to import functions from File.js, and File2.js in app.js, so I can run tests. How do I achieve that?
P.S. I am using es6 modules import/export. But I would like to see how can I run imported functions for test. Maybe using $myapp global variable for it since thats how its done in the tutorial.
test.js:
(function () {
'use strict';
/**
* test function
* #param {string} desc
* #param {function} fn
*/
function it(desc, fn) {
try {
fn();
console.log('\x1b[32m%s\x1b[0m', '\u2714 ' + desc);
} catch (error) {
console.log('\n');
console.log('\x1b[31m%s\x1b[0m', '\u2718 ' + desc);
console.error(error);
}
}
function assert(isTrue) {
if (!isTrue) {
throw new Error()
}
}
it('test if its a string', function () {
assert($myapp.isValidString(2))
})
})();
app.js file:
(function () {
'use strict';
// Create a global variable and expose it to the world
var $myapp = {};
self.$myapp = $myapp;
$myapp.isValidString = function (value) {
return typeof value === 'string' || value instanceof String;
}
})();
From what I understand, you want to import JS functions from one file into another file.
ES6 introduced the module's functionality which allows the import/export of Javascript functions between different files.
Below is a simple example:
// helloworld.js
export function helloWorld() {
return 'Hello World!';
}
// main.js
import helloWorld from './helloworld.js';
console.log(helloWorld());
I have a worker.js file:
self.importScripts('/static/utils/utils.js')
onmessage = (e) => {
let a = e.data[0]
let b = e.data[1]
let c = func1(a,b)
postMessage(c)
}
The utils.js file looks something like this:
module.exports = {
func1: function(a,b){
return a+b
}
I keep getting error:
Uncaught ReferenceError: module is not defined
at utils.js:1
Obviously require, and import and any other server side imports aren't working but I'm not sure why it's having a problem with my importScripts - https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/importScripts
The correct solution is to pack your worker with webpack. If you don't want to do that, read below.
I usually write myself a polyfill for node require:
// This will not work in normal UI thread
// None of this should make it into production
function require(moduleName) {
self.module = { exports: null };
// Nasty sttuff right here, probably should throw error instead
if (moduleName == "fs")
return null;
// This part is especially unprofessional
if (!moduleName.endsWith(".js"))
moduleName += ".js";
importScripts(moduleName);
return self.module.exports;
}
This makes use of the fact that importScripts is synchronous. Note that this will still cause errors if you try to load native node modules (eg. fs) or if other module properties are used.
Try this utils.js:
(function () {
self.func1 = function (a, b) {
return a + b
}
}());
Try to do this:
//inside worker.js
self.addEventListener("message",(event)=>{
importScripts("module.js")
utils.print1()
utils.print2()
})
//inside module.js
//setting a variable in global scope, allows worker.js to use it.
var utils = {
print1(){
console.log("This is a content from a module.")
},
print2(){
console.log("This is a another content from a module.")
}
}
I am running unit tests on a javascript class using Mocha using the follow methodology, firstly the test:
var base = require('../moduleone.js');
describe("some test", function() {
it("description", function() {
var check = base.toBeTested(dummyValue)
//test is here ...
});
});
the moduleone.js containing function to be tested:
function toBeTested(category){
//below I calling an assert function defined in moduletwo
//works fine when running in browser
assert(type(category)=='string','category is string type');
//more code..
return something
module.exports.toBeTested = toBeTested;
moduletwo.js:
function assert(outcome, description) {
//see code.tutsplus.com quick and easy javascript testing with assert
var li = outcome ? 'pass' : 'fail';
if (li == 'fail') {
console.log('FAIL: '+description);
}
else {
console.log('PASS: '+description);
}
}
The issue I have is mocha doesn't know anything about moduletwo and when the moduleone function calles the function in moduletwo mocha throws a ReferenceError: assert is not defined. How can I link all my dependencies so that mocha can see them?
In your moduleone.js be sure that you are requireing moduletwo.js to bring your assert function into scope for moduleone.js. Otherwise, you get a ReferenceError, not for any reasons with mocha, but because moduleone does not have access to assert.
// moduletwo.js
function assert(outcome, description) { /* your functionality */ }
module.exports = assert
// moduleone.js
var assert = require('./moduletwo')
function toBeTested(category) { /* your functionality that uses assert */ }
module.exports.toBeTested = toBeTested
Now, with regards to that tutorial. If you are following it to learn how to make an easy assert module, that is fine. But if you are trying to test some code that does something else, consider using an existing assertion library like chai. For example:
// example.test.js
var expect = require('chai').expect
var isValidCategory = require('./is-valid-category')
describe('isValidCategory(category)', function () {
it('validates string categories', function () {
expect(isValidCategory('A String Category')).to.be.true
})
it('does not validate non-string categories', function () {
expect(isValidCategory(['an', 'array', 'somehow'])).to.be.false
})
})
// is-valid-category.js
module.exports = function isValidCategory(category) {
return typeof category === 'string'
}
Im starting to sort of wrap my head around requirejs and the new Dojo AMD structure, but I have a problem with some early tests:
cg/signup.js:
define(['dojo/_base/fx', 'dojo/dom'], function(fx, dom){
return function(){
this.hidePreloader = function(id){
var preloader = dom.byId(id);
fx.fadeOut({node : preloader}).play()
}
}
})
This works fine. In the master cg.js file:
require(['dojo/_base/kernel', 'dojo/_base/loader'])
dojo.registerModulePath('cg', '../cg')
require(['cg/signup', 'dojo/domReady!'], function(Signup){
var sp = new Signup();
sp.hidePreloader('preloader')
})
Bam. Done. However, in using the Simplified CommonJS Wrapper structure:
define(function(require){
var fx = require('dojo/_base/fx'),
dom = require('dojo/dom');
return function(){
this.hidePreloader = function(id){
var preloader = dom.byId(id);
fx.fadeOut({node : preloader}).play()
}
}
})
I get an undefinedModule error. It seems to come from the dojo/_base/fx line, but I don't know why.
UPDATE
For clarification.
index.html scripts
<script type="text/javascript" src="js/dojo/dojo.js.uncompressed.js" data-dojo-config="isDebug:true,async:true"></script>
<script type="text/javascript" src="js/cg.js"></script>
cg.js
require(['dojo/_base/kernel', 'dojo/_base/loader'])
dojo.registerModulePath('cg', '../cg')
require(['cg/signup', 'dojo/domReady!'], function(signup){
signup.testFunc()
})
js/cg/signup.js
define(['require', 'exports'], function(require, exports){
var dom = require('dojo/_base/kernel');
// Any other require() declarations (with very very few exceptions like 'dojo/_base/array throw undefinedModule errors!!!
// without any error causing requires, this works fine.
exports.testFunc = function(){
alert("hello")
}
})
dojo completely supports the Simplified CommonJS Wrapper format. however, there is a precondition... you must have no dependencies array.
define(function (require, exports, module) {
var fx = require('dojo/_base/fx'),
dom = require('dojo/dom');
// continue...
});
this will NOT work the same
define(['require', 'exports', 'module'], function (require, exports, module) {
var fx = require('dojo/_base/fx'),
dom = require('dojo/dom');
// continue...
});
nor will this...
// in this case require, exports and module will not even exist
define([], function (require, exports, module) {
var fx = require('dojo/_base/fx'),
dom = require('dojo/dom');
// continue...
});
Here is a little wrapper around Dojo define that uses code taken from RequireJS to calculate the dependencies based on the toString of the definition function. It wraps the current "define" in the global namespace, calculates the dependencies and then call's the wrapped define.
defineWrapper.js:
// Workaround for the fact that Dojo AMD does not support the Simplified CommonJS Wrapper module definition
(function() {
var commentRegExp = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg,
cjsRequireRegExp = /require\(\s*["']([^'"\s]+)["']\s*\)/g,
ostring = Object.prototype.toString;
function isArray(it) {
return ostring.call(it) === '[object Array]';
}
function isFunction(it) {
return ostring.call(it) === '[object Function]';
}
var oldDefine = define;
define = function(name, deps, callback) {
//Allow for anonymous functions
if (typeof name !== 'string') {
//Adjust args appropriately
callback = deps;
deps = name;
name = null;
}
//This module may not have dependencies
if (!isArray(deps)) {
callback = deps;
deps = [];
}
//If no name, and callback is a function, then figure out if it a
//CommonJS thing with dependencies.
if (!deps.length && isFunction(callback)) {
//Remove comments from the callback string,
//look for require calls, and pull them into the dependencies,
//but only if there are function args.
if (callback.length) {
callback
.toString()
.replace(commentRegExp, '')
.replace(cjsRequireRegExp, function(match, dep) {
deps.push(dep);
});
//May be a CommonJS thing even without require calls, but still
//could use exports, and module. Avoid doing exports and module
//work though if it just needs require.
//REQUIRES the function to expect the CommonJS variables in the
//order listed below.
deps = (callback.length === 1 ? ['require'] :
['require', 'exports', 'module']).concat(deps);
}
}
if(name === null) {
return oldDefine(deps, callback);
} else {
return oldDefine(name, deps, callback);
}
}
})();
How would you use it?
<script src="...dojo..."></script>
<script src="defineWrapper.js"></script>
<script>require(["some_simplified_commonjs_defined_module"], function(module) {
// use module here
});</script>
Note that Dojo does not support the simplified CommonJS style for dependency detection when doing a build. This means you'll either need to use the normal dependency list style, or you'll have to duplicate all your dependencies when defining layers in the build profile.
Here's the relevant bug in their tracker:
http://bugs.dojotoolkit.org/ticket/15350
is require defined? I don't see where that argument value would come from. I think you might have to do something like
define(["require"], function(require){ ...
I started to think that maybe I wasn't meant to learn Dojo. But, it all comes together with a little more reading. I'm not sure exactly what I did different or whatever, but here's the working layout.
index.html scripts and config
<script type="text/javascript">
dojoConfig = {
async : true,
isDebug : true,
debugAtAllCosts : true,
packages : [{
name : 'cg',
location : '/../js/cg'
}]
}
</script>
<script src="http://ajax.googleapis.com/ajax/libs/dojo/1.7.1/dojo/dojo.js"></script>
<script type="text/javascript" src="js/cg.js"></script>
js/cg.js
require(['cg/signup', 'dojo/ready'], function(signup){
signup.init('preloader')
})
js/cg/signup.js
define(['dojo', 'require'], function(dojo, require){
var fx = require('dojo/_base/fx')
return new function(){
this.init = function(id){
fx.fadeOut({node : dojo.byId(id)}).play()
}
}
})
Again, not entirely sure why the var fx = require(...) statement works differently in this one than the others, could be the build I downloaded vs. the CDN, who cares. It works. Some links I used to help for others possibly in the same boat:
Writing Modular JS
AMD vs CommonJS Wrapper
Dojo Toolkit AMD
Dojo Config (1.7)