CoffeeScript Cakefile not finding NPM Module node-glob - javascript

I am trying to use a code snippet from a README for node-glob in CoffeeScript. I installed the package:
npm install --global glob
I am trying to use the following snippet:
var glob = require("glob")
// options is optional
glob("**/*.js", options, function (er, files) {
// files is an array of filenames.
// If the `nonull` option is set, and nothing
// was found, then files is ["**/*.js"]
// er is an error object or null.
})
and I assume its then written something similar to this in CoffeeScript:
# Cakefile
{glob} = require 'glob' # npm install --global glob
task 'glob-test', 'Testing Globs', ->
glob.sync("**/*.ts") (er, files) ->
console.log files
However, I get the following error messages:
Error: Cannot find module 'glob'
Am I doing this correctly, or is it even possible CoffeeScript and I should just abandon the whole idea?
UPDATE:
Installed the node-glob module as a locally vendored module this time using:
npm install glob
and changed {glob} to glob in the require statement.
and ran the Cakefile task again. Got this error this time.

Related

Jest not recognising JQuery Object ($)

I have used JavaScript to created a simple web application to measure how much time I spend on different projects.
I want to test the code with Jest and this works fine until I try to test a function that contains the JQuery object ($).
This is the error message I get:
ReferenceError: $ is not defined
The answers I have found online tells me that I need to add a jQuery dependency in my global object, which I have done. Below is my package.json file:
"jest": {
"setupFiles": ["PathToSetupFile/setup-jest.js"],
"type": "module"
and my setup-jest.js:
import $ from 'jquery';
global.$ = global.jQuery = $;
I am now met with a new error message:
SyntaxError: Cannot use import statement outside a module
I cannot find any further information on how to fix this. A few resources tell me I need to update my jest.config.js file but this file does not exist anywhere in my node modules.
I thought it would be helpful to start completely from the beginning and therefore address a much wider scope but never the less provide the exact answer to your problem at the end of my response here.
In PowerShell CD to your project folder
Install the jest node modules locally into your project folder using
npm install --save-dev jest
Install jest globally so you can use it as a CLI command
npm install jest -g
This installs Jest globally i.e. to your user profile %APPDATA%\npm location
Ensure %APPDATA%\npm is in your user profile environment PATH variable (in Windows settings, "Edit Environment variables for your account")
Check in your PowerShell console that it is in your path using $Env:PATH. (If your %APPDATA%\npm path still isn't showing then restart the PowerShell window, if the terminal is inside VSCode then you will have to restart VSCode so that the terminal inherits the new environment)
In order to import jquery you will need to a) install jquery and b) define a setup file for jest which is referenced in jest.config.js created using jest --init in your project folder.
Install jquery -
npm install --save-dev jquery
Generate jest.config.js -
jest --init
The following questions will help Jest to create a suitable configuration for your project
√ Would you like to use Typescript for the configuration file? ... no
√ Choose the test environment that will be used for testing » jsdom (browser-like)
√ Do you want Jest to add coverage reports? ... yes
√ Which provider should be used to instrument code for coverage? » v8
√ Automatically clear mock calls, instances, contexts and results before every test? ... yes
✏️ Modified your\project\folder\package.json
📝 Configuration file created at jest.config.js
If you don't specify the jsdom (browser-like) test environment then running code under test that uses jquery will yield an error of "jQuery requires a window with a document"
But this means the 'jest-environment-jsdom' must now be installed
(As of Jest 28 "jest-environment-jsdom" is no longer shipped by default, make sure to install it separately.) -
npm install --save-dev jest-environment-jsdom
Edit jest.config.js
Change
// setupFiles: [],
To
setupFiles: [ './jest.setup.js' ],
N.B. the "./" prefix is required otherwise jest will state it cannot find the jest.setup.js file.
The create jest.setup.js in your project folder and add the following -
const $ = require('jquery');
global.$ = global.jQuery = $;
Node uses the CommonJS module system (https://nodejs.org/en/knowledge/getting-started/what-is-require/)
so the above syntax is required to work with Node.js

Webpack loads unwanted file when passing string+variable to require()

When running the following code I get an error when building with Webpack:
const name = 'Test';
const test = require(`./app/model/${name}`);
However, with the following code I get no error:
const test = require('./app/model/Test');
The error received is:
ERROR in ./node_modules/express/lib/request.js
Module not found: Error: Can't resolve 'net' in '/path/to/maestro/node_modules/express/lib'
# ./node_modules/express/lib/request.js 18:11-25
# ./node_modules/express/lib/express.js
# ./node_modules/express/index.js
# ./app/model/CommanderProgram.js
# ./app/model sync ^\.\/.*$
# ./web.js
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! xops-pat#4.0.0-rc1 build: `webpack`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the xops-pat#4.0.0-rc1 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! /path/to/error/log/2019-12-09T16_19_45_494Z-debug.log
The contents of ./app/model/Test.js are:
'use strict';
module.exports = 'asdf';
So no dependencies. The error above mentions ./app/model/CommanderProgram.js, which absolutely should not be Webpack'd. Based on the fact that Test.js has nothing in it, Webpack should not be trying to include CommanderProgram.js, though. However, if I delete CommanderProgram.js then the error does NOT occur. Restoring CommanderProgram.js then renaming it to either AAA.js or ZZZ.js still DOES cause the problem (without updating references, so nothing could be importing AAA.js/ZZZ.js), so somehow Webpack is trying to include an un-referenced file.
I also tried the following, showing it's not an issue with template literals:
const name = 'Test';
const test = require('./app/model/' + name);
Why does Webpack appear to include an un-referenced file when using variables in strings passed to require?
Environment:
Node: v10.16.3
OS: Windows 10
Webpack: 4.41.2
Webpack-cli: 3.3.10
See code here: https://github.com/xOPERATIONS/maestro/blob/9d7977f52c1a08bc947666f3b1c85c30787cb831/web.js
The underlying problem is documented here: https://webpack.js.org/guides/dependency-management/#require-with-expression
In short, doing require('./app/model/' + name) makes Webpack include files in the directory ./app/model matching regular expressing .* (i.e. everything in that directory). So while CommanderProgram.js was the module that caused errors, thus making this a problem, all other modules in that directory were also being included even if they were not desired.
EDIT: Replacing the string+variable with a function expression in this case will prevent the undesired file from being loaded, and thus the error will go away. However, using a function expression will NOT solve the problem of trying to load modules using variables.
Original answer (does not work):
To get around this, do one of the following (which all boil down to "wrap the string in a function"):
Construct an absolute path with path.resolve():
const test = require(path.resolve(__dirname, 'app/model', name));
Construct the require-string with a function:
const myfunc = function(mod) {
return `./app/model/${mod}`;
};
const name = 'Test';
const test = require(myfunc(name));
Construct the require-string with an IEFE (immediately envoking function expression):
const test = require(
(function() {
return `./app/model/${name}`;
}())
);

Gulp error on node_module that has scss

I recently npm installed the node module react-calendar-timeline .
After implementing it one of my components, I ran gulp to build.
gulp threw an error:
events.js:141
throw er; // Unhandled 'error' event
^
SyntaxError:
/var/www/monitor/node_modules/react-calendar-timeline/modules/lib/Timeline.scss:1
$item-color: white;
^
ParseError: Unexpected token
My gulpfile file for this component looks like this:
var gulp = require('gulp');
var browserify = require('gulp-browserify');
var concat = require('gulp-concat');
var babel = require('gulp-babel');
gulp.task('browserify', function() {
gulp.src('js/ScheduleMain.js')
.pipe(browserify({transform:'babelify'}))
.pipe(concat('ScheduleMain.js'))
.pipe(gulp.dest('static/dist/js'));
It seems as though I am not able to handle the .scss file of the module I have installed. What is the proper way to handle this?
It could be an issue related more to gulp-browserify than your build script.
Keep in mind that gulp-browserify is long dead, in fact it's been more than an year since the last update; this is from it's npm page:
NOTE: THIS PLUGIN IS NO LONGER MAINTAINED , checkout the recipes by gulp team for reference on using browserify with gulp.
Browserify natively supports streming and with just a pair of plugins you can trasform that stream to be gulp compatible, I suggest you to take a look at gulp's examples folder, more specifically to this example using browserify.
By the way, what's the point in running gulp-concat when in your stream theres only one file?

How to manually bundle two javascript files?

I'm writing code in Javascript for Espruino (an embedded platform) and there is a restriction: Only one file is allowed to be saved into the device.
For the following code to work:
var x = new require("Something");
x.hello()
Something module should be reachable from main.js file. The Something module is a separate file and looks like this:
function Something() {
....
}
Something.prototype.hello = function() {
console.log("Hello there!");
}
exports = Something;
Question is; How can I concatenate these two files and still use the Something module as require("Something"); format?
The answer is found in Espruino forums:
# create bundle
BUNDLE="init.min.js"
echo "" > ${BUNDLE}
# Register modules via `Modules.addCached()` method
# see: http://forum.espruino.com/comments/12899741/
MODULE_NAME="FlashEEPROM"
MODULE_STR=$(uglifyjs -c -m -- ${MODULE_NAME}.js | sed 's/\"/\\\"/g' | sed "s/\n//g")
echo "Modules.addCached(\"${MODULE_NAME}\", \"${MODULE_STR}\");" >> ${BUNDLE}
uglifyjs -c -m -- init.js >> ${BUNDLE}
Why don't you use webpack to bundle the modules files into one file.
I suppose that your current directory is your project directory
First install nodejs at:
https://nodejs.org/en/download/
or sudo apt-get install nodejs
Second, install webpack using this command
npm i -g webpack
bundle your module
To build your bundle run this command:
webpack ./main.js bundle.js
Note: your bundle.js will include all the module files that you have required in main.js
There is https://www.npmjs.com/package/espruino tool that has function to prepare code (concatenate + minimize) for uploading to your board.
I use it in my build proc that compiles typescript code to javascript and then prepares for board upload. Tutorial is here https://github.com/espruino/EspruinoDocs/blob/master/tutorials/Typescript%20and%20Visual%20Studio%20Code%20IDE.md
Yes like it's mentioned above, you need to uglify the code. You cannot use webpack or grunt here. They will transpile the code which will break your require libraries.
Here is how I achieved this in my case:
I put all my files inside a folder (like /src). Don't import one file from another. Then minify all files in the folder into a single file (eg. index.js)
uglifyjs src/* --compress --mangle -o ./index.js
Then just upload this index.js into espruino. You need to install this library globally first.
npm install -g espruino
espruino -p /dev/cu.wchusbserial1420 -b 115200 --board ESP8266_4MB.json -e 'save()' index.js
I made a simple example here:
https://github.com/aliustaoglu/espruino-http-server

How to require jQuery.loadTemplate using browserify

I have setup browserify with Gulp.
When I require jQuery, everything works:
var $ = require('jquery');
When I try to require jquery load template module
var loadTemplate = require('jquery.loadtemplate')
I get an error
module "jquery.loadtemplate " not found
I installed loadtemplate using npm like this
npm install --save jquery.loadtemplate
I think there is an error in the package.json of the jquery.loadtemplate module. It should define the source of the plugin somewhere and it's missing. In other modules the source is defined in the "main" property. It should say something like
"main": "jquery-loadTemplate/jquery.loadTemplate-1.5.0.js",
depending on the location of the script file. You can change it manually, but then it'll be deleted the next time you update/reinstall your npm package.

Categories

Resources