I'm using Gulp and the main-bower-files to bundle my bower dependencies.
I need to ensure that jQuery is included before AngularJS, but since the Angular bower package does not actually depend on jQuery it is included after.
Is there a way to push jQuery to the top of source list or override Angular's dependency so it does require jQuery?
I tried using the gulp-order plugin to do this but it messes up the original order of the remaining files:
gulp.task('bower', function () {
var sources = gulp.src(mainBowerFiles(['**/*.js', '!**/*.min.js'])); // don't include min files
return sources
// force jquery to be first
.pipe(plugins.order([
'jquery.js',
'*'
]))
.pipe(plugins.sourcemaps.init())
.pipe(plugins.concat('libs.min.js'))
.pipe(plugins.uglify())
.pipe(plugins.sourcemaps.write('./'))
.pipe(gulp.dest(config.output))
.pipe(plugins.notify({ message: 'Bower task complete' }));
});
You can override angulars dependencies in your project bower.json:
https://github.com/ck86/main-bower-files#overrides-options
{
...
"overrides": {
"angular": {
"dependencies": {
"jquery": "~1.8"
}
}
}
}
I haven't used main-bower-files but one trick I can think of is to just include the jquery file directly and don't load it in the main bower files array, e.g.
var glob = ['/path/to/jquery.js'].concat(mainBowerFiles(['**/*.js', '!/path/to/jquery.js']));
var sources = gulp.src(glob);
Related
I'm looking a simple way to pass the option files to wiredep that allows me to set jquery on top of angular, so far, it is working by dependencies, there fore it set jquery at bottom.
I'm passing as options:
var options = {
bowerJson: require('./bower.json'),
directory: './bower_components/',
ignorePath: '../..'
};
devDependencies is set to True, I cannot find any parameter in the documentation that allow to me to do
I've ended up declaring these explicitly like:
var options = [
'css/component*.css',
'css/global.css',
'css/main-custom.css'
]
and passing this to gulp pipe like
gulp.src("/*.html").pipe(options)....
I would like to deploy my web application to several environments. Using Continuous Integration I can run a task to generate a config.json for a particular environment. This file will contain, among others, the particular URLs to use for it.
{
"baseUrl": "http://www.myapp.es/",
"baseApiUrl": "http://api.myapp.es/",
"baseAuthUrl": "http://api.myapp.es/auth/"
}
The issue comes up when I try to set my different services through providers in the config phase. Of course, services are not available yet in the phase so I cannot use $http to load that json file and set my providers correctly.
Basically I would like to do something like:
function config($authProvider) {
$authProvider.baseUrl = config.baseAuthUrl;
}
Is there a way to load those values on runtime from a file? The only thing I can think about is having that mentioned task altering this file straight away. However I have several modules and therefore, that would have to do in all of them which doesn´t seem right.
You can create constants in the config of your main module:
Add $provide as a dependency in your config method
use the provider method to add all constants like this
$provide.provider('BASE_API_URL', {
$get: function () {
return 'https://myexample.net/api/';
}
});
You can use BASE_API_URL as a dependency in your services.
I hope this helps
Optionally you can set the url depending of your environment:
$provide.provider('BASE_API_URL', {
$get: function () {
if(window.location.hostname.toLowerCase() == 'myapp.myexample.net')
{
return 'https://myexample.net/api/' //pre-production
}else
{
return 'http://localhost:61132/'; //local
}
}
});
Regards!
Finally, the solution was generating an angular constants file using templating (gulp-template) through a gulp task. At the end, I am using a yaml file instead a json one (which is the one generated my CI engine with the proper values for the environment I want to deploy to).
Basically:
config.yml
baseUrl: 'http://www.myapp.es/'
baseApiUrl: 'http://api.myapp.es/'
auth:
url: 'auth/'
config.module.constants.template
(function () {
'use strict';
angular
.module('app.config')
.constant('env_variables', {
baseUrl: '<%=baseUrl%>',
baseApiUrl: '<%=baseApiUrl%>',
authUrl: '<%=auth.url%>'
});
}());
gulpfile.js
gulp.task('splicing', function(done) {
var yml = path.join(conf.paths.src, '../config/config.yml');
var json = yaml.safeLoad(fs.readFileSync(yml, 'utf8'));
var template = path.join(conf.paths.src, '../config/config.module.constants.template');
var targetFile = path.join(conf.paths.src, '/app/config');
return gulp.src(template)
.pipe($.template(json))
.pipe($.rename("config.module.constants.js"))
.pipe(gulp.dest(targetFile), done);
});
Then you just inject it in the config phase you need:
function config($authProvider, env_variables) {
$authProvider.baseUrl = env_variables.baseApiUrl + env_variables.authUrl;
}
One more benefit about using gulp for this need is that you can integrate the generation of these constants with your build, serve or watch tasks and literally, forget about doing any change from now on. Hope it helps!
I'm using gulp-durandal to build our durandal app. It fails on our first module which has a depeendecy to knockout through:
define(['knockout',....
[09:35:27] Durandal Error: ENOENT, no such file or directory 'C:\xxxxx\app\knockout.js'
In module tree:
company/viewmodels/edit
at Object.fs.openSync (fs.js:438:18)
I have knockout defined as a patch in config.js (standard requirejs way) but it seems gulp-durandal does not resolve paths from config.js ?
'knockout': '../Scripts/lib/knockout/knockout-2.3.0',
How do you get gulp-durandal to use our config paths instead of trying to resolve the modules directly under the app folder ? I tried using options.extraModules but that only allows you to add paths to modules, not symbolic names for the module so that doesn't seem to be the correct way.
The basic structure of my durandaljs app follows the standard guidelines I believe, I have a config.js and main.js under the App folder.
My config.js:
define([], function() {
return {
paths: {
'text': '../Scripts/lib/require/text',
'durandal': '../Scripts/durandal',
'plugins': '../Scripts/durandal/plugins',
My main.js
require(['config'], function(config) {
require.config(config);
require(['durandal/system', 'durandal/app', 'durandal/viewLocator', 'plugins/widget', 'custombindings'],
function(system, app, viewLocator, widget) {
..... app code here.....
}
gulpfile.js:
var gulp = require('gulp');
var durandal = require('gulp-durandal');
require(['App/config'], function(config){
console.log('loaded config');
});
gulp.task('durandal', function(){
durandal({
baseDir: 'app', //same as default, so not really required.
main: 'main.js', //same as default, so not really required.
output: 'main.js', //same as default, so not really required.
almond: true,
minify: true,
require:true
})
.pipe(gulp.dest('dir/to/save/the/output'));
});
I guess the question is how do I load my config.js paths into gulp so the paths are resolved correctly ? I tried:
var gulp = require('gulp');
var durandal = require('gulp-durandal');
require(['App/config'], function(config){
console.log('loaded config');
});
But it seems require only wants a string as input (I guess require function in gulp != require from require.js)
I believe the issue is that your gulp-durandal task needs configuration to mimic the config.js file. If you need further assistance please provide more code from your gulp-durandal task.
I am having tried to read tutorials and browse other questions, but cannot find a good answer to how I can set up gulp so that I get javascript-files from (already installed) bower-components for development and for production.
First I tried a simple way. For development:
gulp.task('vendorScriptsDevelopment', function() {
return gulp.src(['bower_components/jquery/dist/jquery.js',
'bower_components/**/*.js',
'!bower_components/**/*.min.js'])
.pipe(filter('*.js'))
.pipe(concat('vendor-scripts.js'))
.pipe(gulp.dest('dev'))
});
And similar for production:
gulp.task('vendorScriptsProduction', function() {
return gulp.src(['bower_components/jquery/dist/jquery.min.js',
'bower_components/**/*.min.js'])
.pipe(filter('*.js'))
.pipe(concat('vendor-scripts.js'))
.pipe(gulp.dest('prod'))
});
I included jquery specifically first, since other plugins often depend on it.
But then I realize that some bower packages includes a lot of files, also various javascript-files that I do not want (I just want "the one" that typically also has a CDN-option (and are offered in two versions, normal js and minimized)).
One tutorial I have read uses the main-bower-files plugin for the development part, but then it goes on in the wrong direction and wants to make a minified version itself (as I understand, it is always best to use the packages included minified version, as that is optimized from the developers of the plugin).
How can I set up my two Gulp tasks so that they works as intended? Or am I forced to included all the files manually (like I included jquery manually in my examples)?
Ok, since nobody has replied, here is my attempt to answer my own question.
I created a function that generates an array of the filenames that I want. This uses main-bower-files and filters out the .js-files. If this is development, then that's it. If it is production, then I just change the file extension from .js to .min.js (and for safety checks if that file exists).
var concat = require('gulp-concat');
var mainBowerFiles = require('main-bower-files');
var fs = require('fs');
var vendorScripts = function (minified) {
var scripts = mainBowerFiles().filter(function (filename) {
return filename.match(/.+\.js$/)
});
if (minified) {
scripts = scripts.map(function (orgFilename) {
var minFilename = orgFilename.replace(/^(.+)\.js$/, '$1.min.js');
if (fs.existsSync(minFilename)) {
return minFilename
}
return orgFilename;
});
}
return scripts;
};
gulp.task('vendorScriptsDevelopment', function() {
return gulp.src(vendorScripts())
.pipe(concat('vendor-scripts.js'))
.pipe(gulp.dest('dev'))
});
gulp.task('vendorScriptsProduction', function() {
return gulp.src(vendorScripts(true))
.pipe(concat('vendor-scripts.js'))
.pipe(gulp.dest('dist'))
});
I should change my function to handle other assets too, like css.
If somebody has a better approach, I would be very glad for a suggestion!
Here is my solution for your problem enjoy:
Create a vendors.json file in your sources folder. Edit the file and make path to relevant files you want to include in the production folder. For example:
{
"js" : [
"lib/jquery/dist/jquery.js",
"lib/lodash/lodash.js",
"lib/angular/angular.js",
"lib/angular-sanitize/angular-sanitize.js",
"lib/angular-ui-router/release/angular-ui-router.js",
"lib/angular-ui-utils/ui-utils.js",
"lib/angular-bootstrap/ui-bootstrap-tpls.js",
"lib/chartjs/Chart.js",
"lib/pnotify/pnotify.core.js",
"lib/pnotify/pnotify.buttons.js",
"lib/angular-pnotify/src/angular-pnotify.js",
"lib/angular-prompt/dist/angular-prompt.js",
"lib/angular-mocks/angular-mocks.js"
],
"css" : [
"lib/bootstrap/dist/css/bootstrap.css",
"lib/bootstrap-rtl/dist/css/bootstrap-rtl.css",
"lib/bootstrap/dist/css/bootstrap-theme.css",
"lib/font-awesome/css/font-awesome.css",
"lib/pnotify/pnotify.core.css",
"lib/pnotify/pnotify.buttons.css"
],
"statics" : [
"lib/font-awesome/fonts/*"
]
}
Then in the gulpFile.js add this:
var sources = {
get 'vendor.js'(){
return getVendorSources().js;
},
get 'vendor.css'(){
return getVendorSources().css;
},
get 'vendor.statics'(){
return getVendorSources().statics;
}
};
function getVendorSources(){
return JSON.parse(fs.readFileSync('yourSourcesFolder/vendor.json', 'utf-8'));
}
gulp.task('vendor.css', function() {
return gulp.src(sources['vendor.css'])
.pipe(changed(paths.dist))
.pipe(gulp.dest(paths.dist));
});
and so on for the js and static files tasks.
How should I be using requirejs-text which is installed via bower? I am supposed to put it in baseUrl but wonder if I could use it from components/requirejs-text/? Whats the best practice?
Define the path to the plugin in the config:
requirejs.config({
paths: {
"text" : "components/requirejs-text/text"
}
},
And use it in your module as documented on https://github.com/requirejs/text:
require(["some/module", "text!some/module.html", "text!some/module.css"],
function(module, html, css) {
//the html variable will be the text
//of the some/module.html file
//the css variable will be the text
//of the some/module.css file.
}
);
You can use also technically use the plugin without the path definition in the requirejs.config, but this is propbably not best practice:
require(["your_path_to_the_plugin_from_baseurl/without_js_at_the_end!some/textfile"],
function(yourTextfile) {
}
);
in PROJECT_APP/bower.js add this line under the dependencies section:
"requirejs": "~2.1.8",
"requirejs-text":"~2.0.10", // this is new
"qunit": "~1.12.0",
then run bower install, it should install this plugin and display at the end a path such as requirejs-text#2.0.10 vendor/bower/requirejs-text (depends on your configuration).
Finally, in the config.js file, add this line under
require.config({
paths: {
// Make vendor easier to access.
"vendor": "../vendor",
// Almond is used to lighten the output filesize.
"almond": "../vendor/bower/almond/almond",
// add the requirejs text plugin here
"text" : "../vendor/bower/requirejs-text/text",
// Opt for Lo-Dash Underscore compatibility build over Underscore.
"underscore": "../vendor/bower/lodash/dist/lodash.underscore",
// Map remaining vendor dependencies.
"jquery": "../vendor/bower/jquery/jquery",
"backbone": "../vendor/bower/backbone/backbone"
}
});
Then to use it, simply require it, in this case you can access it with the template variable
define([
// These are path alias that we configured in our bootstrap
'app', // general app variables
'jquery', // lib/jquery/jquery
'underscore', // lib/underscore/underscore
'backbone', // lib/backbone/backbone
'text!templates/books.html' // use the plugin to import a template
], function(app,$, _, Backbone, template){ // don't forget to define it !
This is how I have install requirejs-text using bower
In your project's bower.json file:
{
"name":"{{YOUR PROJECT NAME}}",
"version":"{{YOUR PROJECT VERSION}}",
"dependencies":{
"requirejs-text":"2.0.6"
}
}