sails.js setup: How to make a node module available across the sails project (controller / model, etc)? - sails.js

I just getting started with SailsJS as my first web framework on Node. Let's say I wanna add MomentJS in and use across the app. How to set it up?

you can use the bootstrap.js (in config/)
like:
module.exports.bootstrap = function (cb) {
sails.moment = require('moment');
cb();
};
in all Sails-Files you can use
sails.moment()
now.

If you're trying to include your node_modules into the client side, such as jQuery, AngularJS or one of the various many font libraries, then you can npm install them as normal, but just to be sure in sails you edit your tasks/config/copy.js and add a new block, example:
grunt.config.set('copy', {
dev: {
files: [{
expand:true,
cwd: './node_modules/font-awesome/fonts',
src: ['**/*'],
dest: '.tmp/public/fonts'
}
}
});
LESS can be #imported like normal without being copied around. Other assets will need to be copied as above. If you're using the sails linker then don't forget to add your JS paths to tasks/pipeline.js too (if necessary).
You can read more here:
http://ash.zi.vc/sails/2016/02/02/including-client-side-node-modules-in-my-sails-application/
It's not directly obvious how to sync npm modules to the web accessible directories.

SailsJS is no different to any other NodeJS app. So on top of your (say) Controller.js file, you do
var m = require("moment");
And you're good to go. #mdunisch's method will obviously let you use the moment package throughout your app, without having to do "require" in each file.

Related

Specifying window (global) variable type hinting in VSCode from external JS file without typescript

This may be a silly question but I really don't know where to look.
I'm creating a browser testing environment for a pretty large-scale API written in typescript. This API uses esbuild to build the typescript files into a /dist/ folder with a single index.js entry-point and its appropriate d.ts file.
I've created a /tests/ folder to hold some browser files that includes an index.html file with Mocha and Chai imported. It also imports /dist/index.js which is set globally to a window.myAPI variable.
In /tests/index.html:
import * as myAPI from "./dist/index.js"
Alongside index.html in the tests folder, there are separate JS files included for different tests that run things on window.myAPI... to do assertion tests.
search.test.js
book.test.js
navigate.test.js
I then run a server to host at the root. These separate tests are then imported from /tests/index.html. The separate tests look like this inside:
const { chai, mocha } = window;
const { assert } = chai;
describe("Search", function() {
describe("Setup", function() {
it("Setting URL should work", function() {
const call = myAPI.someCall()
assert.ok(call);
});
});
});
mocha.run();
Everything works, but I have no code hinting for myAPI. I'd like to be able to see what functions are available when I type myAPI, and what parameters they take, and what they should return - along with all my comments on each function.
In typescript you can do things like ambient declarations, but I don't want to make my tests typescript because then I add an unnecessary build step to the tests. But it would be as easy as:
/// <reference path = "/dist/index.d.ts" />
How can I tell VSCode that window.myAPI is an import of /dist/index.js and should import the types as well so I can see them ?
I'm open to different solutions to this, but I feel like this should be pretty simple. I don't know if ESLint is capable of doing something like this, but I tagged it because I feel it's relevant.
Thanks!

Frontend headless browser testing using CasperJS and configuration-files?

I tried to use CasperJS for headless browser testing using PhantomJS and wanted to have a config file or something to change Website URL, Username passwords etc. So finally I found NuclearJS. Do you guys know any other perfect way to do this? If I wanted to write a one from the scratch would like to know about as well.
I got a solution (not perfect ;) ) that is using multiple configfiles (for selector, execution, desktop, mobile, etc).
I include a in the execution of my casperjs tests a file that offers me all configs i need (i include also global functions there).
Lets guess the test execution looks like that:
casperjs test --includes=loadGlobals.js test_1.js
In the that example loadGlobals.js contains functions like that:
var fs = require('fs');
var config = {},
configFile = fs.read('config.json');
config = JSON.parse(configFile);
Probalby the config.json is looking like that:
{
"url": "http://www.yourTestUrl.com",
"variable_1": "bla",
"variable_2": "blub",
"nextTier": {
"variable_1": "blablub"
}
}
Now you can call in the test_1.js the variables of the config.json:
casper.start(config.url, function() {
casper.then(function() {
casper.echo(config.variable_1);
casper.echo(config.variable_2);
casper.echo(config.nextTier.variable_1);
});
})
casper.run();
You can use like that different configurationfiles, even to override it during tests if nessacary.
The tests should be written in the page object pattern style so they are highly maintable, espacially with a outsourced configuration.
NuclearJS i didn't know, but i will take a look into it, too.

react-jsonschema-form How to use it via cdn?

I am trying to use this library "react-jsonschema-form" to create forms using react and jsonschema.
I am trying to use it in my project as described in the example from the website by including the .js file via cdn. It is not working. The exported component "Form" is undefined.
I had a look at this similar question Using React component from js source maps but I could not understand the solution offered. I am supposed to alias the default export of JSONSchemaForm. But what is JSONSchemaForm? and where can I find it? Is it another library to be included?
Here is what I tried to do:
Using Require.js I have imported the cdn library:
var require = {
baseUrl: "/js/",
waitSeconds: 600,
paths: {
'react-forms': ['https://unpkg.com/react-jsonschema-form/dist/react-jsonschema-form']
},
}
Then in my code I import the library:
var rf = require('react-forms')
But now when I access Form (rf.Form), it is undefined. I had a look at the "react-jsonschema-form.js" source code. "Form" is defined no where.
From the instructions of the library page it is said:
You'll also need to alias the default export property to use the Form component:
const Form = JSONSchemaForm.default;
// or
const {default: Form} = JSONSchemaForm;
But JSONSchemaForm is also undefined.
So I don't know what I am doing wrong. How can I use "react-jsonschema-form" library by including it as a script tag?
Thank you community.
1. Include the cdn path
<script src="https://cdn.jsdelivr.net/npm/react-jsonschema-form#1.0.3/dist/react-jsonschema-form.js"></script>
2.By using field get the access of jsonformDefaultValues;
` <script type="text/babel"
const fields = JSONSchemaForm.default
return(
<Form
schema={schema}
uiSchema={uiSchema}
field={fields}
onSubmit={onSubmit}
</Form>)
</script>`
I was able to solve this problem and I am reporting here the solution for any one facing a simlilar issue. To use react-jsonschema-form via cdn script tag (with require.js):
include this library via require.js by indicating the url path :
paths: {
'react-forms': ['https://unpkg.com/react-jsonschema-form/dist/react-jsonschema-form']
}
include this polyfill library: cdn.polyfill.io/v2/polyfill.min.js
Make sure to use the latest react version ( version v15)
In you code, require the library and alias its default export like this:
var rf = require("react-forms");
const Form = rf.default;
(This is because I am using require.js module system. For another module system, you may use JSONSchemaForm.default)

How do I write a Webpack plugin to generate index.js files on demand?

In general, I want to know how to do code-generation/fabrication in a Webpack plugin on demand. I want to generate contents for files that do not exist when they are "required."
Specifically, I want a plugin that, when I require a directory, automatically requires all files in that directory (recursively).
For example, suppose we have the directory structure:
foo
bar.js
baz.js
main.js
And main.js has:
var foo = require("./foo");
// ...
I want webpack to automatically generate foo/index.js:
module.exports = {
bar: require("./bar"),
baz: require("./baz")
};
I've read most of the webpack docs. github.com/webpack/docs/wiki/How-to-write-a-plugin has an example of generating assets. However, I can't find an example of how to generate an asset on demand. It seems this should be a Resolver, but resolvers seem to only output file paths, not file contents.
Actually for your use case:
Specifically, I want a plugin that, when I require a directory, automatically requires all files in that directory (recursively).
you don't need a plugin. See How to load all files in a subdirectories using webpack without require statements
Doing code-generation/fabrication on demand can be done in JavaScript quite easily, why would you restrict your code generation specifically to only applied, when "required" by WebPack?
As NodeJS itself will look for an index.js, if you require a directory, you can quite easily generate arbitrary exports:
//index.js generating dynamic exports
var time = new Date();
var dynamicExport = {
staticFn : function() {
console.log('Time is:', time);
}
}
//dynamically create a function as a property in dynamicExport
//here you could add some file processing logic that is requiring stuff on demand and export it accordingly
dynamicExport['dyn' + time.getDay()] = function() {
console.log('Take this Java!');
}
module.exports = dynamicExport;

Using twix and momentjs in meteor

I'm trying to put together a small app using meteor, and having a lot of luck. But I can't get the app to use the Twix plugin for momentjs.
Using Meteorite, I added the Momentjs library from Atmosphere, mrt add moment, so no problem there. But there's no twix package in Atmosphere. I used npm to install twix package, but neither meteor no mrt will add twix, responding Package named twix doesn't exist in your meteor installation which I guess makes sense, it being a Nodejs package not a Meteor package. Finally I tried downloading the twix.js file and placing it in different directories, but nothing has worked.
I'm not getting errors with this code:
if (Meteor.isServer) {
Meteor.startup(function () {
var moment = Npm.require('moment');
Npm.require('twix');
});
and I can use the MomentJS library, but not the twix plugin. Writing (within Meteor.isClient)
Template.dayTable.date = function() {
return moment(Session.get('selectedDate')).format("MMM Do YY");
}
works fine, but writing
var t = new moment("1/25/1982 9:30 AM").twix("1/25/1982 1:30 PM");
has the js console tell me Uncaught TypeError: Object [object Object] has no method 'twix'
Is there a secret place I can put the twix.js file for Meteor/MomentJS to use (which seems likely)? Am I not require-ing it correctly? Or what?
Thanks!
Meteor loads javascript in a certain order. See the Meteor docs (search for "load order"). To fix this:
add moment.js to client/lib to ensure it's loaded before twix
add twix.js to the client folder
You can also look into creating a package (which is what Npm.require is intended for) and include that, or rename the files since files are included alphabetically. More info is in the docs.
It's not documented anywhere, but you can also use Twix standalone, like this:
var Twix = Npm.require('twix');
var t = new Twix(firstTime, secondTime);