$ Is not defined scripts Gulp task - node.js

Hi I am trying to run my scripts task in gulp. My scripts path is defined as follows:
scripts: {
coffee: [
'app/assets/scripts/**/*.coffee'
],
js: [
'src/js/*',
'src/js/**/*'
],
map: ['src/js/**/*.map']
},
My original file paths are located in root/src/js/ and I want my scripts to be placed in their minified version inside root/app/assets/scripts/.
My gulp task is as follows:
gulp.task('scripts', function() {
return gulp.src('app/scripts/**/*.js')
.pipe($.if('*.js', $.uglify({preserveComments: 'some'})))
.pipe($.sourcemaps.init())
.pipe($.concat('app.js'))
.pipe($.sourcemaps.write('./'))
.pipe(gulp.dest('app/assets/scripts'));
});
But for some reason I keep getting this error
[13:28:46] ReferenceError: $ is not defined
at Gulp.<anonymous> (C:\Users\Myuser\apps\myapp\gulpfile.js:165:9)
at module.exports (C:\Users\Myuser\apps\myapp\node_modules\gulp\node_
modules\orchestrator\lib\runTask.js:34:7)
at Gulp.Orchestrator._runTask (C:\Users\Myuser\apps\myapp\node_module
s\gulp\node_modules\orchestrator\index.js:273:3)
at Gulp.Orchestrator._runStep (C:\Users\Myuser\apps\myapp\node_module
s\gulp\node_modules\orchestrator\index.js:214:10)
at Gulp.Orchestrator.start (C:\Users\Myuser\apps\myapp\node_modules\g
ulp\node_modules\orchestrator\index.js:134:8)
at C:\Users\Myuser\AppData\Roaming\npm\node_modules\gulp\bin\gulp.js:129:2
0
at process._tickCallback (node.js:355:11)
at Function.Module.runMain (module.js:503:11)
at startup (node.js:129:16)
at node.js:814:3
UPDATE
Hey I think you are both right. $ was not defined and should be $ = require('gulp-load-plugins')();. However now that I am running scripts, I get the following error:
[15:24:46] TypeError: undefined is not a function
at Gulp.<anonymous> (C:\Users\Myuser\apps\myapp\gulpfile.js:166:13)
at module.exports (C:\Users\Myuser\apps\myapp\node_modules\gulp\node_
modules\orchestrator\lib\runTask.js:34:7)
at Gulp.Orchestrator._runTask (C:\Users\Myuser\apps\myapp\node_module
s\gulp\node_modules\orchestrator\index.js:273:3)
at Gulp.Orchestrator._runStep (C:\Users\Myuser\apps\myapp\node_module
s\gulp\node_modules\orchestrator\index.js:214:10)
at Gulp.Orchestrator.start (C:\Users\Myuser\apps\myapp\node_modules\g
ulp\node_modules\orchestrator\index.js:134:8)
at C:\Users\Myuser\AppData\Roaming\npm\node_modules\gulp\bin\gulp.js:129:2
0
at process._tickCallback (node.js:355:11)
at Function.Module.runMain (module.js:503:11)
at startup (node.js:129:16)
at node.js:814:3
Again, another vague error "undefined is not a function", is this explicit? Is there a $ function missing?

You probably need to use gulp-load-plugins package:
var $ = require('gulp-load-plugins')({lazy: true});

Related

How to use a global nodejs module?

I got the following error when I try to use esprima. Does anybody know how to fix the problem? Thanks.
$ npm install -g esprima
/usr/local/bin/esparse -> /usr/local/lib/node_modules/esprima/bin/esparse.js
/usr/local/bin/esvalidate -> /usr/local/lib/node_modules/esprima/bin/esvalidate.js
+ esprima#4.0.1
updated 1 package in 0.837s
$ cat main.js
#!/usr/bin/env node
// vim: set noexpandtab tabstop=2:
var esprima = require('esprima');
var program = 'const answer = 42';
console.log(esprima.tokenize(program));
console.log(esprima.parseScript(program));
$ node main.js
internal/modules/cjs/loader.js:960
throw err;
^
Error: Cannot find module 'esprima'
Require stack:
- /private/tmp/main.js
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:957:15)
at Function.Module._load (internal/modules/cjs/loader.js:840:27)
at Module.require (internal/modules/cjs/loader.js:1019:19)
at require (internal/modules/cjs/helpers.js:77:18)
at Object.<anonymous> (/private/tmp/main.js:4:15)
at Module._compile (internal/modules/cjs/loader.js:1133:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1153:10)
at Module.load (internal/modules/cjs/loader.js:977:32)
at Function.Module._load (internal/modules/cjs/loader.js:877:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12) {
code: 'MODULE_NOT_FOUND',
requireStack: [ '/private/tmp/main.js' ]
}
I think you installed esprima module in global node_modules.
If you want to use esprima in main.js which is located at /private/temp/main.js,
you should run npm install esprima in /private/temp/ without -g
EDIT - How to require global modules
Way 1
I assume you're in mac system.
Before you run your main.js, run export NODE_PATH=/usr/local/lib/node_modules in the shell, not node.js program.
Then you could require the global modules by const esprima = require("esprima").
By the way, global modules position could be different in the different system.
Way 2
After you knew your global modules position,
you could require it by const esprima = require("/usr/local/lib/node_modules/esprima")

Mocha not working in WebStorm in WSL due to 'unknown \"reporter\"'

When running mocha in WebSstorm pointed to a WSL environment I get:
C:\Users\iursino\AppData\Local\Microsoft\WindowsApps\ubuntu.exe run "export PATH=/home/iursino/n/bin:$PATH && /home/iursino/n/bin/node --inspect-brk=49953 /mnt/c/workspace/redacted-project-name/node_modules/mocha/bin/_mocha --timeout 0 --ui bdd --reporter \"/mnt/c/Program Files/JetBrains/WebStorm 2019.2.4/plugins/NodeJS/js/mocha-intellij/lib/mochaIntellijReporter.js\" /mnt/c/workspace/redacted-project-name/src/Filename.spec.ts --grep \"^invoke lambda Expect error if lambda returns an error$\""
Debugger listening on ws://127.0.0.1:49953/f31007fa-106c-4847-94cf-3e7d98d72e71
For help, see: https://nodejs.org/en/docs/inspector
Debugger attached.
mocha debug [spec..]
Run tests with Mocha
Rules & Behavior
--allow-uncaught Allow uncaught errors to propagate [boolean]
--async-only, -A Require all tests to use a callback (async) or
return a Promise [boolean]
--bail, -b Abort ("bail") after first test failure [boolean]
--check-leaks Check for global variable leaks [boolean]
--delay Delay initial execution of root suite [boolean]
--exit Force Mocha to quit after tests complete [boolean]
--forbid-only Fail if exclusive test(s) encountered [boolean]
--forbid-pending Fail if pending test(s) encountered [boolean]
--global, --globals List of allowed global variables [array]
--retries Retry failed tests this many times [number]
--slow, -s Specify "slow" test threshold (in milliseconds)
[number] [default: 75]
--timeout, -t, --timeouts Specify test timeout threshold (in milliseconds)
[number] [default: 2000]
--ui, -u Specify user interface [string] [default: "bdd"]
Reporting & Output
--color, -c, --colors Force-enable color output [boolean]
--diff Show diff on failure
[boolean] [default: true]
--full-trace Display full stack traces [boolean]
--growl, -G Enable Growl notifications [boolean]
--inline-diffs Display actual/expected differences
inline within each string [boolean]
--reporter, -R Specify reporter to use
[string] [default: "spec"]
--reporter-option, --reporter-options, Reporter-specific options
-O (<k=v,[k1=v1,..]>) [array]
Configuration
--config Path to config file [default: (nearest rc file)]
--opts Path to `mocha.opts` [string] [default: "./test/mocha.opts"]
--package Path to package.json for config [string]
File Handling
--exclude Ignore file(s) or glob pattern(s)
[array] [default: (none)]
--extension, --watch-extensions File extension(s) to load and/or watch
[array] [default: js]
--file Specify file(s) to be loaded prior to root
suite execution [array] [default: (none)]
--recursive Look for tests in subdirectories [boolean]
--require, -r Require module [array] [default: (none)]
--sort, -S Sort test files [boolean]
--watch, -w Watch files in the current working directory
for changes [boolean]
Test Filters
--fgrep, -f Only run tests containing this string [string]
--grep, -g Only run tests matching this string or regexp [string]
--invert, -i Inverts --grep and --fgrep matches [boolean]
Positional Arguments
spec One or more files, directories, or globs to test
[array] [default: ["test"]]
Other Options
--help, -h Show usage information & exit [boolean]
--version, -V Show version number & exit [boolean]
--interfaces List built-in user interfaces & exit [boolean]
--reporters List built-in reporters & exit [boolean]
✖ ERROR: Unknown "reporter": /mnt/c/Program Files/JetBrains/WebStorm 2019.2.4/plugins/NodeJS/js/mocha-intellij/lib/mochaIntellijReporter.js
Waiting for the debugger to disconnect...
Process finished with exit code 1
If I copy paste the first line into cmd though it runs. Seems to be an issue with quotes or something.
It doesn't work though, I get this:
C:\Users\iursino>C:\Users\iursino\AppData\Local\Microsoft\WindowsApps\ubuntu.exe run "export PATH=/home/iursino/n/bin:$PATH && /home/iursino/n/bin/node /mnt/c/workspace/project-name-redacted/node_modules/mocha/bin/_mocha --require ts-node/register --ui bdd --reporter \"/mnt/c/Program Files/JetBrains/WebStorm 2019.2.4/plugins/NodeJS/js/mocha-intellij/lib/mochaIntellijReporter.js\" /mnt/c/workspace/project-name-redacted/src/Filename.spec.ts --grep \"^invoke lambda Expect success result when invoking lambda$\""
/mnt/c/workspace/project-name-redacted/node_modules/ts-node/src/index.ts:245
return new TSError(diagnosticText, diagnosticCodes)
^
TSError: ⨯ Unable to compile TypeScript:
error TS2468: Cannot find global value 'Promise'.
../../workspace/project-name-redacted/src/Filename.spec.ts:3:8 - error TS1259: Module '"chai"' can only be default-imported using the 'esModuleInterop' flag
3 import chai, { expect } from 'chai'
~~~~
../../workspace/project-name-redacted/node_modules/#types/chai/index.d.ts:1921:5
1921 export = chai;
~~~~~~~~~~~~~~
This module is declared with using 'export =', and can only be used with a default import when using the 'esModuleInterop' flag.
../../workspace/project-name-redacted/src/Filename.spec.ts:4:8 - error TS1259: Module '"chai-as-promised"' can only be default-imported using the 'esModuleInterop' flag
4 import chaiAsPromised from 'chai-as-promised'
~~~~~~~~~~~~~~
../../workspace/project-name-redacted/node_modules/#types/chai-as-promised/index.d.ts:20:5
20 export = chaiAsPromised;
~~~~~~~~~~~~~~~~~~~~~~~~
This module is declared with using 'export =', and can only be used with a default import when using the 'esModuleInterop' flag.
../../workspace/project-name-redacted/src/Filename.spec.ts:9:1 - error TS2582: Cannot find name 'describe'. Do you need to install type definitions for a test runner? Try `npm i #types/jest` or `npm i #types/mocha`.
9 describe('invoke lambda', () => {
~~~~~~~~
../../workspace/project-name-redacted/src/Filename.spec.ts:25:5 - error TS2304: Cannot find name 'beforeEach'.
25 beforeEach(() => {
~~~~~~~~~~
../../workspace/project-name-redacted/src/Filename.spec.ts:30:5 - error TS2582: Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i #types/jest` or `npm i #types/mocha`.
30 it('Expect success result when invoking lambda', async () => {
~~
../../workspace/project-name-redacted/src/Filename.spec.ts:30:54 - error TS2705: An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option.
30 it('Expect success result when invoking lambda', async () => {
~~~~~~~~~~~~~
../../workspace/project-name-redacted/src/Filename.spec.ts:39:5 - error TS2582: Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i #types/jest` or `npm i #types/mocha`.
39 it('Expect error if lambda returns an error', async () => {
~~
../../workspace/project-name-redacted/src/Filename.spec.ts:39:51 - error TS2705: An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option.
39 it('Expect error if lambda returns an error', async () => {
~~~~~~~~~~~~~
../../workspace/project-name-redacted/src/Filename.spec.ts:48:5 - error TS2582: Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i #types/jest` or `npm i #types/mocha`.
48 it('Expect promise rejection if lambda returns an object as error (but not of type error)', async () => {
~~
../../workspace/project-name-redacted/src/Filename.spec.ts:48:98 - error TS2705: An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option.
48 it('Expect promise rejection if lambda returns an object as error (but not of type error)', async () => {
~~~~~~~~~~~~~
../../workspace/project-name-redacted/src/Filename.spec.ts:57:5 - error TS2304: Cannot find name 'afterEach'.
57 afterEach(() => {
~~~~~~~~~
at createTSError (/mnt/c/workspace/project-name-redacted/node_modules/ts-node/src/index.ts:245:12)
at reportTSError (/mnt/c/workspace/project-name-redacted/node_modules/ts-node/src/index.ts:249:19)
at getOutput (/mnt/c/workspace/project-name-redacted/node_modules/ts-node/src/index.ts:357:34)
at Object.compile (/mnt/c/workspace/project-name-redacted/node_modules/ts-node/src/index.ts:415:32)
at Module.m._compile (/mnt/c/workspace/project-name-redacted/node_modules/ts-node/src/index.ts:493:43)
at Module._extensions..js (internal/modules/cjs/loader.js:787:10)
at Object.require.extensions.(anonymous function) [as .ts] (/mnt/c/workspace/project-name-redacted/node_modules/ts-node/src/index.ts:496:12)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Module.require (internal/modules/cjs/loader.js:690:17)
at require (internal/modules/cjs/helpers.js:25:18)
at /mnt/c/workspace/project-name-redacted/node_modules/mocha/lib/mocha.js:330:36
at Array.forEach (<anonymous>)
at Mocha.loadFiles (/mnt/c/workspace/project-name-redacted/node_modules/mocha/lib/mocha.js:327:14)
at Mocha.run (/mnt/c/workspace/project-name-redacted/node_modules/mocha/lib/mocha.js:804:10)
at Object.exports.singleRun (/mnt/c/workspace/project-name-redacted/node_modules/mocha/lib/cli/run-helpers.js:207:16)
at exports.runMocha (/mnt/c/workspace/project-name-redacted/node_modules/mocha/lib/cli/run-helpers.js:300:13)
at Object.exports.handler.argv [as handler] (/mnt/c/workspace/project-name-redacted/node_modules/mocha/lib/cli/run.js:296:3)
at Object.runCommand (/mnt/c/workspace/project-name-redacted/node_modules/yargs/lib/command.js:242:26)
at Object.parseArgs [as _parseArgs] (/mnt/c/workspace/project-name-redacted/node_modules/yargs/yargs.js:1087:28)
at Object.parse (/mnt/c/workspace/project-name-redacted/node_modules/yargs/yargs.js:566:25)
at Object.exports.main (/mnt/c/workspace/project-name-redacted/node_modules/mocha/lib/cli/cli.js:63:6)
at Object.<anonymous> (/mnt/c/workspace/project-name-redacted/node_modules/mocha/bin/_mocha:10:23)
at Module._compile (internal/modules/cjs/loader.js:776:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:829:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
Why is it different in cmd and WebStorm? Another question: What's up with the error I get in cmd?
Edit: uploaded the cmd output in a redacted form.

Getting Error: spawn ./node_modules/.bin/grunt ENOENT when running grunt

I have a project that is started in development by
yarn start
It runs a index.js that starts a grunt process and get this error:
$ yarn start
yarn start v0.23.2
$ node ./development
grunt_arguments [ '--force', '--notify', '--verbose', '--debug', '--stack' ]
=======================================
Open http://localhost:8000 to start developing
events.js:141
throw er; // Unhandled 'error' event
^
Error: spawn ./node_modules/.bin/grunt ENOENT
at exports._errnoException (util.js:907:11)
at Process.ChildProcess._handle.onexit (internal/child_process.js:189:32)
at onErrorNT (internal/child_process.js:355:16)
at nextTickCallbackWith2Args (node.js:458:9)
at process._tickCallback (node.js:372:17)
at Function.Module.runMain (module.js:443:11)
at startup (node.js:139:18)
at node.js:990:3
error Command failed with exit code 1.
No idea what can it be. Environment is:
Win10
Running with MINGW64
I usually monkey patch child_process to help me debug that kind of issues. Add something like this in the beginning of your index.js file:
const util = require('util')
const childProcess = require("child_process");
const originalSpawn = childProcess.spawn;
childProcess.spawn = function() {
console.trace('SPAWN');
console.log('ARGS');
console.log(util.inspect(arguments, false, null)); // showHidden = false, depth = null
return originalSpawn.apply(this, arguments);
};
If your run, childProcess.spawn('ls', ['-lh', '/usr']) you will see something like:
Trace: SPAWN
at Object.childProcess.spawn (repl:2:9)
at myFunction (repl:2:14)
at repl:1:1
at REPLServer.defaultEval (repl.js:164:27)
at bound (domain.js:250:14)
at REPLServer.runBound [as eval] (domain.js:263:12)
at REPLServer.<anonymous> (repl.js:392:12)
at emitOne (events.js:82:20)
at REPLServer.emit (events.js:169:7)
at REPLServer.Interface._onLine (readline.js:210:10)
ARGS
{ '0': 'ls', '1': [ '-lh', '/usr' ] }
Maybe after running it you can update your question with the new information.

Found extra flags error in new version of protractor

I am trying to run a js scripts using protractor, but i am getting following error
C:\Users\Hoodi\AppData\Roaming\npm\node_modules\protractor\built\cli.js:172
throw new Error('Found extra flags: ' + unknownKeys.join(', '));
^
Error: Found extra flags: identityManagement
at Object.<anonymous> (C:\Users\Hoodi\AppData\Roaming\npm\node_modules\protractor\built\cli.js:172:15)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (C:\Users\Hoodi\AppData\Roaming\npm\node_modules\protractor\bin\protractor:5:1)
at Module._compile (module.js:570:32)
My config file
// conf.js
exports.config = {
framework: 'jasmine',
seleniumAddress: 'http://localhost:4444/wd/hub',
useAllAngular2AppRoots: true,
// Options to be passed to Jasmine-node.
jasmineNodeOpts: {
// Use colors in the command line report.
showColors: true,
// Default time to wait in ms before a test fails.
defaultTimeoutInterval: 60000,
},
onPrepare: function() {
require('../../lib/waitReady.js');
},
capabilities :{
browserName : 'chrome',
}
}
console.dir("argv: " + process.argv)
switch(process.argv[3]) {
case '--identityManagement':
exports.config.specs = ['./identityManagement.js'];
break;
default:
exports.config.specs = ['./identityManagement.js'];
}
I tried executing above script using protractor as well as "npm run" command, but in both cases i am getting same error. command that i used
protractor ./conf.js --identityManagement
and
npm run im
This actually works on my other system. npm and node version of system where this works are
node v7.2.1
npm v3.10.10
And where is doesnt work
node v7.4.0
npm v4.0.5
My package.json file looks like this
{
"name": "intelliflash",
"author": "Vishwanath Rawat <rawat#tegile.com>",
"description": "IntelliFlash tests",
"scripts": {
"im": "protractor ./conf.js --identityManagement"
}
}
Please help.
It has nothing to do with your npm or node versions, Latest release of Protractor 5.0 has put a check in cli for unidentified flags as you are putting with the help of process.argv.
You can solve this by disabling the flag checks:
protractor ./conf.js --identityManagement --disableChecks
For more details please refer the Protractor 5.0 changelog
Note: min node version now is v6.9.x which supports this version of protractor

Grunt reference error

Gruntfile.js
module.exports = functions(grunt)
{
grunt.initConfig({
//pkg: grunt.file.readJSON('package.json'),
concat: {
options: {
separator: ';',
},
dist: {
src: ['APIdocu/AccountsCollection.md', 'APIdocu/AccountsFollowersCollection.md'],
dest: 'APIdocu/ConcatApis.md',
//files: {
//'APIdocu/NewApi.md' : ['APIdocu/AccountsCollection.md', 'APIdocu/AccountsFollowersCollection.md']
},
},
});
grunt.loadNpmTasks('grunt-contrib-concat');
//tasks
grunt.registerTask('default', ["concat"]);
}
error message
Initializing
Command-line options: --verbose
Reading "Gruntfile.js" Gruntfile...OK
Registering Gruntfile tasks.
Loading "Gruntfile.js" tasks...ERROR
ReferenceError: grunt is not defined
at Object.<anonymous> (C:\Users\gs1460\Desktop\Markdownfiles\apis\Gruntfile.js:1:90)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at loadTask (C:\Users\gs1460Desktop\Markdownfiles\apis\node_modules\grunt\lib\grunt\task.js:323:10)
at Task.task.init (C:\Users\gs1460\Desktop\Markdownfiles\apis\node_modules\grunt\lib\grunt\task.js:437:5)
at Object.grunt.tasks (C:\Users\gs1460\Desktop\Markdownfiles\apis\node_modules\grunt\lib\grunt.js:120:8)
at Object.module.exports [as cli] (C:\Users\gs1460\Desktop\Markdownfiles\apis\node_modules\grunt\lib\grunt\cli.js:38:9)
Running tasks: concat:dist
Warning: Task "concat:dist" not found. Use --force to continue.
Aborted due to warnings.
How do I get rid of this error.
I need to concatenate md files to one.It gives me the above error. Tried changing the code many times. But same issue. Can you help in this.
Probably the problem is that you are writting functions instead of function.
Check also if the variable grunt is in the correct scope. And please use tabs correctly!
module.exports = function(grunt)
Regards.

Resources