Can't require Underscore with CasperJS - javascript

I'm using CasperJS to run automated frontend tests but have run in to an issue with using other npm modules in my tests. I'm aware of patchRequire however I believe that is only to be called outside of the test environment as the test runner patches require automatically. I did include it but the results were the same. It says it can't find the module. I have confirmed the underscore module is installed in node_modules in the projects root folder.
Code
'use strict'
_ = require 'underscore'
testConfig =
testPageUrl: ''
testSearchTerm: 'the'
config = _.extend testConfig, require 'common/config'
Code in Javascript
'use strict';
_ = require('underscore');
testConfig = {
testPageUrl: '',
testSearchTerm: 'the'
};
config = _.extend(testConfig, require('common/config'));
Error
CasperError: Can't find module underscore

So solution I eventually found was to create proxy modules that import the npm module and export it out to the casper script.
./proxies/underscore.js:
module.exports = require('underscore');
./tests/test.js
var _ = require('../proxies/underscore');

Related

esbuild cannot resolve the Node.js module 'events'

One of my dependencies contains the following code
var EventEmitter = require('events').EventEmitter;
exports.EventEmitter = EventEmitter;
exports.mixin = mixin;
function mixin(Constructor) {
for (var key in EventEmitter.prototype) {
Constructor.prototype[key] = EventEmitter.prototype[key];
}
}
I got the following error when trying to bundle everything into a file
$ npm run build
> gantt#0.0.0 build
> esbuild public/js/src/main.ts --bundle --minify --sourcemap --outfile=public/js/dest/bundled.js
> node_modules/sharedb/lib/emitter.js:1:27: error: Could not resolve "events" (use "--platform=node" when building for node)
1 │ var EventEmitter = require('events').EventEmitter;
╵ ~~~~~~~~
1 error
I am targeting browsers, so it's impractical to have --platform=node. I discovered this issue when searching around, but the offending line is in a dependency, so I cannot simply edit its source to replace the CommonJS module import with an ES module import.
How can I point esbuild to the implementation of events?

NodeJS require from unknown child folder

-- plugins
---- myplugin1
------ core
---- myplugin2
------ core
If this is my directory structure, is there any way for me to import all core folders from plugins without knowing the name myplugin1 etc?
require('/plugins/./core')
I know how to require from parent folders... but there seem to be nothing about child folders?
Node-Cheat available here, run node app followed by npm i glob.
Possible try:
const glob = require('glob');
const path = require('path');
glob.sync('./plugins/**/core/*.js').forEach(( file ) => {
require(path.resolve( file ) );
});
Expected output:
myplugin1 core loading
myplugin2 core loading
You can use require-dir to achieve this.
These will be the steps
npm install require-file-directory
var requireDir = require('require-dir');
var dir = requireDir('pathToyourCoreDirectory');
And inside the above handler function you can require all of the modules

Typescript module, require external node_modules

I need to use a simple node_module inside a simple typescript file, but it seems that the compiler doesn't want to get it.
Here's my simple ts file :
import glob = require('glob');
console.log(glob);
And I've got this error :
[13:51:11] Compiling TypeScript files using tsc version 1.5.0
[13:51:12] [tsc] > F:/SkeletonProject/boot/ts/Boot.ts(4,23): error TS2307: Cannot find external module 'glob'.
[13:51:12] Failed to compile TypeScript: Error: tsc command has exited with code:2
events.js:72
throw er; // Unhandled 'error' event
^
Error: Failed to compile: tsc command has exited with code:2
npm ERR! skeleton-typescript-name#0.0.1 start: `node compile && node ./boot/js/Boot.js`
npm ERR! Exit status 8
npm ERR!
npm ERR! Failed at the skeleton-typescript-name#0.0.1 start script.
However, when I use a simple declaration in this same script, it works :
var x = 0;
console.log(x); // prints 0 after typescript compilation
What am I doing wrong in this case ?
EDIT:
Here's my gulp file :
var gulp = require('gulp');
var typescript = require('gulp-tsc');
gulp.task('compileApp', ['compileBoot'], function () {
return gulp.src(['app/src/**/*.ts'])
.pipe(typescript())
.pipe(gulp.dest('app/dist/'))
});
gulp.task('compileBoot', function () {
return gulp.src(['boot/ts/*.ts'])
.pipe(typescript({
module:'commonjs'
}))
.pipe(gulp.dest('boot/js/'))
});
gulp.start('compileApp');
Thanks for advance
Thanks for advance
You are using the correct syntax:
import glob = require('glob');
But the error: Cannot find external module 'glob' is pointing out that you are using a special case.
By default, the compiler is looking for glob.ts, but in your case you are using a node module, not a module that you have written. For this reason, the glob module will need special treatment...
If glob is a plain JavaScript module, you can add a file named glob.d.ts with type information that described the module.
glob.d.ts
declare module "glob" {
export class Example {
doIt(): string;
}
}
app.ts
import glob = require('glob');
var x = new glob.Example();
Some Node modules already include the .d.ts in the package, in other cases you can grab it from Definitely Typed.
Here is the error with your code
import glob = require('glob');
Because in node.js import is not a reserved keyword. If you require any module in your application, you simply require it using the statement
var glob = require('glob');
Once done you can then use
console.log(glob);
To print the value of glob.Replacing import will hopefully do the job for you.

Compiling into CommonJS does not produce files usable by NodeJS

Given the syntax provided here (standard ES6 modules with import/export), and the files below, the typescript compiler (tsc) builds files which will throw Error: Cannot find module when used with NodeJS.
Here's a stripped down example:
Input files
src/main.ts
import {Example} from 'example';
let e = new Example();
src/example.ts
export class Example {}
Compilation
Note, using the tsc from npm install -g typescript, version 1.5.0-beta, from a windows machine.
tsc --rootDir src --outDir bin
Output files
bin/main.js
var example_1 = require('example');
var e = new example_1.Example();
bin/example.js
var Example = (function () {
function Example() {
}
return Example;
})();
exports.Example = Example;
Am I doing something incorrectly? I expected main.js to include something like require('example.js') instead.
import {Example} from 'example';
You're importing a module here, not a file. Try
import {Example} from './example';

Where do we put node modules we install by npm in a Meteor project?

I followed the github meteorirc project's lead and put them in /public/
I installed my node modules via npm from inside /public/ and therefore I have a /public/node_modules/ directory.
I don't think this is the 'proper' or 'standard' place for them because according to the Meteor docs...
Meteor gathers all your JavaScript files, excluding anything under the
client and public subdirectories, and loads them into a Node.js server
instance inside a fiber
The code to load is in the server dir and server js files and looks like this.
var require = __meteor_bootstrap__.require;
var path = require("path");
var fs = require('fs');
var base = path.resolve('.');
if (base == '/'){
base = path.dirname(global.require.main.filename);
}
var Twit;
var twitPath = 'node_modules/twit';
var publicTwitPath = path.resolve(base+'/public/'+twitPath);
var staticTwitPath = path.resolve(base+'/static/'+twitPath);
if (path.existsSync(publicTwitPath)){
Twit = require(publicTwitPath);
}
else if (path.existsSync(staticTwitPath)){
Twit = require(staticTwitPath);
}
else{
console.log('WARNING Twit not loaded. Node_modules not found');
}
Based on the docs this is not standard and I don't believe I should be doing it this way. Yet, it works both on my dev platform and in production at deploy meteor.com.
Where in the directory structure of the project should node modules be installed so that they work locally and upon deployment at meteor.com or elsewhere?
cd /usr/local/meteor/lib/ && npm install <module>
To use Npm modules in Meteor its adding the npm module in.
First you need to add a npm package adapter such as meteorhacks:npm
meteor add meteorhacks:npm
Then start your meteor app by running meteor, you will notice a new packages.json file in your project
Add in modules like this (you need to explicitly define a version)
{
"request" : "2.53.0"
}
Then you can use the npm modules in your meteor app, use Meteor.npmRequire instead of require
var request = Meteor.npmRequire("request")
Meteor takes lib/node_modules from the development bundle and makes a symbolic link or copies it to server/node_modules, which is in the hidden .meteor sub folder under your project.
So, if you cd into the lib directory of the development bundle or into server directory of the .meteor folder (I believe it is in build); you will be able to use the node modules. If you have trouble loading them, you might want to check out this question.
You have to add bundle folder to the path:
var staticTwitPath = path.resolve(base+'/bundle/static/'+twitPath);
Here is my working sample in coffeescript, node_modules are in public folder:
# loading node_modules from public folder
require = __meteor_bootstrap__.require
path = require("path")
fs = require('fs')
cheerioPath = 'node_modules/cheerio'
base = path.resolve('.')
if base == '/'
base = path.dirname(global.require.main.filename)
publicPath = path.resolve(base+'/public/'+cheerioPath)
staticPath = path.resolve(base+'/bundle/static/'+cheerioPath)
if path.existsSync(publicPath)
cheerio = require(publicPath)
else if path.existsSync(staticPath)
cheerio = require(staticPath)
else
console.log('node_modules not found')
Good luck!
This helped me a lot including a syntax highlighting package! Thanks!
I use a little helper though, as I think this will not be the last npm package I'll use ;)
meteorNpm = do() ->
require = __meteor_bootstrap__.require
path = require 'path'
fs = require 'fs'
base = path.resolve '.'
if base is '/'
base = path.dirname global.require.main.filename
meteorNpm =
# requires npm modules placed in `public/node_modules`
require: (moduleName) ->
modulePath = 'node_modules/' + moduleName
publicPath = path.resolve(base + '/public/' + modulePath)
staticPath = path.resolve(base + '/bundle/static/' + modulePath)
if path.existsSync(publicPath)
module = require publicPath
else if path.existsSync(staticPath)
module = require staticPath
else
module = null
return module
Use it like this:
highlight = meteorNpm.require "highlight.js"
I am using such script which nicely install all node.js dependencies. It behaves similar to official support in Meteor engine branch (it installs dependencies at runtime) but it supports also installing from git repositories and similar goodies.

Categories

Resources