Gulp-inject says "Nothing to inject into index.html" - javascript

I'm trying to inject some files in my index, all of them concatenated and minified into a .tmp folder, as follows:
gulp.task('prep-js',['clean'], function(){
var jspath = './src/page/**/*.js';
var treatJs = gulp.src(jspath)
.pipe(plugins.concat('scripts.js'))
.pipe(plugins.uglify())
.pipe(gulp.dest('.tmp/page/js'))
});
But when I run the injection task, it says "Nothing to inject into index.html". Here's the code:
gulp.task('inject-deps', ['prep-css', 'prep-js'], function(){
//select main bower files
var bowerDep = gulp.src(plugins.mainBowerFiles(), {read: false});
//inject files
return gulp.src('./src/page/index.html')
.pipe(plugins.inject(bowerDep, {relative: true, name:'bower'}))
.pipe(plugins.inject(gulp.src('.tmp/page/js/*.js'), {name:'frontjs'}))
.pipe(plugins.inject(gulp.src('.tmp/page/css/*.css'), {name:'frontcss'}))
.pipe(gulp.dest('.tmp/page'));
});
Interesting thing, the first pipe injecting the main bower files works perfectly, but it doesn't happen to the following two.
Also, just for information, 'plugins' is a variable which is requiring my plugins.
Any idea about this issue?

You need to return the stream in your prep-js task:
gulp.task('prep-js',['clean'], function(){
var jspath = './src/page/**/*.js';
return gulp.src(jspath)
.pipe(plugins.concat('scripts.js'))
.pipe(plugins.uglify())
.pipe(gulp.dest('.tmp/page/js'))
});
Otherwise inject-deps will not wait for prep-js to finish before it runs, meaning the concatenated and uglified JS files will not be in .tmp/page/js yet.
Relevant portion of the Gulp documentation:
Note: By default, tasks run with maximum concurrency -- e.g. it launches all the tasks at once and waits for nothing. If you want to create a series where tasks run in a particular order, you need to do two things:
give it a hint to tell it when the task is done,
and give it a hint that a task depends on completion of another.

Related

How do I make a gulp function run in series? (gulp-download)

I've been trying to set up functions to download and then install frameworks into my development workflow with gulp-download. Every time I run gulp-download in series, it always runs last, so the function tries to move the files, then they download.
I tried to use merge and run this in a single function, then split it and used a task in series to run it. Neither way is successful.
// DOWNLOAD BOOTSTRAP
function downloadBootstrap(cb) {
download('https://github.com/twbs/bootstrap/releases/download/v4.0.0/bootstrap-4.0.0-dist.zip')
.pipe(unzip())
.pipe(gulp.dest('downloads/bootstrap'));
cb();
}
// INSTALL BOOTSTRAT
function installBootstrap(cb) {
var css = gulp.src('downloads/bootstrap/css/*.{min.css,min.css.map}')
.pipe(dest('_developer/2-css/0-frameworks/bootstrap'))
var js = gulp.src('downloads/bootstrap/js/*.{min.js,min.js.map}')
.pipe(dest('_developer/3-js/0-frameworks/bootstrap'))
var clear = gulp.src('downloads/bootstrap', {read: false, allowEmpty: true})
.pipe(clean())
return merge(css, js, clear); // Combined src
cb();
}
gulp.task('bootstrap', gulp.series('downloadBootstrap', 'installBootstrap'));
You need to make sure you only call the callback function when your task is complete. Inside download, the function call returning doesn't mean the download has finished. However, since you're using a pipeline here, you can eliminate the callback parameter altogether. (On an unrelated note, I would avoid having two functions named download.)
// DOWNLOAD BOOTSTRAP
function download() {
return download('https://github.com/twbs/bootstrap/releases/download/v4.0.0/bootstrap-4.0.0-dist.zip')
.pipe(unzip())
.pipe(gulp.dest('downloads/bootstrap'));
}
Returning the stream will ensure that the stream has been fully processed before the next task continues. Also, you can just remove the callback from your install function since it will never actually be used. (Nothing runs after your function returns.)
I worked it out, I just had to add return to the download lol. Now I have the download finishing before it moves onto the install, but now only the css is migrated, the js remains and the clean isn't running. I had these working before.
gulp.task("bootstrap", gulp.series(downloadBootstrap, installBootstrap));
function downloadBootstrap() {
return download('https://github.com/twbs/bootstrap/releases/download/v4.0.0/bootstrap-4.0.0-dist.zip')
.pipe(unzip())
.pipe(gulp.dest('downloads/bootstrap'));
}
function installBootstrap() {
return gulp.src('downloads/bootstrap/css/*.{min.css,min.css.map}') // Gather [developer] css files
.pipe(gulp.dest('_developer/2-css/0-frameworks/bootstrap')) // Deliver css files to [build]
return gulp.src('downloads/bootstrap/js/*.{min.js,min.js.map}') // Gather [developer] css files
.pipe(gulp.dest('_developer/3-js/0-frameworks/bootstrap')) // Deliver css files to [build]
return gulp.src('downloads/bootstrap', { allowEmpty: true })
.pipe(clean());
}

How to execute a gulp task even if the file is unchanged

EDIT: Additional addition of code for task execution
I have a question I can't answer. I need gulp to execute a stain even if the file is unchanged. Currently only when I change my source file it recreates the new destination file. But I would like it to create it even if it hasn't changed. Thank's you in advance :)
Library external : "gulp-inject-string": "^1.1.2",
// Add timestamp in cache PWA
function pwa_cache() {
return src(`${paths.pwa}/serviceworker.tmp.js`)
.pipe(inject.prepend('const CACHE_VERSION = "pwa-v-'+ new Date().getTime() +'"; \n'))
.pipe(rename('serviceworker.js'))
.pipe(dest(`${paths.js}/pwa/`,{overwrite:true}))
}
// Generate all assets
const generateAssets = parallel(
styles,
scripts,
pwa_cache,
imgCompression
)
exports.default = series(generateAssets)
exports["generate-assets"] = generateAssets
Are you maybe running this task within a gulp.watch() ? If so, you'd need to stop the watch task and re-run it.
well I proceeded differently, if it can help someone, it's the only way I found and I don't have time to find another solution.
Instead of adding I rather assign the variable in my file and then I change its value, and I no longer work on a template file but directly on the original file.
Post and link that helped me find the answer: https://eureka.ykyuen.info/2015/07/13/gulp-rewrite-source-files-instead-of-creating-new-files/, How to inject variable value into JS file from GULP, Inject variable into html via Gulp Task
gulp file :
// Add timestamp in cache PWA
function pwa_cache() {
return src(`${paths.js}/pwa/serviceworker.js`, {base: './'})
.pipe(sourcemaps.init())
.pipe(replace(new RegExp('django-pwa-v-\\d*', 's'), 'django-pwa-v-'+ new Date().getTime()))
.pipe(sourcemaps.write('./'))
.pipe(dest('./'))
}
js file :
// Cache version don't touch string assigned to the variable /
CACHE_VERSION = "django-pwa-v-1580491632502";
/////////////////////////////////////////////////////////////

How do I detect when Emscripten's generated .js finishes loading the wasm so I can run my JS functions which call it?

I'm using Emscripten to compile some C code to WebAssembly. This is the final emcc call in my Makefile:
emcc $(CFLAGS) iva.a -o iva.js
Which works as intended and generates a .js file and a .wasm file. The JS is loaded into my HTML page as follows:
<script src="../dist/iva.js">
And it loads and instantiates the WebAssembly code iva.wasm properly. This message appears in the console soon after I load the page:
Fetch finished loading: GET "http://localhost:6931/dist/iva.wasm".
Which I take to mean that my WebAssembly is loaded through a fetch() and, perhaps pending some processing, I can access my functions through the console:
Module._init_display_system()
And get the return values. This holds true and everything works.
Clearly, I should be able to do this through a script as well. However, I can't see a way to only run a function after my WebAssembly has been instantiated. I get the feeling that I'm missing something rather obvious.
Anyway, how do I do this?
Use Module['onRuntimeInitialized'].
Module['onRuntimeInitialized'] = function() {
console.log("wasm loaded ");
var x=Module.ccall("doubleIt","number",["number"],[20]);
alert(x);
}
You have used emsdk, there are online WASM compilers like Wasmfiddle. Find my github repo useful for both the methods.
While the two solutions of Sudhakar RS and Anil8753 are totally fine, I want to add, that you have to execute this approach before you load your WebAssembly. Otherwise it might be too late to catch the event.
Besides that, there is another approach, which uses promises. If you add
-s MODULARIZE=1 -s 'EXPORT_NAME="createMyModule"'
as options when compiling with emcc, your resulting .js will contain the function createMyModule. This function will return a Promise that resolves as soon as your WebAssembly code is ready to use. Example usage:
In your HTML, add your WebAssembly as you already did:
<script src="../dist/iva.js">
In your js, call the function and after the promise resolved, you are good to go:
createMyModule().then(MyModule => {
console.log('WebAssembly loaded!');
// Access your functions (if bound by Embind):
console.log(MyModule.getSomething());
});
<script>
var Module = {
onRuntimeInitialized: function() {
console.log('module loaded');
}
};
</script>

Gulp Watch Not calling associated gulp task

So I'm coming back to a personal project after a (prolonged) break, and I'm getting back into the flow of things. One thing that smacks me in the face is that my watchers aren't working. If, for example, I call gulp watch-for-jshint, I expect JSHint to be changed anytime I modify a JS file -- either a root one (gulp.js) or one of my client-app ones (./client-app/js/controllers/register.js). That's not happening. I can see watch is starting, but it never calls JSHint when I change my files!
Anyone have any ideas what is going wrong or how to diagnose? As far as I can tell, I have the syntax right... And because (for testing purposes) I'm directly calling watch-for-jshint, I should be avoiding the usual pitfall of never actually calling my watcher.
Simplified gulp file:
var gulp = require('gulp'),
clean = require('gulp-clean'),
jshint = require('gulp-jshint'),
notify = require('gulp-notify'),
watch = require('gulp-watch'),
gulp.task('jshint', function(){
console.log("Running JSHint");
return gulp.src(['*.js', 'client-app/**/*.js'], ['jshint'])
.pipe(jshint({"moz":true}))
.pipe(jshint.reporter('default'))
.pipe(jshint.reporter('fail'))
.on('error', notify.onError({ sound: "Funk" }));
});
gulp.task('watch-for-jshint', function(){
return watch(['*.js', './client-app/**/*.js'], ['jshint']);
});
I've truncated a lot of extraneous tasks, but what's above should be everything relevant.
And naturally, 5 minutes after posting I notice one difference between my syntax and what a lot of questions are using. Most people are using gulp.watch, I was just following the syntax found at the gulp-watch NPM module page of using just watch.
Not... entirely sure why one works and the other doesn't; odd. Seems like the new version shouldn't work, since it's not referencing the gulp-watch module.
Remove the following line in gulp task, if it is not necessary.
.on('error', notify.onError({ sound: "Funk" }))
This makes the gulp task stop and show error. Hence watch is also stopped.
Replace
return watch(['*.js', './client-app/**/*.js'], ['jshint']);
with
gulp.watch(['*.js', './client-app/**/*.js'], ['jshint']);

Make Gulp task synchronous without creating a bunch of other tasks

So I am writing up my gulpfile.js and I have come to a point where I need to avoid JavaScript's asynchronous behavior. In short, this is for file-system read/write.
The problem is that all the solutions I have found online thus far create several sub-tasks; which is something I want to avoid so that I don't have to write any confusing documentation about what tasks should and shouldn't be used in the command line, and what order they need to be run in, etc.
My Question: How can I make the below script run each part synchronously, without creating sub-tasks?
gulp.task('rebuild', function(){
// Remove old build
gulp.src('build/', {read: false}).
pipe(rimraf());
// Copy all of the non generated files
gulp.src('src/**/*').
pipe(gulp.dest('build/'));
// Parse SASS/LESS and minify JS
build_styles();
build_scripts();
});
Well if all else fail, you can always fall back to the callback hell:
gulp.task('rebuild', function(){
// Remove old build
gulp.src('build/', {read: false}).
pipe(rimraf())
.on('end', function () {
// Copy all of the non generated files
gulp.src('src/**/*').
pipe(gulp.dest('build/'))
.on('end', function () {
// Parse SASS/LESS and minify JS
build_styles();
build_scripts();
});
});
});

Categories

Resources