I am developing a frontend using the Backbone.js and require.js and everything is going well till i need to create a file named it config.js to store some defaule values to use it in the whole of the application
below is the code of the config.js file
// Filename: config.js
define([''], function(){
var baseUrl = "http://localhost:8888/client/",
apiServer = "http://api-server:8888";
return function(type){
return eval(type);
};
});
in one of my views I would define the config.js then i can access the value of both
var baseUrl = "http://localhost:8888/client/",
apiServer = "http://api-server:8888";
via this line of code below that i put it inside any *.js file on my application
var baseUrl = config('baseUrl');
console.log(baseUrl); //prints out this > http://localhost:8888/client/
the problem here is i am using eval to get the value of what kind of value i need to retrieves, I know it's not safe method to use but could anyone suggest safe solution
RequireJS lets you define objects just like you define more complicated modules. You can have a config module and then use it in whichever other files that require it.
Inside config.js you can do:
define({
baseUrl:"http://localhost:8888/client/",
apiServer:"http://api-server:8888"
});
Then require it in other modules:
//someotherfile.js , defining a module
define(["config"],function(config){
config.baseUrl;// will return the correct value here
//whatever
});
Side note: You can use actual global state (defining the variable on window) but I strongly urge you not to since this will make testing hard, and will make the dependency implicit and not explicit. Explicit dependencies should always be preferred. In the above code and unlike the global it's perfectly clear that the configuration is required by the modules using it.
Note, if you want values that are not valid identifiers you can use bracket syntax too config["baseUrl"] the two (that and config.baseUrl) are identical in JavaScript.
As an alternative solution (and uglier than Benjamin's) you can put both urls into an object:
define([''], function(){
var urls = {
baseUrl: "http://localhost:8888/client/",
apiServer: "http://api-server:8888"
};
return function(type){
return urls[type];
};
});
Still, simply exporting an object is much cleaner.
Related
I have a different URL for our api depending if it's development or production for a react app.
Using webpack, how can I set an env var like __API_URL__ and then change that depending if it's built using webpack.config.dev vs webpack.config.prod
I thought the answer may be in webpack.DefinePlugin but no luck.
new webpack.DefinePlugin({
__API_URL__: 'localhost:3005',
}),
I'd expect __API_URL__ to be available as a global but no such luck.
What would be the right way to do this? Also key thing is that no express server on the prod deploy. So this has to happen during the build...
As Michael Rasoahaingo said, the DefinePlugin works similar like replacing values with regular expressions: It replaces the value literally in your source code. I would not recommend to use the DefinePlugin for this kind of task.
If you want to switch configs based on the environment, you could use resolve.alias for that. Just import your config like this:
var config = require("config");
and then add a mapping in your webpack.config.js:
resolve: {
alias: {
config$: require.resolve("path/to/real/config/file")
}
}
DefinePlugin is not working as you expected. It doesn't expose __API_URL__ as a global variable.
According to the documentation: "The values will be inlined into the code which allows a minification pass to remove the redundant conditional."
So, it will find all occurence of __API_URL__ and changes it.
var apiUrl = __API_URL__
and
__API_URL__: '"localhost:3005"' // note the ' and "
become
var apiUrl = "localhost:3005"
I'm part of a team developing an AngularJS application and right now I'm working on modifying the Gulp build script. Part of my task is prepopulating the template cache (up till now we have been loading the templates as the routes/directives needed them).
The Gulp task is basically:
var templateCache = require('gulp-angular-templatecache');
gulp.task('cache-templates', function(){
var dest = destinationPath,
src = sourcePath;
return gulp.src(src)
.pipe(plumber())
.pipe(templateCache('templates.js', {root: './templates/'}))
.pipe(gulp.dest(dest));
});
The problem I am getting is that gulp removes the "./" from the root. For instance:
$templateCache.put("templates/foo.html","<div>some html</div>");
in stead of
$templateCache.put("./templates/foo.html","<div>some html</div>");
The module is loaded correctly into app.js and declared as a dependency, and if I do put the "./"'s as a prefix manually, after building, everything works fine. So could you please tell me how to force Gulp to include the "./" prefix in my root?
Note: Every other prefix works fine, it just removes the "./". I would prefer it if I could solve this from within the Gulpfile, without having to modify the templateUrl's in my directives and $routeProvider, because the application is rather large and that would only be asking for trouble. Thanks! :)
What you can do is use gulp-replace and replace 'templates/' with './templates/'.
Old Answer
In the options that you pass to template you can provide a base function
.pipe(templateCache('templates.js', {root: './templates/', base: baseFn}))
you can modify the file-path there
var baseFn = function (file) { return './' + file.relative; }
I'm doing some studies using the Pixijs library, which I find amazing. I'll also have a look into Fabricjs, that seems to have a smaller footprint.
I've been working with Angularjs for some time now and I like conventions, instead of taking time in each project doing configuration and organizing code differently every time.
I would like to hear from some body who experienced Pixijs (or similar) with a framework to organise the code.
I understand that Angularjs is MVVM, but let me know about any tips or suggestion that you may think of?
I did some research this far and a few things came to my mind, such as Browserify (I do believe in convention instead of configuration like I've mentioned though and maybe this wouldn't be the best tool for me).
Kinda old question, but this is something I was looking for myself when starting out with PIXI, so I hope it could be of help to someone to get started.
I use the Revealing module pattern and separate the application into separate files/modules, and then use Browserify to create the application bundle. The HTML loads the app.js bundle which stems from the app.js source below.
index.html: Load your libs (PIXI et al) in <head> and then your app.js in the <body>.
app.js source example:
(function() {
// App.js is the "bootstrap" that loads dependencies, takes care of pre-loading etc.
// I have a template of this which I copy into any new project and use as a checklist.
var core = require("./core.js"); // Use a dummy module as application-wide namespace for easy access
// Any external modules (f eg node modules) could go here
core.utilityLib = require("node-lib");
// Application modules here
core.myModule = require("./myModule.js");
// core.myModule2 = require("./myModule2.js"); // .. you get the idea
// Our main application module
core.main = require("./main.js");
// Init function to run when DOM/scripts have loaded
var init = function() {
// I have a generic screen module which sets up PIXI renderer depending on device compatibility using Modernizr (or weapon of choice). To keep it simple for the sake of the example, lets just create our renderer directly:
core.renderer = PIXI.autoDetectRenderer(screen.innerWidth,screen.innerHeight,{resolution:window.devicePixelRatio});
// I also use a generic loader module that wraps PIXI.loader, taking a list of assets from a config file. Let's just call PIXI.loader directly for now:
PIXI.loader
.add({name:"myasset",url:"/myasset.png"})
.on('progress', loadProgressFunction)
.once('complete',loadCompleteFunction)
})
.load();
}
window.onload = init; // Tell browser to call init function when loaded
// Optional loading progress bar
var function = loadProgressCallback(e) {
}
// Call when mandatory assets has been loaded
var loadCompleteFunction = function() {
myModule.init(); // Init any mandatory modules, f eg to instantiate a player
main.init(); // Tell our main application/game module that we're ready to do fancy stuff
}
// Method to make things move
var animate = function() {
// Send juice to modules that needs to be juiced (or use a ticker module on per-module basis).
// core.main.animate();
requestAnimationFrame(animate);
}
requestAnimationFrame(animate); // See comment below
}());
Comment: PIXI has an built-in requestAnimationFrame alias that takes care of fallback. If not using PIXI, you could use Paul Irish' gist.
core.js:
module.exports = {}; // Just a dummy object to create a module scope that all the modules
// can use to communicate with each other, without running into circular reference problems
main.js:
// Main application/game module
module.exports = (function() {
// Dependencies
var core = require("./core.js"); // This way we can easily access all the necessary modules
// Exports
var exports = {}; // Everything put into this object will be "public"
// Vars
var stuff = 1; // Module vars
exports.init = function() {
// Application magic starts here :)
}
// Some other public method ...
exports.publicMethod = function() {
}
// Some private method
var privateMethod = function() {
}
return exports; // Expose public functions to other modules
}());
Any additional modules can be organized in pretty much the same way as main.js.
Run browserify dev/app.js > html_root/app.js each time you want to "compile" your bundle (or create a Makefile, gulp-, node-, or webpack-script - whichever you prefer).
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'));
});
I am using angular-translate on a rather large Angular project. I am breaking the project into multiple modules to make it more manageable, but I am unable to break up my translation strings per module.
For example, I have modules A and B, where B is a submodule of A. There are strings that pertain to the HTML covered by module A, which are placed in '/json/localization/A/en.json'. Likewise, there are strings pertaining to B that I place in '/json/localization/B/en.json'. First I load B's en.json in module B using angular-translate's $translationProvider. Then I load module A's en.json, also using $translationProvider. The problem is that loading A's strings overrides B's strings and they are lost.
Using angular-translate, is there a way to load strings per module, without overriding, or does the parent module have to load all of the strings from a single en.json?
Here is an example (in coffeescript) of how I am loading the translation strings:
my_module.config(['$translateProvider', ($translateProvider) ->
$translateProvider.useStaticFilesLoader
prefix: '/json/localization/A/'
suffix: '.json'
$translateProvider.preferredLanguage 'en'
])
angular-translate supports async loading of partial language files. All partials are merged into one dictionary per language.
The official documentation can be found here: http://angular-translate.github.io/docs/#/guide/12_asynchronous-loading
It supports applying a template for url templates that point to the modularised language files:
$translateProvider.useLoader('$translatePartialLoader', {
urlTemplate: '/i18n/{part}/{lang}.json'
});
From within your controllers, you can add language modules and refresh the data bindings like this:
angular.module('contact')
.controller('ContactCtrl',
function ($scope, $translatePartialLoader, $translate) {
$translatePartialLoader.addPart('contact');
$translate.refresh();
});
Of course, loading the partials can also be covered in a route's resolve phase
Alternatively, you can also look into building your own custom loader function. http://angular-translate.github.io/docs/#/guide/13_custom-loaders
This provides all the flexibility you need to combine required language modules in one shot. E.g. you could do something like this:
app.factory('customLoader', function ($http, $q) {
// return loaderFn
return function (options) {
var deferred = $q.defer();
var data = {
'TEXT': 'Fooooo'
};
$http.get('nls/moduleA/en.json').success(function(moduleA){
angular.extend(data, moduleA);
$http.get('nls/moduleB/en.json').success(function(moduleB){
angular.extend(data, moduleB);
deferred.resolve(data);
});
});
return deferred.promise;
};
});