Currently I have a very simple Gulp build script:
const gulp = require('gulp');
const ts = require('gulp-typescript');
const tsProject = ts.createProject('tsconfig.json');
const del = require('del');
const nodemon = require('gulp-nodemon');
gulp.task('build-clean', function() {
return del('dist');
});
gulp.task('build', ['build-clean'], function () {
return gulp.src('src/**/*.ts')
.pipe(tsProject())
.pipe(gulp.dest('dist'));
});
gulp.task('start', ['build'], function () {
nodemon({
script: 'dist/app.js'
, ext: 'js html'
})
})
This reloads the page on changes to JS or HTML files.
This is useful for developing, but on production I want the exact opposite. If my files change, that's because of a git push to my server. That means Jenkins will run, after that's finished Jenkins will push the code to my webfolder.
I want to stop this nodemon server if Jenkins pushes the code, because a completely fresh gulp-build will be executed, including the Nodemon server.
So - how can I make nodemon exit after files change instead of restarting?
Maybe should you just use nodein production instead of nodemon
gulp.task('start', ['build'], function () {
node({
script: 'dist/app.js'
, ext: 'js html'
})
})
Related
I've been trying to get this straight for a few days now but haven't been able to get it working the way I need to. I'm unable to find any examples of other people using Browsersync with .net core, that may even be the reason I'm experiencing all of these issues. But I can't find any evidence that proves that and wouldn't understand why exactly that would be the case.
Anyway... I've got everything working in my gulp file exactly how I want it to for sass/js for handling errors, etc. I'm not new to gulp otherwise I'd blame my lack of experience for my inability to get this working.
Here's my gulp file followed by what the output is when running gulp.
Default Task:
const gulp = require("gulp"),
uglify = require("gulp-uglify"),
sass = require("gulp-sass"),
rename = require('gulp-rename'),
sassGlob = require('gulp-sass-glob'),
postcss = require('gulp-postcss'),
autoprefixer = require('gulp-autoprefixer'),
sourcemaps = require('gulp-sourcemaps'),
cleanCSS = require('gulp-clean-css'),
concat = require('gulp-concat'),
msbuild = require('gulp-msbuild'),
through = require('through2'),
notifier = require('node-notifier'),
browserSync = require('browser-sync').create();
// Static Server + watching scss/html files
gulp.task('serve', ['sass', 'compileJS'], function() {
browserSync.init({
proxy : {
target: "https://localhost:3000",
},
files: ['./wwwroot/css/*'],
rewriteRules: [
{
match: new RegExp('/css/main.min.css'),
fn: function() {
return './wwwroot/css/main.min.css'
}
}
]
});
//Watch for any changes to the scss files.
gulp.watch('./wwwroot/sass/**/*.scss', ['sass']);
//Watch for any changes to the js files, reload after those changes are made.
gulp.watch('./wwwroot/js/source/*.js', ['compileJS']).on('change', browserSync.reload);
//Watch for any changes to a .cshtml file and reload the browser if/when that change happens.
gulp.watch("./**/*.cshtml").on('change', browserSync.reload);
});
gulp.task('default', ['serve']);
/**
* Compiles SASS files and stores the result into the public folder
*/
gulp.task('sass', function () {
return gulp.src('./wwwroot/sass/main.scss')
.pipe(sassGlob())
.pipe(sass().on('error', function (err) {
console.log('Sass Error:', err.toString());
notifier.notify({
'title': 'Gettin\' Sassy 💁♀️',
'message': 'You goofed. Check your terminal window for more information.'
});
this.emit("end");
}))
.pipe(postcss([require('autoprefixer')]))
.pipe(
autoprefixer({
browsers: ['last 2 versions'],
cascade: false
})
)
.pipe(
through.obj(function(chunk, enc, cb) {
cb(null, chunk)
})
)
.pipe(cleanCSS({compatibility: 'ie8',
level: 2}))
.pipe(rename({suffix: '.min'}))
.pipe(gulp.dest('./wwwroot/css'))
.pipe(browserSync.stream());
});
/**
* Compiles the Javascript files and stores the result in the public folder
*/
gulp.task('compileJS', function (done) {
return gulp.src('./wwwroot/js/source/*.js')
.pipe(sourcemaps.init())
.pipe(concat('main.js'))
.pipe(uglify().on('error', function (err) {
console.log('JS Uglify Error:', err.toString());
notifier.notify({
'title': 'JS Compile Error',
'message': 'Something about your JS is a little off. Check yourself before you wreck yourself.'
});
this.emit("end");
}))
.pipe(rename({suffix: '.min'}))
.pipe(sourcemaps.write('../maps'))
.pipe(gulp.dest('./wwwroot/js/dist'));
});
Output:
$ gulp
[21:34:15] Using gulpfile
~/Repos/PROJECT_DIRECTORY/PROJECT_NAME/gulpfile.js
[21:34:15] Starting 'sass'...
[21:34:15] Starting 'compileJS'...
[21:34:15] Finished 'sass' after 437 ms
[21:34:15] Finished 'compileJS' after 426 ms
[21:34:15] Starting 'serve'...
[21:34:16] Finished 'serve' after 1 s
[21:34:16] Starting 'default'...
[21:34:16] Finished 'default' after 68 μs
[Browsersync] Proxying: https://localhost:3000
[Browsersync] Access URLs:
------------------------------------
Local: https://localhost:3000
External: https://10.0.0.137:3000
------------------------------------
UI: http://localhost:3001
UI External: http://localhost:3001
------------------------------------
[21:34:35] Starting 'sass'...
[Browsersync] 1 file changed (main.min.css)
[21:34:35] Finished 'sass' after 207 ms
[21:34:58] Starting 'compileJS'...
[21:34:58] Finished 'compileJS' after 154 ms
[Browsersync] Reloading Browsers...
So, looking at that output you would probably think to yourself, "This dude is an idiot... Browsersync states that it's reloading browsers..." Right, it does state that, but it is not reloading the browser. Browsersync also fails to inject my css into the browser as well.
As I mentioned, I've used gulp before, and this setup closely represents the gulp files that I use when doing Wordpress development as well. However, it won't work for this project (which has led me to my .net core / Visual Studio suspicions).
You could just do something like this
Create a env variable thats global to your application then above the closing tag in your view you can add the following code.
This code is how I do it in Laravel with my Blade templates but it should be exactly the same you just need to replace it with the way .NET does it, I think they use Razor templating engine :)
{{-- Live reload with browser sync --}}
#if (!empty(env('APP_ENV')) && env('APP_ENV') === 'local')
<script
async
defer
src="{{ URL::to('/') . ':3000/browser-sync/browser-sync-client.js?v=2.26.7'}}">
</script>
#endif
Hope this helps you.
Just for interest sake below is my gulp pipeline:
const browserSync = require("browser-sync");
const sass = require("gulp-sass");
const autoprefixer = require("gulp-autoprefixer");
const sourcemaps = require("gulp-sourcemaps");
const rename = require("gulp-rename");
const reviser = require("gulp-rev");
const runSequence = require("run-sequence");
gulp.task("browserSync", function() {
return browserSync.init({
open: false,
https: false,
notify: false,
injectChanges: true,
proxy: "http://{site-name-here}.local/",
});
});
gulp.task("compile:scss", function() {
return (
gulp
// Gets the main.scss file
.src("resources/assets/scss/main.scss")
// Passes it through a gulp-sass, log errors to console
.pipe(sass().on("error", sass.logError))
// Adds versioning
.pipe(reviser())
// Add vendor prefixes
.pipe(
autoprefixer({
browsers: ["last 2 versions"],
cascade: false
})
)
// Rename the file
.pipe(rename({ suffix: ".min" }))
// Outputs it in the css folder
.pipe(gulp.dest("public/css"))
// Add sourcemaps
.pipe(sourcemaps.write())
// Adds versioned file to manifest so we can access with the same name
.pipe(reviser.manifest("manifest/rev-manifest.json"), { merge: true })
// Outputs it in the css folder
.pipe(gulp.dest("public/css"))
.pipe(
browserSync.reload({
// Reloading with Browser Sync
stream: true
})
)
);
});
// Watchers
gulp.task("watch", function() {
gulp.watch(["./resources/assets/scss/**/*"], "compile:scss", browserSync.reload);
});
// Default task
gulp.task("start", function(callback) {
return runSequence(
"browserSync",
"compile:scss",
"watch",
callback
);
});
to use it I just run gulp start
Keep in mind that running gulp like this you will need to have gulp installed globally. to do this run npm install --global gulp-cli
I'm trying to run the 'rundev' task in the following gulp code but it keeps causing my Node/Gulp process to hang. I can't unhang them without restarting my computer so tracking down the problem has proven difficult.
const gulp = require("gulp");
const concat = require("gulp-concat");
const uglify = require("gulp-uglify");
const uglifycss = require("gulp-uglifycss");
const del = require("del");
const sass = require('gulp-sass');
const streamqueue = require('streamqueue');
const gzip = require('gulp-gzip');
const compression = require('compression');
const browserSync = require("browser-sync").create();
const scripts = require("./scripts");
const styles = require("./styles");
var devMode = false;
gulp.task("html", function() {
gulp.src("./src/html/**/*.html")
.pipe(gulp.dest("./dist/"))
/*.pipe(gzip({extension: 'gz'}))
.pipe(gulp.dest("./dist/"))*/
.pipe(browserSync.reload({
stream: true
}));
});
gulp.task("css", function() {
var cssRaw = gulp.src(styles["css"])
.pipe(uglifycss());
var cssFromSass = gulp.src(styles["scss"])
.pipe(sass({outputStyle: 'compressed'}));
return streamqueue({objectMode: true},
cssFromSass,
cssRaw)
.pipe(concat("allStyles.min.css"))
.pipe(gulp.dest("./dist/css"))
/*.pipe(gzip({extension: 'gz'}))
.pipe(gulp.dest("./dist/css"))*/
.pipe(browserSync.reload({
stream: true
}));
});
gulp.task("js", function() {
var jsMin = gulp.src(scripts["min"]);
var jsOther = gulp.src(scripts["other"])
.pipe(uglify());
return streamqueue({objectMode: true},
jsMin,
jsOther)
.pipe(concat("allScripts.min.js"))
.pipe(gulp.dest("./dist/js"))
/*.pipe(gzip({extension: 'gz'}))
.pipe(gulp.dest("./dist/js"))*/
.pipe(browserSync.reload({
stream: true
}));
});
gulp.task("fonts", function() {
gulp.src(["./src/fonts/**/*.eot",
"./src/fonts/**/*.svg",
"./src/fonts/**/*.ttf",
"./src/fonts/**/*.woff",
"./src/fonts/**/*.woff2"])
.pipe(gulp.dest("./dist/fonts"))
.pipe(browserSync.reload({
stream: true
}));
});
gulp.task("images", function() {
gulp.src(["./src/images/**/*.*"])
.pipe(gulp.dest("./dist/images"))
.pipe(browserSync.reload({
stream: true
}));
});
gulp.task("sounds", function() {
gulp.src(["./src/sounds/**/*.*"])
.pipe(gulp.dest("./dist/sounds"))
.pipe(browserSync.reload({
stream: true
}));
});
gulp.task("clean", function() {
return del('./dist/**', {read: false});
});
gulp.task("build", ['clean'], function() {
gulp.start(["css", "js", "html", "fonts", "images", "sounds"]);
});
gulp.task("browser-sync", function() {
browserSync.init(null, {
open: false,
server: {
baseDir: "dist",
middleware: compression()
}/*,
httpModule: 'http2',
https: true*/
});
});
gulp.task("rundev", function() {
devMode = true;
gulp.start(["build", "browser-sync"]);
gulp.watch(["./src/css/**/*.css", "./src/css/**/*.scss"], ["css"]);
gulp.watch(["./src/js/**/*.js"], ["js"]);
gulp.watch(["./src/html/**/*.html"], ["html"]);
gulp.watch(["./src/fonts/**/*.*"], ["fonts"]);
});
I recently picked this project back up after a month long break and haven't touched the code since, yet I've never had this issue before.
I have this problem when I try to run 'gulp rundev' in my Git Bash window. It appears to complete without errors but never actually serves the files and I can't use the Git Bash window or even close it afterwards (none of these work: clicking exit, Alt+F4, or killing the process in Task Manager). The only way to get rid of it is to restart the computer. I'm using Windows 10, Node v8.9.4, Gulp v3.9.1, Brackets, and Git Bash as my development environment in case that helps.
Here's a copy of the output:
MyName#MyComputer MINGW64 ~
$ cd Documents/GitHub/PoeFilterEditor
MyName#MyComputer MINGW64 ~/Documents/GitHub/PoeFilterEditor (Development)
$ gulp rundev
[12:11:27] Using gulpfile ~\Documents\GitHub\PoeFilterEditor\gulpfile.js
[12:11:27] Starting 'rundev'...
[12:11:27] Starting 'clean'...
[12:11:27] Starting 'browser-sync'...
[12:11:27] Finished 'browser-sync' after 114 ms
[12:11:28] Finished 'rundev' after 816 ms
[Browsersync] Access URLs:
--------------------------------------
Local: http://localhost:3000
External: http://192.168.1.142:3000
--------------------------------------
UI: http://localhost:3001
UI External: http://192.168.1.142:3001
--------------------------------------
[Browsersync] Serving files from: dist
I do remember getting more 'Starting' and 'Finished' lines in the output for the other tasks that are called by 'rundev' but otherwise the output looks normal.
Since the 'clean' task never reports as 'Finished' I assume the problem is somehow related to that and my research seems to indicate that the problem has something to do with permissions or the files being locked when it tries to operate on them. To this end, I've tried messing with the devMode, closing all programs except the Git Bash to call the task, and making sure everything is running with admin privileges, but it always hangs.
I'm a bit new to Node and Gulp so there may be something glaringly obvious that I don't even know to ask about, so hopefully someone here can help me learn my way through this.
My use case is pretty simple:
First I want to run node server.js(start my Node.js app) - and after Node has started - I want to run mocha test (running some tests on the API provided by previous server.js) by executing npm run test.
The script: "test": "NODE_ENV=development node server.js && mocha test"
Node starts, but unfortunately the mocha testdoes not seem to be executed:
So how can I execute mocha test after node server.js?
The reason why you're running into this is because node server.js continuously runs until killed (Ctrl + C) or a fatal unhandled exception occurs. Since the node process keeps running mocha test never get executed.
One approach to this would be to use gulp as a task runner and utilize tasks implementing gulp-nodemon and gulp-mocha. If you've never used Gulp before or are unfamiliar with task runners I suggest you read the docs beforehand just to get an idea of how it works.
Add the gulpfile.js below to your app (adjust some of the settings as necessary) and modify your package.json scripts with the test script below and this should solve your issue.
gulpfile.js
var gulp = require('gulp');
var mocha = require('gulp-mocha');
var nodemon = require('gulp-nodemon');
gulp.task('nodemon', (cb) => {
let started = false;
return nodemon({
script: 'server.js'
})
.on('start', () => {
if (!started) {
started = true;
return cb();
}
})
.on('restart', () => {
console.log('restarting');
});
});
gulp.task('test', ['nodemon'], function() {
return gulp.src('./test/*.js')
.pipe(mocha({reporter: 'spec' }))
once('error', function() {
process.exit(1);
})
.once('end', function() {
process.exit();
});
});
package.json scripts
{
"scripts": {
"test": "NODE_ENV=development gulp test"
}
}
Supertest Alternative
A more elegant solution ,and in my opinion the better option, would be to rewrite your tests to use supertest. Basically what you do with supertest is pass your Express instance to it and run assertions tests against it with the supertest package.
var mocha = require('mocha');
var request = require('supertest');
var server = require('server');
describe('test server.js', function() {
it('test GET /', function(done) {
request(server)
.get('/')
.expect(200, done);
});
});
add this code to your test case
after(function (done) {
done();
process.exit(1);
})
I have following hello World test to my __tests__ folder:
hello-test.js:
describe('hello world', function() {
it('basic test', function() {
expect(1).toBe(1);
});
});
My aim is to eventually write tests in es6 and run using a gulp task. I have tried running the above with the following gulp task:
gulp.task('jest', ['test-compile'], function(done){
jest.runCLI({
rootDir : __dirname,
//scriptPreprocessor : "../node_modules/babel-jest",
testFileExtensions : ["es6", "js"],
}, __dirname, function (result) {
if (result) {
console.log(result);
} else {
console.log('Tests Failed');
}
done();
});
});
I have also tried running jest using the globally install jest-cli and cannot get it to work, I also tried using the npm test way as shown on line but no matter which of these I try I just get Using Jest CLI v0.6.0 in the terminal, no errors no results.
I am very confused as I seem to be doing what all the doc's online say. I am using Node 4.2.1 if that has any bearing
I am currently trying to write a gulp task that allows me to serve development code up through a node webserver and use browser sync to reload the page. In doing so i'm attempting to use the events with nodemon, so for example when start event occurs, I want my gulp to log what its starting. Currently the events for gulp nodemon are not firing at all. No error is being thrown and the web server is starting. I'm not sure what I am doing wrong.
gulp.task('serve-dev', ['inject'], function(){
var isDev = true;
var nodeOptions = {
script: config.nodeServer,
delayTime: 1,
env: {
'PORT': port,
'NODE_ENV': isDev ? 'dev': 'build'
},
watch: ['server.js']
};
$.nodemon(nodeOptions)
.on('start', function(){
log('*** nodemon started');
// startBroswerSync();
})
.on('restart', function (ev){
log('*** nodemon restarted');
log('files changed on restart:\n' + ev);
})
.on('crash', function(){
log('Server Crashed for some reason');
})
.on('exit', function(){
log('Server Ended Cleanly');
})
Here is my config File:
module.exports = function() {
var client = './src/';
var temp = './.tmp/';
var server = './server.js';
var config = {
// Location of index.html
index: client + 'index.html',
// Temp folder
temp: temp,
// All of the js files to load
js: [
client + '**/*.module.js',
client + '**/*.js',
'!' + client + '**/*.spec.js'
],
// Root Folder of App(Where to find index.html etc...)
client: client,
// Where to find build Sass and CSS files
css: [temp + '*css', client + 'css/*.css'],
// All Js to Vet
alljs: [
'./src/**/*.js',
'./*js'
],
// Path to Node Server
server: server,
//Sass to Compile
sass: ['src/scss/*.scss'],
// Bower and NPM Locations
bower: {
json: require('./bower.json'),
directory: './bower_components/',
ignorePath: '../..'
},
// Node Settings
defaultPort: 7203,
nodeServer: './server.js'
};
config.getWiredepDefaultOptions = function() {
var options = {
bowerJson: config.bower.json,
directory: config.bower.directory,
ignorePath: config.bower.ignorePath
};
return options;
};
return config;
};
Completely Unrelated answer, log method was not functioning properly, thus no log statements....sorry