Getting imported .less files to update with au run --watch in Aurelia - gulp-watch

Sorry, this is quite hard to explain but I want to be able to change any less file (including imported ones) and have it update the site via watch.
I have a root level (from src) site.less file.
I also have various less files scattered around the src folder and am importing them from in the site.less file.
When I run au run --watch this inital build is updating css for my application successfully.
When I then update a less file it is triggering a refresh but the site is not updated with the changes.
In an attempt to resolve this, I have changed the watch file in aurelia_project/tasks/watch. -
I have made it so that when a less file is changed it only adds my root less file to the pendingRefreshPaths instead.
Now when I change and save an imported less file it is triggering a watch refresh adding in the appropriate files (including the root) but still not updating the site.
If I then open the root less file and save with no changes it is doing the same, no changes are shown.
The strange thing and clue to where I think I need to look is if I CHANGE the contents of the root less file and THEN save, it all works as expected.
As such I think I need to trick somewhere in the pipeline to make it think there is a real change to the root less file so that watches from other less files are actually successful.
Any ideas where it is ignoring unchanged files despite being in the pendingRefreshPaths?

Found the culprit, it is the changedInPlace function that was filtering it out.
As such if I remove this, now when I change any .less file it ques up the root .less file instead and this obviously imports and compiles the other files successfully.
export default function processCSS() {
return gulp.src(project.cssProcessor.source) <--- remove this
//.pipe(changedInPlace({firstPass:true}))
.pipe(plumber({ errorHandler: notify.onError('Error: <%= error.message %>') }))
.pipe(sourcemaps.init())
.pipe(less())
.pipe(build.bundle());
}
watch.ts
let watch = (callback?) => {
watchCallback = callback || watchCallback;
return gulpWatch(
Object.keys(watches),
{
read: false, // performance optimization: do not read actual file contents
verbose: true
},
(vinyl) => {
if (vinyl.path && vinyl.cwd && vinyl.path.startsWith(vinyl.cwd)) {
let pathToAdd = vinyl.path.substr(vinyl.cwd.length + 1);
if (pathToAdd.endsWith(".less")) {
log(`Watcher: Adding path src\\site.less to pending build changes...`);
// Crude but could be moved to config to define a root
pendingRefreshPaths.push("src\\site.less");
}
else {
log(`Watcher: Adding path ${pathToAdd} to pending build changes...`);
pendingRefreshPaths.push(pathToAdd);
}
refresh();
}
});
};

Related

The storage file is not properly formatted (Unexpected end of JSON) discord.js

I'm working on a giveaway bot and got that error. This is the full error
(node:4) UnhandledPromiseRejectionWarning: SyntaxError: The storage file is not properly formatted (Unexpected end of JSON input).
at GiveawaysManager.getAllGiveaways (/app/node_modules/discord-giveaways/src/Manager.js:308:27)
at async GiveawaysManager._init (/app/node_modules/discord-giveaways/src/Manager.js:391:30)
Here is my code:
const { GiveawaysManager } = require("discord-giveaways");
const manager = new GiveawaysManager(bot, {
storage: "./giveaways.json",
updateCountdownEvery: 10000,
default: {
botsCanWin: false,
embedColor: "#FF0000",
reaction: "🎉"
}
})
bot.giveawaysManager = manager;
}
})
I'm new to coding so it wil be great if you explain in baby steps
I had this same issue, and it turns out that the giveaways.json file only had a [] in it.
It is best if you just don't add a file because the module should add one for you!
The storage file is your ./giveaways.json. As seen in the npm documentation, it saves the file in JSON format which is highly likely to go wrong, make sure that you haven't touched the giveaways.json file, much less change it. Adding even a single line in the giveaways.json file may cause the GiveawaysManager to append wrongly and not be able to read it.
My suggestion is basically delete the ./giveaways.json file. This should refresh the file and be rid of all syntax errors unless it was from the npm module itself. Note that deleting it, will delete and therefore, stop all the giveaways in process, so make sure you have no giveaways in progress.
If this doesn't fix the issue, then delete the ./giveaways.json file again, and create a new ./giveaways.json file with this as it's contents:
{}

wagtail 'Page with this Path already exists.' error on attempting to create page manually

I have some code to create a Custom page object as part of a data import:
instance = PerformancePage(
run=run,
date=json_data['date'],
time=json_data['time'],
price=json_data['price'],
title=f'{run.title} {json_data["date"]} {json_data["id"]}',
content_type=ContentType.objects.get_for_model(PerformancePage)
)
perf = run.add_child(instance=instance)
and that sometimes raises:
django.core.exceptions.ValidationError: {'path': ['Page with this Path already exists.']}
A bit of debug code does show that there is another page out there with the same path:
except ValidationError:
print('error attempting to save', instance)
print('path', instance.path)
print('is leaf', run.is_leaf())
rivals = Page.objects.filter(path=instance.path)
print(rivals.last().specific.run == run)
Why might that be?
trying to manually increment the rival path to set a new path doesn't work either:
instance.path = rivals.last().specific._inc_path()
perf = run.add_child(instance=instance)
# still raises
Interestingly, if I just skip over those exceptions and continue my import,
when I print out those paths, they seem to follow a similar pattern:
path 00010001000T0005000D0001
path 00010001000T000800050001
path 00010001000T000900060001
path 00010001000T000A00050001
path 00010001000T000A00050001
path 00010001000T000A00070001
path 00010001000T000A00070001
path 00010001000T000A00030001
could that be relevant?
Looks like the in-memory parent "run" object was out of date. re-fetching it from the database before trying to add the child fixes the problem:
run = RunPage.objects.get(id=run.id)

Using VS 2015/gulp for versioning js files

I'm using VS 2015, ASP.NET 5 (MVC 6) and Gulp to write a SPA with angularjs and supplementary modules. My target framework is dnx451. I've read several best practices which state that the response from Index should have a strict no cache policy set, and all other resources (e.g. js, css, img) should all be heavily cached. In doing so, the browser always downloads the lightweight page and caches the scripts. When publishing, I am trying to have a gulp task which concats/uglifys all my JS files and outputs a single app.min.{version}.js (also for the less -> css file). This gives the benefit of always downloading the latest file version, but keeping them in cache while it is the latest and greatest.
Is there a way to get the Version (from project.json) and the build (from the * portion of project.json) from my gulp task? I am looking for a way to have the file {version} portion of the name match the version/build of the website.
I have seen examples of using process.env in gulp for VS environment variables, but am having trouble putting the pieces together to achieve the desired Version.Build format.
I have tried:
var project = require('./project.json');
gulp.task('js-publish', function(){
project.version; //this give 1.0.0-* (makes sense since its a string)
});
and
gulp.task('js-publish', function(){
process.env.BUILD_VERSION; //which is undefined
});
You want to use the gulp-rename NPM package to rename the file. Add gulp-rename to your package.json file. Here is an example of how it can then be used in your gulpfile.js:
var rename = require("gulp-rename");
// rename via string
gulp.src("./src/main/text/hello.txt")
.pipe(rename("main/text/ciao/goodbye.md"))
.pipe(gulp.dest("./dist")); // ./dist/main/text/ciao/goodbye.md
// rename via function
gulp.src("./src/**/hello.txt")
.pipe(rename(function (path) {
path.dirname += "/ciao";
path.basename += "-goodbye";
path.extname = ".md"
}))
.pipe(gulp.dest("./dist")); // ./dist/main/text/ciao/hello-goodbye.md
// rename via hash
gulp.src("./src/main/text/hello.txt", { base: process.cwd() })
.pipe(rename({
dirname: "main/text/ciao",
basename: "aloha",
prefix: "bonjour-",
suffix: "-hola",
extname: ".md"
}))
.pipe(gulp.dest("./dist")); // ./dist/main/text/ciao/bonjour-aloha-hola.md

Gulp - How do I control processing order with gulp-concat

I'm trying to generate combined JavaScript and CSS resources into a single file using gulp-concat using something like this:
var concatjs = gulp
.src(['app/js/app.js','app/js/*Controller.js', 'app/js/*Service.js'])
.pipe(concat('app.js'))
.pipe(gulp.dest('build'));
I get a concatted file with this, but the order of the javascript files embedded in the combined output file is random - in this case the controllers are showing up before the initial app.js file, which causes problems when trying to load the Angular app that expects app.js before any of the related resources are loaded. Likewise for CSS resources that get combined end up in random order, and again the order is somewhat important - ie. bootstrap needs to load before the theme and any custom style sheets.
How can I set up the concatenation process so that the order remains intact?
Update
So it turns out the ordering above DOES actually work by explicitly specifying the file order in the array of file specs. So in this case the crucial thing is to list app/js/app.js first, then let the rest of the scripts where order doesn't matter in in any order.
The reason I failed to see this behavior (Duh!) is that Gulp Watch was running and the gulpfile.js update wasn't actually reflected in the output. Restarting gulp did update the script. Neophyte error...
Other Thoughts:
Still wondering though - is this the right place to specify build order? It seems you're now stuffing application logic (load order) into the build script, which doesn't feel right. Are there other approaches to address this?
For an angular application like the one in your example (and it's dependency management), I normally use this kind of syntax: gulp.src(['app\js\app.js', 'app\js\**\*.js']).
You can also use just gulp.src('app\js\**\*.js') if your app.js file is the first one in alphabetic order.
I see your point about moving the load file order into the build script: I had the same feeling till I started using gulp-inject for injecting the unminified files references in my index.html at development time and injecting the bundled, minified and versioned ones in the production index file. Using that glob ordering solution across all my development cycle made so sense to me that i don't think to it anymore.
Finally, a possible solution for this 'ordering smell' can be using browserify but to me it is just complicating the architecture for an angular application: in the end, as you said, you just need that one specific file is called before all the other ones.
For my js i use a particular structure/naming convention which helps. I split it up into directories by feature, where each 'feature' is then treated as a separate encapsulated module.
So for my projects i have,
app/js/
- app.js
- app.routes.js
- app.config.js
/core/
- core.js
- core.controllers.js
- core.services.js
/test/
- .spec.js test files for module here
/feature1/
- feature1.js
- feature1.controllers.js
/feature2/
- feature2.js
- feature2.controllers.js
...
So each directory has a file of the same name that simply has the initial module definition in it, which is all that app.js has in it for the whole app. So for feature1.js
angular.module('feature1', [])
and then subsequent files in the module retrieve the module and add things (controllers/services/factories etc) to it.
angular.module('feature1')
.controller(....)
Anyway, i'll get to the point...
As i have a predefined structure and know that a specific file has to go first for each module, i'm able to use the function below to sort everything into order before it gets processed by gulp.
This function depends on npm install file and npm install path
function getModules(src, app, ignore) {
var modules = [];
file.walkSync(src, function(dirPath, dirs, files) {
if(files.length < 1)
return;
var dir = path.basename(dirPath)
module;
if(ignore.indexOf(dir) === -1) {
module = dirPath === src ? app : dir;
files = files.sort(function(a, b) {
return path.basename(a, '.js') === module ? -1 : 1;
})
.filter(function(value) {
return value.indexOf('.') !== 0;
})
.map(function(value) {
return path.join(dirPath, value);
})
modules = modules.concat(files);
}
})
return modules;
}
It walks the directory structure passed to it, takes the files from each directory (or module) and sorts them into the correct order, ensuring that the module definition file is always first. It also ignores any directories that appear in the 'ignore' array and removes any hidden files that begin with '.'
Usage would be,
getModules(src, appName, ignoreDirs);
src is the dir you want to recurse from
appName is the name of your app.js file - so 'app'
ignoreDirs is an array of directory names you'd like to ignore
so
getModules('app/js', 'app', ['test']);
And it returns an array of all the files in your app in the correct order, which you could then use like:
gulp.task('scripts', function() {
var modules = getModules('app/js', 'app', ['test']);
return gulp.src(modules)
.pipe(concat('app.js'))
.pipe(gulp.dest('build'));
});

Loading uncompressed js file in debug mode

Joomla has a feature where it loads the a minified javascript file and the uncompressed version when the site is in debug mode.
I have named both my files correctly and am include it as follows:
JHtml::_('script', JUri::root() . 'path_to_file/jquery-sortable.js');
When I put the site in debug mode, it does not load the uncompressed file.
However, If I use the following instead, it works fine:
JHtml::_('script', 'path_to_file/jquery-sortable.js');
Now I'm not sure whether this is a bug in Joomla or not, but I cannot find any information online regarding this. I would like to use JURI::root() in the path.
Does anyone have any information on this?
Indeed, if the script URL begins with http, the code that is responsible for including the uncompressed version (i.e, remove the min. segment if such exists or add -uncompressed otherwise) is ignored.
The source for this behavior:
JHtml::includeRelativeFiles() in libraries/cms/html/html.php:298
protected static function includeRelativeFiles($folder, $file, $relative, $detect_browser, $detect_debug)
{
// If http is present in filename
if (strpos($file, 'http') === 0)
{
$includes = array($file);
}
else
//process the script sourch.
}
...
}
Most of the script files, including frameworks, are included as relative paths. I guess that this behavior is meant to prevent remote resources from getting 404ed.

Resources