I am using Gulp to start a web application. I have the following basic code for my gulpfile.js:
var gulp = require('gulp'),
nodemon = require('gulp-nodemon');
gulp.task('default', function () {
nodemon({
script: 'server.js'
, ext: 'js html'
, env: { 'NODE_ENV': 'development' }
})
})
Using Gulp, I want to check for dependencies and if they are not available then install them and then run 'script.js'. How can this be done?
I have the following package.json:
{
"name": "sample-project",
"version": "1.0.0",
"description": "Displays users and user details",
"main": "server.js",
"dependencies": {
"jquery" : “>=1.5.1",
“bootstrap”: ">= 3.0.0”
}
"directories": {
"test": "test"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
"author": "Arihant Jain",
"license": "ISC"
}
You can run npm install independently from an executing task using node's child_process as such:
var gulp = require('gulp');
var nodemon = require('gulp-nodemon');
var child_process = require('child_process');
gulp.task('default', function () {
// Run npm install from the child process
child_process.exe('npm install', function(err, stdout, stderr){
// if everything goes well
if(!err){
// run nodemon
nodemon({
script: 'server.js'
, ext: 'js html'
, env: { 'NODE_ENV': 'development' }
})
}
});
})
Given your requirement:
Using Gulp, I want to check for dependencies and if they are not
available then install them...
That is exactly what npm install does. It checks the local package.json and proceeds to install missing packages.
So, I worked it around in a way by using gulp-run. I actually run the command npm install.
gulpfile looks like this:
var gulp = require('gulp'),
nodemon = require('gulp-nodemon')
run = require('gulp-run')
runSequence = require('run-sequence')
open = require('gulp-open');
gulp.task('default', function() {
runSequence('dependencies',
'start',
'uri');
});
gulp.task('dependencies', function() {
return run('npm install').exec();
})
gulp.task('uri', function(){
gulp.src(__filename)
.pipe(open({uri: 'http://localhost:3000/index.html'}));
});
gulp.task('start', function () {
nodemon({
script: 'server.js'
, ext: 'js html'
, env: { 'NODE_ENV': 'development' }
})
})
Related
Hi everbody I hope everyone is alright during this pandemic. I got 1 issue with my code my but my sass and autoprefixer are working fine only my scripts task wont stop whenever I save my main.js. I hope everyone can help me with this one. Thank You
const gulp = require('gulp');
const sass = require('gulp-sass');
const browserSync = require('browser-sync').create();
const autoprefixer = require('gulp-autoprefixer');
gulp.task('sass', function () {
return gulp.src('./scss/**/*.scss')
.pipe(sass({
errLogToConsole: true,
outputStyle: 'expanded'
}))
.on('error', console.error.bind(console))
.pipe(autoprefixer(['last 99 versions'], {cascade: true }))
.pipe(gulp.dest('./css/'))
.pipe(browserSync.stream());
});
// I think my script task its the problem
gulp.task('scripts', function() {
return gulp.src('./js/*.js')
.pipe(gulp.dest('./js/'))
.pipe(browserSync.stream());
});
gulp.task('html', function () {
return gulp.src('./*.html')
.pipe(browserSync.stream());
});
gulp.task('browserSync', function(){
browserSync.init({
server : {
baseDir : './'
}
});
gulp.watch('./scss/**.scss', gulp.series('sass'));
gulp.watch('./*.html', gulp.series('html'));
gulp.watch('./js/*.js', gulp.series('scripts'));
});
gulp.task('default', gulp.series('sass', 'scripts', 'html', 'browserSync'));
My Basic Directory Tree:
|-css
|-img
|-js
|- main.js
package.json:
{
"name": "horita",
"version": "1.0.0",
"description": "",
"main": "gulpfile.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"browser-sync": "^2.26.7",
"gulp": "^4.0.2",
"gulp-autoprefixer": "^6.1.0",
"gulp-sass": "^4.1.0"
}
}
On terminal you can see below that the task wont end it keeps on Finished and Starting.
UPDATE: index.js file content added.
I have this electron app that is executing some bash scrips(*.sh) files to perform some task.
Everything is working absolutely fine in the development environment but when building the production build for deb installer for Ubuntu platform, everything is working, like opening on the app, other NodeJS stuff, but bash scripts are not executing.
Problem Statement: How to execute shell scripts in the production build of an electron app for Linux(Ubuntu OS). Getting this error
app/terminal_scripts/timer.sh Not Found
Below are the detailed explanation for the app.
**Project Directory Setup**:
ProjectName
|
app > css | images | js | renders
terminal_scripts
node_modules
package.json
package-lock.json
Where inside the app directory, I have all CSS, images, js, HTML, and terminal scripts.
package.json:
{
"name": "timer",
"productName": "Timely",
"version": "1.0.25",
"description": "This desktop app shows you system clock",
"main": "app/js/main/index.js",
"scripts": {
"start": "electron .",
"test": "echo \"Error: no test specified\" && exit 1",
"watch": "nodemon --exec 'electron .'",
"dist": "electron-builder"
},
"homepage": ".",
"keywords": [
"Electron",
"Desktop App"
],
"author": "NotABot Ltd <contact#notabot.com>",
"contributors": [
{
"name": "Not A Bot",
"email": "nab#notabot.com"
}
],
"license": "ISC",
"dependencies": {
"desandro-matches-selector": "^2.0.2",
"electron-context-menu": "^1.0.0",
"electron-is": "^3.0.0",
"fix-path": "^3.0.0",
"isotope-layout": "^3.0.6",
"jquery": "^3.5.0",
"jquery-bridget": "^2.0.1"
},
"build": {
"appId": "com.test.timely",
"productName": "Timely",
"linux": {
"target": "deb",
"category": "System"
}
},
"devDependencies": {
"electron": "^8.1.1",
"electron-builder": "^22.6.0"
}
}
HTML:
<html>
<head>
<title>Timely</title>
</head>
<body>
<button onclick="displayTime()">Display Time</button>
<textarea rows="20" cols="90" id="command-output" disabled="true"></textarea>
<script>
const {app} = require('electron');
function displayTime(){
console.log("button clicked");
let cmd = `bash app/terminal_scripts/timer.sh`;
let completeMessage = 'This is the message';
backgroundProcess(cmd, completeMessage);
}
function getCommandOutput() { return document.getElementById("command-output"); };
function getStatus() { return document.getElementById("status"); };
function appendOutput(msg) { getCommandOutput().value += (msg+'\n'); };
function setStatus(msg) { getStatus().innerHTML = msg; };
function backgroundProcess(cmd, completeMessage){
const process = require('child_process');
var child = process.execFile(cmd, [] , {shell: true} );
appendOutput("Processing......");
child.on('error', function(err) {
appendOutput('stderr: '+err );
});
child.stdout.on('data', function (data) {
appendOutput(data);
});
child.stderr.on('data', function (data) {
appendOutput(data );
});
return new Promise((resolve, reject) => {
child.on('close', function (code) {
console.log(`code is: ${code}`);
if (code == 0){
setStatus(completeMessage);
resolve(1);
}
else{
setStatus('Exited with error code ' + code);
resolve(-1);
}
});
});
}
</script>
</body>
</html>
Bash Script:
#!/bin/bash
timer="$(date)"
echo "$timer"
Permission is set 777 for this shell file
Platform Information:
OS: Ubuntu 18.04.4 LTS
NodeJS: 13.6.0
NPM: 6.14.5
Electron: 8.1.1
Electron Builder: 22.6.0
index.js
const {app, BrowserWindow, Menu, Tray, ipcMain, MenuItem} = require('electron');
const path = require('path');
const contextMenu = require('electron-context-menu');
let splashWindow;
function createMainWindow(){
mainWindow = new BrowserWindow({
minHeight: 700,
minWidth: 800,
webPreferences: {
nodeIntegration: true,
webviewTag: true
},
show: false
});
//For dev only
// mainWindow.webContents.openDevTools();
mainWindow.loadFile('app/renderer/index.html');
mainWindow.maximize();
}
app.on('ready', () =>{
createMainWindow();
});
Another way is to move flies to a new directory outside app directory and call it as extraResources.
Inside that directory you can add all your bash files and for production you can use below method.
let urlPath = path.join(process.resourcesPath, '/extraResources/')
and then use let cmd = `${urlPath}timer.sh`;
I have created a new directory alongside the app directory called the termainal_scripts.
Inside this, I have my bash file timer.sh.
I figured out how to execute shell scripts, in production by using process.resourcesPath inside path.join().
So, let the fixed path be as:
let fixedURL = path.join(process.resourcesPath, '/terminal_scripts/');
Then the command to execute will be:
let cmd = `${fixedURL}timer.sh`
I am using craco with create react app and I would like to add a plugin only in DEV mode or by ENV Var
my craco.config looks is:
const path = require('path');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
module.exports = () => {
return {
webpack: {
alias: {
environment: path.join(
__dirname,
'src',
'environments',
process.env.CLIENT_ENV || 'production'
)
}
// plugins: [new BundleAnalyzerPlugin()]
},
jest: {
configure: {
testPathIgnorePatterns: ['<rootDir>/src/environments/'],
moduleNameMapper: {
environment: '<rootDir>/src/environments/test'
}
}
}
};
};
so I would like this BundleAnalyzerPlugin. only if the ENV param x =true or if NODE_ENV=test
while I trying to push to plugin array I got that plugin I undefined
module.exports.webpack.plugins.push(plugin)
You can set an environment variable right before any script command. For example, in your package.json, add a new line in the scripts paragraph that sets some variables:
"scripts": {
"start": "craco start",
"build": "craco build",
"test": "craco test",
"analyzer": "env NODE_ENV=production ANALYZER=test yarn start"
}
In craco.config.js you can simply use:
plugins: process.env.ANALYZER === 'test' ? [new BundleAnalyzerPlugin()] : []
Now, running npm run analyzer will both, set node env to production, set a variable ANALYZER to test (used later on) and load the craco config, that will start both the webpack server and the analyser.
you can use conditions from craco like when, whenDev, whenProd, whenTest
webpack: {
plugins: [...whenDev(() => [new BundleAnalyzerPlugin()], [])]
},
I'm new in ReactJS and Gulp... .
I have a problem with Gulp. my problem is that when I write gulp serve in terminal, in the browser, my page doesn't show anything and the page doesn't load completely and after a long time with loading status, the browser show me:
This webpage is not available
ERR_CONNECTION_TIMED_OUT
message.
I don't know whats my problem?
My package.json is:
{
"name": "projectOverview",
"version": "1.0.0",
"description": "",
"main": "gulpfile.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "gulp serve"
},
"author": "",
"license": "MIT",
"devDependencies": {
"react": "^0.13.2",
"gulp-react": "^3.0.1",
"gulp": "^3.8.11",
"gulp-connect": "^2.2.0",
"gulp-concat": "^2.5.2",
"gulp-open": "^0.3.2",
"gulp-browserify": "^0.5.1",
"reactify": "^1.1.0"
}
}
and I config gulpfile.js like as follow:
var gulp = require('gulp'),
connect = require('gulp-connect'),
open = require("gulp-open"),
browserify = require('gulp-browserify'),
concat = require('gulp-concat'),
port = process.env.port || 3031;
gulp.task('browserify', function(){
gulp.src('./app/src/js/components/main.js')
.pipe(browserify({ transform: 'reactify' }))
.pipe(gulp.dest('./app/dist/js'));
});
//launch browser in a part
gulp.task('open', function(){
var options = {
url: 'http://localhost:' + port,
};
gulp.src('./app/index.html')
.pipe(open('',options));
});
//live reload server
gulp.task('connect', function(){
connect.server({
root: 'app',
port: port,
livereload: true
});
});
//live reload js
gulp.task('js', function(){
gulp.src('./app/dist/**/*.js')
.pipe(connect.reload());
});
//live reload html
gulp.task('html', function(){
gulp.src('./app/*.html')
.pipe(connect.reload());
});
//watch files for live reload
gulp.task('watch', function(){
gulp.watch('app/dist/js/*.js', ['js']);
gulp.watch('app/index.html', ['html']);
gulp.watch('app/src/js/**/*.js', ['browserify']);
});
gulp.task('default', ['browserify']);
gulp.task('serve', ['browserify', 'connect', 'open', 'watch']);
Note that this is a Test project and the main.js file is empty and it just contain pragma:
/** #jsx React.DOM */
and It should be show ddddd message, if it successfully load.
I think my problem is in the paths that I set in index.html or gulpfile.js. but...
My problem was solved!
my mistake was from 2 part: 1.
I must run two command before calling gulp serve: first:
gulp
and after that,
npm i
in terminal.
2.
My Kerio VPN was enable during test. after disconnecting from VPN account, it works perfect! I think the kerio application and gulp port, has conflict... .
Background
I am very new to Node.js so please don't hate..
I found NPM very useful because I can install Node.js packages globally and then use them like standalone, available-on-path apps.
This does work on Windows, which really suprises me.
For instance I installed UglifyJS this way, via npm install -g uglifyjs and now I can run it from anywhere in my system, from the console via uglifyjs <rest of command> (not node uglifyjs .. or sth else).
I'd like to create my own stand-alone Node.js application. How do I get starded? I am asking here because most tutorials only cover how to write a simple script and then run it va node (which I already covered)
My current config
package.json:
{
"name": "hash",
"version": "1.0.0",
"author": "Kiel V.",
"engines": [
"node >= 0.8.0"
],
"main": "hash.js",
"dependencies": {
"commander" : "1.2.0"
},
"scripts": {
"start": "node hash.js"
}
}
hash.js:
var crypto = require('crypto'),
commander = require('commander');
/* For use as a library */
function hash(algorithm, str) {
return crypto.createHash(algorithm).update(str).digest('hex');
}
exports.hash = hash;
/* For use as a stand-alone app */
commander
.version('1.0.0')
.usage('[options] <plain ...>')
.option('-a, --algorithm [algorithm]', 'Hash algorithm', 'md5')
.parse(process.argv);
commander.args.forEach(function(plain){
console.log( plain + ' -> ' + hash(commander.algorithm, plain) );
});
Question:
Suppose I have only these two files in node-hash directory. How do I install this project, so that later I can run it in cmd.exe via hash -a md5 plaintext just like coffescript, jslint etc. installs ?
You have to add some code into package.json and hash.js, then you can run this command to install the package from local folder.
npm install -g ./node-hash
package.json
{
"name": "hash",
"version": "1.0.0",
"author": "Kiel V.",
"engines": [
"node >= 0.8.0"
],
"bin": {
"hash": "hash.js"
},
"main": "hash.js",
"dependencies": {
"commander" : "1.2.0"
},
"scripts": {
"start": "node hash.js"
}
}
hash.js
#!/usr/bin/env node
var crypto = require('crypto'),
commander = require('commander');
/* For use as a library */
function hash(algorithm, str) {
return crypto.createHash(algorithm).update(str).digest('hex');
}
exports.hash = hash;
/* For use as a stand-alone app */
commander
.version('1.0.0')
.usage('[options] <plain ...>')
.option('-a, --algorithm [algorithm]', 'Hash algorithm', 'md5')
.parse(process.argv);
commander.args.forEach(function(plain){
console.log( plain + ' -> ' + hash(commander.algorithm, plain) );
});