gulp and babel with gulp-live-server - javascript

I'm trying to write an express server with ES6 and I'm using Babel to do the transpiling, but I'm having trouble getting it to work with gulp-live-server, as I can't make it restart properly when I change my files.
Currently I have the following:
// gulpfile.babel.js
import gulp from 'gulp';
import gls from 'gulp-live-server';
import babel from 'gulp-babel';
gulp.task('transpile', ['clean:server'], () => {
gulp.src(['server/**/*.js'])
.pipe(babel())
.pipe(gulp.dest('dist'));
});
gulp.task('server', ['transpile'], () => {
var server = gls.new('dist/app.js');
server.start();
gulp.watch(['server/**/*.js'], ['transpile']);
gulp.watch('dist/app.js', server.start.bind(server)); //error
});
But it's not working, this code returns a Gaze error:
internal/child_process.js:274
var err = this._handle.spawn(options);
^
TypeError: Bad argument
at TypeError (native)
at ChildProcess.spawn (internal/child_process.js:274:26)
at exports.spawn (child_process.js:339:9)
at Object.exports.start (/Users/oni/Documents/Projects/meanimo/node_modules/gulp-live-server/index.js:134:19)
at Gaze.<anonymous> (/Users/oni/Documents/Projects/meanimo/node_modules/gulp/node_modules/vinyl-fs/node_modules/glob-watcher/index.js:18:14)
at emitTwo (events.js:87:13)
at Gaze.emit (events.js:172:7)
at Gaze.emit (/Users/oni/Documents/Projects/meanimo/node_modules/gulp/node_modules/vinyl-fs/node_modules/glob-watcher/node_modules/gaze/lib/gaze.js:129:32)
at /Users/oni/Documents/Projects/meanimo/node_modules/gulp/node_modules/vinyl-fs/node_modules/glob-watcher/node_modules/gaze/lib/gaze.js:415:16
at StatWatcher._pollers.(anonymous function) (/Users/oni/Documents/Projects/meanimo/node_modules/gulp/node_modules/vinyl-fs/node_modules/glob-watcher/node_modules/gaze/lib/gaze.js:326:7)
The error has to do with the callback being passed to watch: server.start.bind(server), although that comes straight from the gls documentation...
I don't see my changes reflected and I can't seem to find any documentation on using gls with transpilers.
Please help.

OK I've fixed it and I'll share for posterity: for some reason, you have to wrap the server restart function on another function and execute it yourself. I think is has to do with the way Gaze is wrapping the subprocesses.
gulp.watch('dist/app.js', () => server.start());
That will do the trick.

Related

TypeError: Cannot read properties of undefined (reading 'getContractFactory') when testing contract

First question so bare with me if it is not very clear, but I'll try my best.
I am currently running through a youtube video to test my contract with hardhat, ethers, and waffle (https://www.youtube.com/watch?v=oTpmNEYV8iQ&list=PLw-9a9yL-pt3sEhicr6gmuOQdcmWXhCx4&index=6).
Here is the contract:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "#openzeppelin/contracts/token/ERC721/ERC721.sol";
contract MyContract is ERC721 {
constructor(string memory name, string memory symbol)
ERC721(name, symbol) {
}
}
And here is test.js:
const { expect } = require('chai');
describe("MyContract", function() {
it("should return correct name", async function() {
const MyContract = hre.ethers.getContractFactory("MyContract");
const myContractDeployed = await MyContract.deploy("MyContractName", "MCN");
await myContractDeployed.deployed();
expect(await myContractDeployed.name()).to.equal("MyContractName");
});
});
when I run "npx hardhat test" in the terminal it returns:
MyContract
1) should return correct name
0 passing (7ms)
1 failing
1) MyContract
should return correct name:
TypeError: Cannot read properties of undefined (reading 'getContractFactory')
at Context.<anonymous> (test\test.js:7:35)
at processImmediate (node:internal/timers:464:21)
My code matches the one from the video, and I am having a tough time understanding why I am getting a TypeError here. Any guidance is much appreciated!
EDIT:
I somehow fixed it, I dont understand how exactly it fixed it but it did. Instead of just installing
npm install #nomiclabs/hardhat-waffle ethereum-waffle chai #nomiclabs/hardhat-ethers ethers
I installed
npm install --save-dev #nomiclabs/hardhat-waffle ethereum-waffle chai #nomiclabs/hardhat-ethers ethers
Then the terminal printed
npm WARN idealTree Removing dependencies.#nomiclabs/hardhat-waffle in favor of devDependencies.#nomiclabs/hardhat-waffle
npm WARN idealTree Removing dependencies.ethereum-waffle in favor of devDependencies.ethereum-waffle
npm WARN idealTree Removing dependencies.#nomiclabs/hardhat-ethers in favor of devDependencies.#nomiclabs/hardhat-ethers
npm WARN idealTree Removing dependencies.ethers in favor of devDependencies.ethers
then I removed the hre in front of ethers.getContractFactory("MyContract") and it worked! If anyone would like to explain why this might have fixed it I'd be happy to read it, otherwise I am moving on.
Add the following code snippet at the top of your hardhat.config.js file
require("#nomiclabs/hardhat-waffle");
Sometimes it is because any of these dependencies below missing. Especially if you are using dotenv file and forgetting to import it. So, put these import statements on your hardhat.config or truffle.config file:
require("#nomicfoundation/hardhat-toolbox");
require("#nomiclabs/hardhat-ethers");
require("dotenv").config();
You needed to import hre in the test code.
const hre = require("hardhat");

Jest Call retries were exceeded

I have error in the following below test. My node version is : v12.10.0. is there any alternative of setTimeout?
test('demo code', async () => {
const cc = await projectSetup(project);
const onNotification = jest.fn();
cc.sendNotification();
await waitForExpect(() => {
expect(onNotification).toHaveBeenCalledTimes(2);
});
});
The Error log is as
Call retries were exceeded
at ChildProcessWorker.initialize (../../../node_modules/jest-worker/build/workers/ChildProcessWorker.js:230:21)
just add jest.useFakeTimers(); after your imports
...
jest.useFakeTimers();
test('demo code', async () => {
const cc = await projectSetup(project);
const onNotification = jest.fn();
cc.sendNotification();
await waitForExpect(() => {
expect(onNotification).toHaveBeenCalledTimes(2);
});
});
it works in my code
In my case, the actual problem was with the promise handling.
I got the same issue when I was running all my test cases in one go with the jest.
Solution:
Try running one test separately then see what error is coming.
I got the below error after running one problematic test separately where earlier I was getting the Call retries were exceeded:
[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "TypeError: Cannot read property 'code' of undefined".] {
code: 'ERR_UNHANDLED_REJECTION'
}
With this, I was sure that the problem is with the catch block and when I added it in the async service API function then the test case worked perfectly fine.
Maybe you can also try the same and see if it works for you or not.
I am using the below config:
node: 15.13.0
npm: 7.8.0
jest: 26.6.3
Try running npm doctor using the latest npm version. It's a great tool and it helped me diagnose permission and ownership issues right away.
Takeaway:
Verify File/Folder Permissions & Ownership
Encountered same error when updating the vue-jest version to below listed versions
#vue/vue3-jest: ^27.0.0-alpha.4
#vue/cli-plugin-unit-jest: ~5.0.0,
node: v17.9.0 or v16.14.2
Error disappeared, once downgraded it to node version v14.x.x
Hunch is - the latest node versions are not compatible with the dependencies.
I was able to run the test's successfully doing the following;
Install npm i -D jest-canvas-mock
Update the jest.config.ts file to have:
export default {
...
testEnvironment: "jsdom",
setupFiles: ["jest-canvas-mock"],
}

gulp : "TypeError: print is not a function"

I am trying to build Semantic-UI with gulp in a directory, but I get having these errors :
root#ks4000003:/var/www/mg.guylabbe.ca/web/inc/semantic# gulp build
[10:36:53] Using gulpfile /var/www/clients/client1/web179/web/inc/semantic/gulpfile.js
[10:36:53] Starting 'build'...
Building Semantic
[10:36:53] Starting 'build-javascript'...
Building Javascript
[10:36:54] 'build-javascript' errored after 19 ms
[10:36:54] TypeError: print is not a function
at Gulp.module.exports (/var/www/clients/client1/web179/web/inc/semantic/tasks/build/javascript.js:64:11)
at module.exports (/var/www/clients/client1/web179/web/inc/node_modules/orchestrator/lib/runTask.js:34:7)
at Gulp.Orchestrator._runTask (/var/www/clients/client1/web179/web/inc/node_modules/orchestrator/index.js:273:3)
at Gulp.Orchestrator._runStep (/var/www/clients/client1/web179/web/inc/node_modules/orchestrator/index.js:214:10)
at Gulp.Orchestrator.start (/var/www/clients/client1/web179/web/inc/node_modules/orchestrator/index.js:134:8)
at runNextSet (/var/www/clients/client1/web179/web/inc/node_modules/run-sequence/index.js:124:15)
at runSequence (/var/www/clients/client1/web179/web/inc/node_modules/run-sequence/index.js:136:2)
at Gulp.module.exports (/var/www/clients/client1/web179/web/inc/semantic/tasks/build.js:49:3)
at module.exports (/var/www/clients/client1/web179/web/inc/node_modules/orchestrator/lib/runTask.js:34:7)
at Gulp.Orchestrator._runTask (/var/www/clients/client1/web179/web/inc/node_modules/orchestrator/index.js:273:3)
[10:36:54] 'build' errored after 21 ms
[10:36:54] TypeError in plugin "run-sequence(build-javascript)"
Message:
print is not a function
Stack:
TypeError: print is not a function
at Gulp.module.exports (/var/www/clients/client1/web179/web/inc/semantic/tasks/build/javascript.js:64:11)
at module.exports (/var/www/clients/client1/web179/web/inc/node_modules/orchestrator/lib/runTask.js:34:7)
at Gulp.Orchestrator._runTask (/var/www/clients/client1/web179/web/inc/node_modules/orchestrator/index.js:273:3)
at Gulp.Orchestrator._runStep (/var/www/clients/client1/web179/web/inc/node_modules/orchestrator/index.js:214:10)
at Gulp.Orchestrator.start (/var/www/clients/client1/web179/web/inc/node_modules/orchestrator/index.js:134:8)
at runNextSet (/var/www/clients/client1/web179/web/inc/node_modules/run-sequence/index.js:124:15)
at runSequence (/var/www/clients/client1/web179/web/inc/node_modules/run-sequence/index.js:136:2)
at Gulp.module.exports (/var/www/clients/client1/web179/web/inc/semantic/tasks/build.js:49:3)
at module.exports (/var/www/clients/client1/web179/web/inc/node_modules/orchestrator/lib/runTask.js:34:7)
at Gulp.Orchestrator._runTask (/var/www/clients/client1/web179/web/inc/node_modules/orchestrator/index.js:273:3)
If I check javascript.js file, gulp-print is correctly loaded :
var print = require('gulp-print');
and used (8th line below) :
// copy source javascript
gulp.src(source.definitions + '/**/' + globs.components + '.js')
.pipe(plumber())
.pipe(flatten())
.pipe(replace(comments.license.in, comments.license.out))
.pipe(gulp.dest(output.uncompressed))
.pipe(gulpif(config.hasPermission, chmod(config.permission)))
.pipe(print(log.created))
.pipe(uglify(settings.uglify))
.pipe(rename(settings.rename.minJS))
.pipe(gulp.dest(output.compressed))
.pipe(gulpif(config.hasPermission, chmod(config.permission)))
.pipe(print(log.created))
.on('end', function() {
gulp.start('package compressed js');
gulp.start('package uncompressed js');
callback();
})
;
Gulp version :
[10:42:25] CLI version 3.9.1
[10:42:25] Local version 3.9.1
Does anybody has thoughts on this problem?
Thank you!
gulpPrint function is default export, therefore, I need to add a bit of code while importing gulp dependencies. Replace :
var print = require('gulp-print');
by :
var print = require('gulp-print').default;
// usage
print();
so the gulpPrint(); function is renamed print();
or can also be used in the following way:
var print = require('gulp-print');
// usage
print.default()
In case of doubt, dump variable contents with console.log(print), for instance. It will help a lot to understand the logic behind it if you are a beginner like me.
Changes described in the first answer are already in semantic-ui guilpfile.js. However, I have got the same error while running gulp build.
The reason for that was the old version of gulp-print. After update to the newest version gulp was building fine:
npm install gulp-print#5.0.0 --save-dev

syntaxhighlighter - Building: loadReposFromCache(...).error is not a function

I am trying to use the plugin SyntaxHighlighter v4, but I cannot get the build process to work!
Following the instructions here, I get the following error:
$ ./node_modules/gulp/bin/gulp.js setup-project
[10:12:20] Requiring external module babel-register
[10:12:20] Using gulpfile C:\git\syntaxhighlighter\gulpfile.babel.js
[10:12:20] Starting 'setup-project:clone-repos'...
[10:12:20] 'setup-project:clone-repos' errored after 1.96 ms
[10:12:20] TypeError: loadReposFromCache(...).error is not a function
at loadRepos (C:/git/syntaxhighlighter/build/setup-project.js:39:48)
at Gulp.<anonymous> (C:/git/syntaxhighlighter/build/setup-project.js:48:5)
at module.exports (C:\git\syntaxhighlighter\node_modules\orchestrator\lib\runTask.js:34:7)
at Gulp.Orchestrator._runTask (C:\git\syntaxhighlighter\node_modules\orchestrator\index.js:273:3)
at Gulp.Orchestrator._runStep (C:\git\syntaxhighlighter\node_modules\orchestrator\index.js:214:10)
at Gulp.Orchestrator.start (C:\git\syntaxhighlighter\node_modules\orchestrator\index.js:134:8)
at C:\git\syntaxhighlighter\node_modules\gulp\bin\gulp.js:129:20
at _combinedTickCallback (internal/process/next_tick.js:67:7)
at process._tickCallback (internal/process/next_tick.js:98:9)
at Module.runMain (module.js:606:11)
(node:2532) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: ENOENT: no such file or directory, open 'C:\git\syntaxhighlighter\.projects-cache.json'
It seems not to be importing the github repository files to the /repos/ directory. Can I do this manually somehow? Is there another way to get this to build so I can use it? Or even find the built files like in v3?
Here is the function that's failing in build/setup-project.js
gulp.task('setup-project:clone-repos', 'Clones all repositories from
SyntaxHighlighter GitHub organization', () =>
loadRepos()
.then(R.filter(repo => !fs.existsSync(pathToRepo(repo))))
.then(R.filter(repo => repo.name !== 'syntaxhighlighter'))
.then(R.map(R.curry(cloneRepo)))
.then(Promise.all)
);
Tracing backward we see:
const loadReposFromCache = () => fs.readFile.promise(REPOS_CACHE, 'utf8').then(JSON.parse);
const loadRepos = () => loadReposFromCache().error(loadReposFromGitHub).then(R.map(R.pick(['clone_url', 'name'])));
function loadReposFromGitHub() {
const request = require('request');
const opts = {
url: 'https://api.github.com/orgs/syntaxhighlighter/repos?per_page=300',
json: true,
headers: { 'User-Agent': 'node.js' },
};
return new Promise((resolve, reject) =>
request(opts, (err, response) => {
if (err) return reject(err);
const json = response.body;
fs.writeFile(REPOS_CACHE, JSON.stringify(json, null, 2));
resolve(json);
})
);
}
There are a couple of issues in the build code for that project.
For the specific issue here, the Songbird wrapper on Bluebird promises doesn't seem to match up any more - hence the ".error is not a function" (on songbird, but ok on bluebird).
So replace .error with .catch or replace require('songbird') with require('bluebird')
In either case, that's just the start of your build woes...
I've added this to the project's issue tracking anyway, but here's what I did to get it to buiid:
https://github.com/karljacuncha/syntaxhighlighter/commit/dc015fa299d4d249e8518664e205a838c55372cf
The build broke again (April 2021). I forked the project from karljacuncha's answer and changed the call for fs.writeFile to fs.writeFileSync
https://github.com/BartJolling/syntaxhighlighter/commit/7dbd08203cba8ef3be72cbe1abbfb3475be19ef4
I also included other fixes I found in the larger community and I fixed the usage of the -output parameter as well.

Gulp-Coveralls returns 422, no TravisCI builds can be found

TravisCI builds are passing for my open-source project, and I'm now trying to integrate gulp-coveralls. On Coveralls.io, no builds can be found for my repository, even though Travis builds have run successfully since I added my repo to Coveralls.
'There have been no builds for this repo.'
When I try to run my gulp-coveralls gulp task, I get this error:
'Repo token could not be determined. Continuing without it.'
Error in plugin 'gulp-coveralls'
Bad response:422 {"message":"Couldn't find a repository matching this job.","error":true}
at handleError (/Users/sarah.green/angular-embedly/node_modules/gulp-coveralls/index.js:11:30)
at sendToCoverallsCallback (/Users/sarah.green/angular-embedly/node_modules/gulp-coveralls/index.js:19:9)
at /Users/sarah.green/angular-embedly/node_modules/gulp-coveralls/index.js:31:13
at Request._callback (/Users/sarah.green/angular-embedly/node_modules/gulp-coveralls/node_modules/coveralls/lib/sendToCoveralls.js:7:5)
at Request.self.callback (/Users/sarah.green/angular-embedly/node_modules/gulp-coveralls/node_modules/coveralls/node_modules/request/index.js:142:22)
at Request.EventEmitter.emit (events.js:98:17)
at Request.<anonymous> (/Users/sarah.green/angular-embedly/node_modules/gulp-coveralls/node_modules/coveralls/node_modules/request/index.js:856:14)
at Request.EventEmitter.emit (events.js:117:20)
at IncomingMessage.<anonymous> (/Users/sarah.green/angular-embedly/node_modules/gulp-coveralls/node_modules/coveralls/node_modules/request/index.js:808:12)
at IncomingMessage.EventEmitter.emit (events.js:117:20)
at _stream_readable.js:919:16
at process._tickCallback (node.js:419:13)
Here's what I've got so far:
gulp-coveralls in my dev dependencies in package.json
gulpfile.js:
var coveralls = require('gulp-coveralls');
...
gulp.task('coveralls', function () {
gulp.src('coverage/**/lcov.info')
.pipe(coveralls());
});
karma.conf.js:
coverageReporter: {
type : 'lcov',
dir : 'coverage/'
}
Github: https://github.com/lithiumtech/angular-embedly
I use Karma and PhantomJS to run my tests. The file coverage/lcov.info is definitely being generated. Any idea what could be going on?
Sarah,
What you are missing is a coveralls repository token. You must go to coveralls.io and create a login using your GitHub account. This will then pull all your repos into coveralls. Then for the repo that you want to use coveralls with, you turn coveralls on by clicking the "Off" switch.
Now click the "view on coveralls" button and it will show you your repo key. You can then set it up by creating a .coveralls.yml file and copying your keys into that file. This should solve your problem.
Maybe you have a mistake in your .coveralls.yml file. If you are using Travis CI, try this:
service_name: travis-ci
repo_token: token_given
and if you're using Travis Pro:
service_name: travis-pro
repo_token: token_given
I hope this will be useful.
For GitHub builds running in travis-ci.org you don't need a service name in your .coveralls.yml file, just the token. You don't need a passing build in Travis either, just successfully generated LCOV data and a plugin that sends it.
I had one issue with gulp-coveralls where the LCOV data was not sent properly to coveralls, when read from file using gulp.src. The only way I it would work finally was if the LCOV data was sent to the plugin directly, rather than using an intermediary file to store it to first.
To have both LCOV data piped to gulp-coveralls and have a JSON/HTML report, finally I resorted to lazy-pipe to create reusable steps.
The complete project can be found at GitHub's angular-logger
// .coveralls.yml
repo_token: the_token
var jasmine = require('gulp-jasmine');
var cover = require('gulp-coverage');
var coveralls = require('gulp-coveralls');
var lazypipe = require('lazypipe');
(..)
// gulpfile.js
var testAndGather = lazypipe()
.pipe(cover.instrument, {
pattern: ['src/**/*.js'],
debugDirectory: 'debug'
})
.pipe(jasmine, {includeStackTrace: true})
.pipe(cover.gather);
gulp.task('test', ['build'], function () {
gulp.src('spec/**/*spec.js')
.pipe(testAndGather())
.pipe(cover.format(['html']))
.pipe(gulp.dest('reports'));
});
gulp.task('travis', ['build'], function () {
gulp.src('spec/**/*spec.js')
.pipe(testAndGather())
.pipe(cover.format(['lcov']))
.pipe(coveralls()); // directly pipe into coveralls
});
Using:
"gulp-jasmine": "~2.0.1",
"gulp-coverage": "~0.3.35",
"gulp-coveralls": "~0.1.4",
"lazypipe": "~0.2.3"

Categories