Laravel Elixir: Use wildcard without combining - css

I have a folder, in resources/assets/sass that have 2 files 1.scss and 2.scss
I would want to do:
elixir(function (mix) {
.sass('*.scss', './public/css/');
});
And for that to generate 1.css and 2.css
I actually have more than 2 files and that's why I don't want to write them one by one. Any way to accomplish this? Thanks

Since you can write any JavaScript in the Gulpfile, you can use the 'glob' module to get the filenames, like this:
var elixir = require('laravel-elixir');
var glob = require('glob');
var path = require('path');
elixir(function (mix) {
for (let file of glob.sync('resources/assets/sass/*.scss')) {
mix.sass(path.basename(file), './public/css/');
}
});
It can be more advanced if needed - e.g. I'm using it with versioning and custom paths (and ES2015 syntax):
const elixir = require('laravel-elixir');
const glob = require('glob');
const path = require('path');
elixir(mix =>
{
let build_files = [];
for (let theme of glob.sync('resources/assets/sass/themes/*/')) {
theme = path.basename(theme);
mix.sass(`themes/${theme}/app.scss`, `public/css/${theme}/app.css`);
build_files.push(`css/${theme}/app.css`);
}
mix.version(build_files);
});

Related

Switch output folder based on filename in gulp task

I have different *.scss files in my src folder and I want one file to be compiled in its own separate folder.
Lets assume I have the files normalFile_1.scss, specialFile.scss, normalFile_2.scss. I want the two normal files to be compiled to the folder Public/Css, the special file however should end up in the folder Public/Css/Special.
I have tried to get the current filename in the task with gulp-tap, which works fine.
.pipe($.tap(function (file, t) {
filename = path.basename(file.path);
console.log(filename); //outputs normalFile_1.css, specialFile.css, normalFile_2.css
}))
And with gulp-if I then wanted to switch the output folder based on the filename variable (PATHS.dist is the output "root" folder Public):
.pipe($.if(filename == 'specialFile.css', gulp.dest(PATHS.dist + '/Css/Special'), gulp.dest(PATHS.dist + '/Css')));
But everything still ends up in the Public/Css folder. Why does this not work? Is this even a good way of trying to accomplish that or are there better methods?
There are two ways to do this shown below:
var gulp = require("gulp");
var sass = require("gulp-sass");
var rename = require("gulp-rename");
var path = require('path');
gulp.task('sass', function () {
return gulp.src('src/*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(rename(function (path) {
if (path.basename == "specialFile") {
path.dirname = "Special";
}
}))
.pipe(gulp.dest('Public/Css'))
// .pipe(gulp.dest(function(file) {
// var temp = file.path.split(path.sep);
// var baseName = temp[temp.length - 1].split('.')[0];
// console.log(baseName);
// if (baseName == "specialFile") {
// return 'Public/Css/Special';
// }
// else return 'Public/Css';
// }))
});
gulp.task('default', ['sass']);
Obviously I suggest the rename version.
[Why a simple file.stem or file.basename doesn't work for me in the gulp.dest(function (file) {} version I don't know - that would certainly be easier but I just get undefined.]

Why is gulp injecting the css styles in the wrong directory?

I am pretty new to Gulp.
I'm working in a project that uses gulp and when I run gulp serve in the console and make some changes in my sass files, gulp inject the styles in the wrong directory:
[09:39:26] gulp-ruby-sass: write ../../../../../cjdelgado/AppData/Local/Temp/gulp-ruby-sass/index.css
[09:39:26] gulp-ruby-sass: write ../../../../../cjdelgado/AppData/Local/Temp/gulp-ruby-sass/index.css.
And this doesn't happen to my coworkers.
Could this be happening because my node or ruby versions?
Can I change that path manually? And, Should I change it?
This is my gulp file:
/**
* Welcome to your gulpfile!
* The gulp tasks are split into several files in the gulp directory
* because putting it all here was too long
*/
'use strict';
var fs = require('fs');
var gulp = require('gulp');
/**
* This will load all js or coffee files in the gulp directory
* in order to load all gulp tasks
*/
fs.readdirSync('./gulp').filter(function(file) {
return (/\.(js|coffee)$/i).test(file);
}).map(function(file) {
require('./gulp/' + file);
});
/**
* Default task clean temporaries directories and launch the
* main optimization build task
*/
gulp.task('default', ['clean'], function () {
gulp.start('build');
});
And I am running it from:
/c/Users/cjdelgado/Documents/Gitlab/register
And this is my gulp/inject.js file, wich I think the problem could be solved from:
'use strict';
var path = require('path');
var gulp = require('gulp');
var conf = require('./conf');
var $ = require('gulp-load-plugins')();
var wiredep = require('wiredep').stream;
var _ = require('lodash');
var browserSync = require('browser-sync');
gulp.task('inject-reload', ['inject'], function() {
browserSync.reload();
});
gulp.task('inject', ['scripts', 'styles'], function () {
var injectStyles = gulp.src([
path.join(conf.paths.tmp, '/serve/app/**/*.css'),
path.join('!' + conf.paths.tmp, '/serve/app/vendor.css')
], { read: false });
var injectScripts = gulp.src([
path.join(conf.paths.src, '/app/**/*.module.js'),
path.join(conf.paths.src, '/app/**/*.js'),
path.join('!' + conf.paths.src, '/app/**/*.spec.js'),
path.join('!' + conf.paths.src, '/app/**/*.mock.js'),
])
.pipe($.angularFilesort()).on('error', conf.errorHandler('AngularFilesort'));
var injectOptions = {
ignorePath: [conf.paths.src, path.join(conf.paths.tmp, '/serve')],
addRootSlash: false
};
return gulp.src(path.join(conf.paths.src, '/*.html'))
.pipe($.inject(injectStyles, injectOptions))
.pipe($.inject(injectScripts, injectOptions))
.pipe(wiredep(_.extend({}, conf.wiredep)))
.pipe(gulp.dest(path.join(conf.paths.tmp, '/serve')));
});

How to set up react-native integration test

In react-native doc, it says to check UIExploreIntegrationTest. It seems that it requires some setup on Xcode as it uses Objective C code(*.m). I'm new on Obj-C test.. May I know how to set up the integration test on Xcode?
With some guesswork I was able to nail down a few steps to get integration tests running on iOS. However I'm still figuring out how to get Android integration tests working.
Go ahead and copy IntegrationTests.js from the RN github and make a new JS file called Tests.js
Place both of these files in the root of your project. Then change IntegrationTests.js by going down and changing all of their requires to just one require statement for the file you just created require('./Tests')
Here is a basic implementation of what your Tests.js file should look like:
'use strict';
var React = require('react');
var ReactNative = require('react-native');
var {
Text,
View,
} = ReactNative;
var { TestModule } = ReactNative.NativeModules;
var Tests = React.createClass({
shouldResolve: false,
shouldReject: false,
propTypes: {
RunSampleCall: React.PropTypes.bool
},
getInitialState() {
return {
done: false,
};
},
componentDidMount() {
if(this.props.TestName === "SomeTest"){
Promise.all([this.SomeTest()]).then(()=>
{
TestModule.markTestPassed(this.shouldResolve);
});
return;
}
},
async SomeTest(){
var one = 1;
var two = 2;
var three = one + two;
if(three === 3){
this.shouldResolve = true;
}else{
this.shouldResolve = false;
}
}
render() : ReactElement<any> {
return <View />;
}
});
Tests.displayName = 'Tests';
module.exports = Tests;
Here is a basic implementation of your Tests.m file (inside xcode)
#import <UIKit/UIKit.h>
#import <XCTest/XCTest.h>
#import <RCTTest/RCTTestRunner.h>
#import "RCTAssert.h"
#define RCT_TEST(name) \
- (void)test##name \
{ \
[_runner runTest:_cmd module:##name]; \
}
#interface IntegrationTests : XCTestCase
#end
#implementation IntegrationTests
{
RCTTestRunner *_runner;
}
- (void)setUp
{
_runner = RCTInitRunnerForApp(#"IntegrationTests", nil);
}
- (void)test_SomeTest
{
[_runner runTest:_cmd
module:#"Tests"
initialProps:#{#"TestName": #"SomeTest"}
configurationBlock:nil];
}
#end
Also you need to add RCTTest from node_modules/react-native/Libraries/RCTTest/RCTTest.xcodeproj to your libraries. then you need to drag the product libRCTTest.a of that project you added to Linked Frameworks and Libraries for your main target in the general tab.
^^ that path might be slightly incorrect
Then you need to edit your scheme and set an environment variable CI_USE_PACKAGER to 1
So if you do all those steps you should have a simple test run and pass. It should be fairly easy to expand after that. Sorry if my answer is slightly sloppy, let me know if you have any questions.

Theme Development: Adding custom handle bar helpers

For the techno theme I wanted to make custom hb helpers and configuration available to users. To do this I applied an override to the [ghost root]/index.js.
The code below searches for index.js in the current theme folder and runs it.
var ghost = require('./core'),
errors = require('./core/server/errorHandling');
ghost()
.then(function (param) {
var settings = require('./core/server/api').settings;
settings
.read({key: 'activeTheme', context: {internal: true}})
.then(function (result) {
try {
require('./content/themes/' + result.value + '/index')();
}
catch (e) {
//No custom index found, or it wasn't a proper module.
}
});
})
.otherwise(function (err) {
errors.logErrorAndExit(err, err.context, err.help);
});
The theme level index.js injects custom blog variables (from a config file) and hb helpers.
var hbs = require('express-hbs'),
_ = require('lodash'),
downsize = require('downsize'),
blogVariable = require('../../../core/server/config/theme');
module.exports = function() {
//This block allows configuration to be available in the hb templates.
var blogConfig = blogVariable();
var config = require('./config') || {};
blogConfig.theme = config;
//console.log(JSON.stringify(blogConfig));
////Custom hb helpers////
hbs.registerHelper('excerpt', function (options) {
...
return new hbs.handlebars.SafeString(excerpt);
});
...
};
An example of using the custom blog variables is below.
<ul class="list-inline">
<li><i class="fa fa-fw fa-github"></i>
</li>
...
Is there a better way to do this in Ghost 0.4.2? I do not like having users override the ghost core index.js file.
There is a blog post explaining how to do this only by modifying the config.js file, and adding a file to the root directory. I agree with the author that this is more likely to be update-proof. http://zackehh.com/safely-creating-custom-handlebars-helpers/
Add:
require('./helpers')();
To the top of config.js
And add helpers to your helpers.js file like so:
var hbs = require('express-hbs');
module.exports = function(){
hbs.registerHelper('json', function(context) {
return JSON.stringify(context);
});
};
Unfortunately not, there was a post about this a little while ago on the forums, however you can add your own helpers.js file to the core folder for example...
var hbs = require('express-hbs')
// quick function for an example
registerHelper = function(){
hbs.registerHelper('ifNthItem', function(nthItem, currentCount, offset, options) {
if((currentCount+ offset)%(nthItem) == 0) {
return options.fn(this);
} else {
return options.inverse(this);
}
});
};
module.exports = registerHelper;
Then just link this into the index.js
var when = require('when'),
bootstrap = require('./bootstrap'),
scopa = require('./helpers');
scopa();
At least this way your not modifying the core index.js but the helpers.js instead.

Browserify - multiple entry points

I am using Browserify within gulp. I am trying to compile down my tests to a single file as well. But unlike my main app, which I have working just fine, I am having trouble getting the tests to compile. The major difference is the tests have multiple entry points, there isn't one single entry point like that app. But I am getting errors fro Browserify that it can't find the entry point.
browserify = require 'browserify'
gulp = require 'gulp'
source = require 'vinyl-source-stream'
gulp.task 'tests', ->
browserify
entries: ['./app/js/**/*Spec.coffee']
extensions: ['.coffee']
.bundle
debug: true
.pipe source('specs.js')
.pipe gulp.dest('./specs/')
Below is a task I was able to build that seems to solve the problem. Basically I use an outside library to gather the files names as an array. And then pass that array as the entry points
'use strict;'
var config = require('../config');
var gulp = require('gulp');
var plumber = require('gulp-plumber');
var glob = require('glob');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
gulp.task('tests', function(){
var testFiles = glob.sync('./spec/**/*.js');
return browserify({
entries: testFiles,
extensions: ['.jsx']
})
.bundle({debug: true})
.pipe(source('app.js'))
.pipe(plumber())
.pipe(gulp.dest(config.dest.development));
});
Here's an alternate recipe that fits more with the gulp paradigm using gulp.src()
var gulp = require('gulp');
var browserify = require('browserify');
var transform = require('vinyl-transform');
var concat = require('gulp-concat');
gulp.task('browserify', function () {
// use `vinyl-transform` to wrap around the regular ReadableStream returned by b.bundle();
// so that we can use it down a vinyl pipeline as a vinyl file object.
// `vinyl-transform` takes care of creating both streaming and buffered vinyl file objects.
var browserified = transform(function(filename) {
var b = browserify(filename, {
debug: true,
extensions: ['.coffee']
});
// you can now further configure/manipulate your bundle
// you can perform transforms, for e.g.: 'coffeeify'
// b.transform('coffeeify');
// or even use browserify plugins, for e.g. 'minifyiy'
// b.plugins('minifyify');
// consult browserify documentation at: https://github.com/substack/node-browserify#methods for more available APIs
return b.bundle();
});
return gulp.src(['./app/js/**/*Spec.coffee'])
.pipe(browserified)/
.pipe(concat('spec.js'))
.pipe(gulp.dest('./specs'));
});
gulp.task('default', ['browserify']);
For more details about how this work, this article that I wrote goes more in-depth: http://medium.com/#sogko/gulp-browserify-the-gulp-y-way-bb359b3f9623
For start, you can write a suite.js to require all the tests which you want to run and browserify them.
You can see two examples from my project https://github.com/mallim/sbangular.
One example for grunt-mocha-phantomjs
https://github.com/mallim/sbangular/blob/master/src/main/resources/js/suite.js
One example for protractor
https://github.com/mallim/sbangular/blob/master/src/main/resources/js/suite.js
This is just a start and I am sure there are more fancy ways available.
A little more complicated example to build files by glob pattern into many files with watching and rebuilding separated files. Not for .coffee, for es2015, but not a big difference:
var gulp = require("gulp");
var babelify = require("babelify");
var sourcemaps = require("gulp-sourcemaps");
var gutil = require("gulp-util");
var handleErrors = require("../utils/handleErrors.js");
var browserify = require("browserify");
var eventStream = require("event-stream");
var glob = require("glob");
var source = require("vinyl-source-stream");
var buffer = require("vinyl-buffer");
var watchify = require("watchify");
var SRC_PATH = "./src";
var BUILD_PATH = "./build";
var bundle = function (bundler, entryFilepath) {
console.log(`Build: ${entryFilepath}`);
return bundler.bundle()
.on("error", handleErrors)
.pipe(source(entryFilepath.replace(SRC_PATH, BUILD_PATH)))
.pipe(buffer())
.on("error", handleErrors)
.pipe(
process.env.TYPE === "development" ?
sourcemaps.init({loadMaps: true}) :
gutil.noop()
)
.on("error", handleErrors)
.pipe(
process.env.TYPE === "development" ?
sourcemaps.write() :
gutil.noop()
)
.on("error", handleErrors)
.pipe(gulp.dest("."))
.on("error", handleErrors);
};
var buildScripts = function (done, watch) {
glob(`${SRC_PATH}/**/[A-Z]*.js`, function (err, files) {
if (err) {
done(err);
}
var tasks = files.map(function (entryFilepath) {
var bundler = browserify({
entries: [entryFilepath],
debug: process.env.TYPE === "development",
plugin: watch ? [watchify] : undefined
})
.transform(
babelify,
{
presets: ["es2015"]
});
var build = bundle.bind(this, bundler, entryFilepath);
if (watch) {
bundler.on("update", build);
}
return build();
});
return eventStream
.merge(tasks)
.on("end", done);
});
};
gulp.task("scripts-build", function (done) {
buildScripts(done);
});
gulp.task("scripts-watch", function (done) {
buildScripts(done, true);
});
Complete code here https://github.com/BigBadAlien/browserify-multy-build

Resources