uRequire@greecejs: An introduction to http://uRequire.org

The JavaScript Universal Module &
Resource Converter
“Write modular JavaScript code once, run everywhere” is a reality.
uRequire.org
• Why Modularity
• JavaScript module systems
• uRequire primer
• A modules & dependencies builder
• Build config usage
uRequire.org
Why modularity
• Maintainable & reusable code
– Organize code in logical parts
– Clearly stated dependencies
– Reusability, Replace-ability, Testability etc
• Employ standards and trusted tools
– Unit Testing, Versioning, Regression Testing
• Have a dynamic code loading mechanism.
• End the damnation of
– Authoring “OneHuge.js” file
– .js file concatenation
uRequire.org
• Why Modularity
• JavaScript module systems & woes
• uRequire primer
• A modules & dependencies builder
• Build config usage
uRequire.org
CommonJS (nodejs)
var dep1 = require("../some/path/dep1"),
dep2 = require("../other/path/dep2"),
localDep = require("localDep");// ‘localDep’ in node_modules
// do stuff with dep1, dep2 & localDep
// `return` module value
module.exports = {my: "module"}
// or set properties on `exports`
exports.my = "module" // `exports` is a pre-given {}
uRequire.org
AMD (browser)
Asynchronous Module Definition
define([“../some/path/dep1”, “other/path/dep2”,“localDep”],
function(dep1, dep2, localDep) {
// do stuff with dep1, dep2, localDep
return {my:'module'}
}
);
uRequire.org
• Many woes on Module formats & incompatibilities
• Verbose syntax, boilerplate ceremony & intricacies
(especially AMD)
• execution environment (AMD only for Web,
CommonJs only for nodejs)
• capabilities, dependency/path resolutions, plugins,
semantics etc are a mess
• UMD is a semi-standard boilerplate, far from usable.
• U need a bridge to enjoy the richness of modules.
uRequire.org
Why do JavaScript developers hate
modules ?
Mixing AMD & CommonJs ?
define(['main/dep1', 'main/helpers/dep2'],
function(dep1, dep2) {
var dep3 = require('moredeps/dep3');
if (dep3(dep1) === 'wow'){
require(['./dep4'], function(dep4) {
// asynchronously do things with dep4
});
}
// do stuff with dep1, dep2, dep3
return {my:'module'}
}
);
uRequire.org
Too many woes
AMD: “require” needs to be in []
dependencies 1st (& fn params)
AMD: “moredeps/dep3” not
listed as [] dependency, halts
nodejs: ‘define’
is unknown (use
amdefine ?)
nodejs: async
‘require’ not working
nodejs: bundleRelative
paths not working
UMD: Universal Module Definition
// https://github.com/umdjs/umd/blob/master/returnExports.js
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['b'], factory);
} else if (typeof exports === 'object') {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports, like Node.
module.exports = factory(require('b'));
} else {
// Browser globals (root is window)
root.returnExports = factory(root.b);
}
}(this, function (b) {
// use b in some fashion.
// Just return a value to define the module export.
// This example returns {}, but can return a function as the exported value.
return {};
}));
uRequire.org
Not really a “Universal” one but …
… 10s of proposed module templates, for different scenarios.
Dependency path resolution:
• nodejs: relative to requiring file (fileRelative) only:
• AMD: relative to bundle (bundleRelative) also:
• Both are useful (at times). Can we use both ?
uRequire.org
AMD + CommonJS = neighbors from hell
var replace = require(“../../../string/replace");
• define(["utils/string/replace"], ...);
• Why Modularity
• JavaScript module systems & woes
• uRequire primer
• A modules & dependencies builder
• Build config usage
uRequire.org
uRequire primer
• Convert from any format to any other:
– from AMD and CommonJS (.js, .coffee, .iced, .coco, .ls)
– to AMD, CommonJS, UMD, Combined for nodejs-Web/AMD-
Web/Script
– Control conversion features (runtimeInfo, globalWindow etc)
• Forget the woes or Module formats incompatibilities
– Resolve paths, fill missing deps from [], inject ‘require’ etc
• Eliminate boilerplate & write modular Javascript code
once, run everywhere : Web/Script, Web/AMD, nodejs
• A Universal Module Format with the power, goodies &
standards from all.
• Convert to a single combined.js, that runs everywhere &
is super optimized uRequire.org
• Why Modularity
• JavaScript module systems & woes
• uRequire primer
• A modules & dependencies builder
• Build config usage
uRequire.org
A Modules & Dependencies aware builder.
• Exporting modules to global (like window.$)
with no boilerplate.
• Want noConflict(), baked in? Its a simple
declaration away.
• The same in a config:
• Export to bundle:
uRequire.org
// file `uberscore.js` - export it to root (`window`) as `_B`
({ urequire: { rootExports: '_B', noConflict: true }});
module.exports = {...}
dependencies: { exports: { root: { 'uberscore': '_B' }}}
dependencies: { exports: { bundle: { ‘lodash': '_' }}}
Manipulate module dependencies
• Replace deps with mocks or alternative versions:
• With a ResourceConverter callback:
uRequire.org
// underscore is dead, long live _
dependencies: { replace: { lodash: 'underscore'}}
function(m){
m.replaceDeps('models/PersonModel','mock/models/PersonModelMock');
}
Manipulate Module Code
Inject, replace or delete code fragments or AST nodes:
• Delete matching code of code skeleton
• Traverse matching nodes, replace or delete them
• Inject code before (or after) each module's body:
uRequire.org
function(m){ m.replaceCode('if (debug){}') }
function(m){ m.replaceCode('console.log()', function(nodeAST){}) }
function(m) { m.beforeBody = 'var VERSION = ‘1.0’;' }
Manipulate Module Code
Inject common or merged statements:
• beforeBody can be calculated per module
• Before main body at each module:
• Like above, but merge code on 'combined' template:
uRequire.org
bundle: commonCode: 'var expect = chai.expect;'
function(m) {
m.mergedCode = '"var p1 = myModule.p1, p2 = myModule.p2;"'
}
function(m) {
m.beforeBody = "var l = new _B.Logger('" + m.dstFilename + "');";
}
• Why Modularity
• JavaScript module systems & woes
• uRequire primer
• A modules & dependencies builder
• Build config usage
uRequire.org
uRequire config
uRequire.org
uberscore:
path: 'source'
dstPath: 'build'
filez: ['**/*', (f)-> f isnt 'badfile']
copy: [/./]
runtimeInfo: ['!**/*', 'Logger']
dependencies: exports:
bundle: 'lodash': '_'
root: 'uberscore': '_B'
resources: [
['+inject:VERSION', ['uberscore.js'],
(m)-> m.beforeBody = "var VERSION ='0.0.15';"]
]
template: banner: "// uBerscore v0.0.15"
read files from ‘source’
save to ‘build’
filter some filez
copy all other files
affect template selectively
inject ‘lodash’ in each module
export ‘uberscore’ as
`window._B` with noConflict()
inject ‘VERSION = ..’ before body
banner after template/optimize
Can be gruntjs, .coffee / .js nodejs module, .json, .yml & more
Deriving a config
uRequire.org
min:
derive: ['uberscore']
filez: ['!', /RegExpSpecs/]
template: 'combined'
dstPath: 'build/uberscore-min.js'
optimize: true
inherit deeply & modify
filter more filez
change template
optimize through Uglify2.
Can also pass an options {}
• Deeply inherit / extend all properties
change destination
filez: ['**/*', (f)-> f isnt 'badfile', '!', /RegExpSpecs/]
• Either overwriting or appending props:
Declarative template options
uRequire.org
globalWindow: false
runtimeInfo: ['Logger']
useStrict: true
injectExportsModule: ['circular/Dependency']
bare: true
allNodeRequires: ['/data/preCached']
noRootExports: true
scanAllow: false
window === global always
__isWeb, __isNode & __isAMD
inject 'use strict;‘
inject ‘exports’ & ‘module’
no enclosing function
& more…
• per module (minimatch of module path)
• whole bundle (true)
• Why Modularity
• JavaScript module systems & woes
• uRequire primer
• A modules & dependencies builder
• Build config usage
•Thank you
uRequire.org
uRequire.org
1 of 23

Recommended

Requirejs by
RequirejsRequirejs
RequirejsJason Lotito
1.2K views72 slides
JavaScript Dependencies, Modules & Browserify by
JavaScript Dependencies, Modules & BrowserifyJavaScript Dependencies, Modules & Browserify
JavaScript Dependencies, Modules & BrowserifyJohan Nilsson
8.4K views58 slides
Browserify by
BrowserifyBrowserify
Browserifydavidchubbs
1.6K views14 slides
RequireJS by
RequireJSRequireJS
RequireJSTim Doherty
6.1K views43 slides
Lightning Talk: Making JS better with Browserify by
Lightning Talk: Making JS better with BrowserifyLightning Talk: Making JS better with Browserify
Lightning Talk: Making JS better with Browserifycrgwbr
826 views13 slides
Asynchronous Module Definition (AMD) by
Asynchronous Module Definition (AMD)Asynchronous Module Definition (AMD)
Asynchronous Module Definition (AMD)xMartin12
15.5K views18 slides

More Related Content

What's hot

The SPDY Protocol by
The SPDY ProtocolThe SPDY Protocol
The SPDY ProtocolFabian Lange
13.4K views38 slides
Asynchronous Module Definition (AMD) used for Dependency Injection (DI) and MVVM by
Asynchronous Module Definition (AMD) used for Dependency Injection (DI) and MVVMAsynchronous Module Definition (AMD) used for Dependency Injection (DI) and MVVM
Asynchronous Module Definition (AMD) used for Dependency Injection (DI) and MVVMHugh Anderson
1.8K views11 slides
Workshop Intro: FrontEnd General Overview by
Workshop Intro: FrontEnd General OverviewWorkshop Intro: FrontEnd General Overview
Workshop Intro: FrontEnd General OverviewVisual Engineering
668 views34 slides
Requirejs by
RequirejsRequirejs
Requirejssioked
3.4K views16 slides
Workshop 4: NodeJS. Express Framework & MongoDB. by
Workshop 4: NodeJS. Express Framework & MongoDB.Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.Visual Engineering
1.6K views32 slides
Workshop 21: React Router by
Workshop 21: React RouterWorkshop 21: React Router
Workshop 21: React RouterVisual Engineering
2.8K views12 slides

What's hot(20)

The SPDY Protocol by Fabian Lange
The SPDY ProtocolThe SPDY Protocol
The SPDY Protocol
Fabian Lange13.4K views
Asynchronous Module Definition (AMD) used for Dependency Injection (DI) and MVVM by Hugh Anderson
Asynchronous Module Definition (AMD) used for Dependency Injection (DI) and MVVMAsynchronous Module Definition (AMD) used for Dependency Injection (DI) and MVVM
Asynchronous Module Definition (AMD) used for Dependency Injection (DI) and MVVM
Hugh Anderson1.8K views
Requirejs by sioked
RequirejsRequirejs
Requirejs
sioked3.4K views
Workshop 4: NodeJS. Express Framework & MongoDB. by Visual Engineering
Workshop 4: NodeJS. Express Framework & MongoDB.Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.
Visual Engineering1.6K views
Once upon a time, there were css, js and server-side rendering by Andrea Giannantonio
Once upon a time, there were css, js and server-side renderingOnce upon a time, there were css, js and server-side rendering
Once upon a time, there were css, js and server-side rendering
Front-end build tools - Webpack by Razvan Rosu
Front-end build tools - WebpackFront-end build tools - Webpack
Front-end build tools - Webpack
Razvan Rosu167 views
Testing nodejs apps by felipefsilva
Testing nodejs appsTesting nodejs apps
Testing nodejs apps
felipefsilva12.3K views
Module design pattern i.e. express js by Ahmed Assaf
Module design pattern i.e. express jsModule design pattern i.e. express js
Module design pattern i.e. express js
Ahmed Assaf861 views
CodeFest 2014. Пухальский И. — Отзывчивые кроссплатформенные веб-приложения by CodeFest
CodeFest 2014. Пухальский И. — Отзывчивые кроссплатформенные веб-приложенияCodeFest 2014. Пухальский И. — Отзывчивые кроссплатформенные веб-приложения
CodeFest 2014. Пухальский И. — Отзывчивые кроссплатформенные веб-приложения
CodeFest2.3K views
Module, AMD, RequireJS by 偉格 高
Module, AMD, RequireJSModule, AMD, RequireJS
Module, AMD, RequireJS
偉格 高38.5K views
Ember.js - A JavaScript framework for creating ambitious web applications by Juliana Lucena
Ember.js - A JavaScript framework for creating ambitious web applications  Ember.js - A JavaScript framework for creating ambitious web applications
Ember.js - A JavaScript framework for creating ambitious web applications
Juliana Lucena9.7K views
Backbone.js by VO Tho
Backbone.jsBackbone.js
Backbone.js
VO Tho6.7K views
Modularize JavaScript with RequireJS by Minh Hoang
Modularize JavaScript with RequireJSModularize JavaScript with RequireJS
Modularize JavaScript with RequireJS
Minh Hoang4K views

Viewers also liked

Jetairfly Magazine 08 by
Jetairfly Magazine 08Jetairfly Magazine 08
Jetairfly Magazine 08MaartenSouwens
2.9K views44 slides
EcoSense International, Inc. VaultOx by
EcoSense International, Inc. VaultOxEcoSense International, Inc. VaultOx
EcoSense International, Inc. VaultOxEcoSenseINT
483 views22 slides
Grece(Music) by
Grece(Music)Grece(Music)
Grece(Music)guest9615a9
395 views63 slides
Caroline Miller Visual Imagination Project by
Caroline Miller Visual Imagination ProjectCaroline Miller Visual Imagination Project
Caroline Miller Visual Imagination ProjectCaroline Miller
257 views11 slides
My Routine by
My RoutineMy Routine
My RoutineDori Serrano Canelas
154 views6 slides
Engineering eCommerce systems for Scale by
Engineering eCommerce systems for ScaleEngineering eCommerce systems for Scale
Engineering eCommerce systems for Scalevivekv
744 views18 slides

Viewers also liked(16)

EcoSense International, Inc. VaultOx by EcoSenseINT
EcoSense International, Inc. VaultOxEcoSense International, Inc. VaultOx
EcoSense International, Inc. VaultOx
EcoSenseINT483 views
Caroline Miller Visual Imagination Project by Caroline Miller
Caroline Miller Visual Imagination ProjectCaroline Miller Visual Imagination Project
Caroline Miller Visual Imagination Project
Caroline Miller257 views
Engineering eCommerce systems for Scale by vivekv
Engineering eCommerce systems for ScaleEngineering eCommerce systems for Scale
Engineering eCommerce systems for Scale
vivekv744 views
QOSMO by Diverge Design (Portugal) by Jose dos Santos
QOSMO by Diverge Design (Portugal)QOSMO by Diverge Design (Portugal)
QOSMO by Diverge Design (Portugal)
Jose dos Santos3.5K views
Educción médica en un mundo globalizado by EBAUTISTA
Educción médica en un mundo globalizadoEducción médica en un mundo globalizado
Educción médica en un mundo globalizado
EBAUTISTA854 views
Reported Speech by msitgeba
Reported SpeechReported Speech
Reported Speech
msitgeba1.5K views
TASK PRESENTATION by msitgeba
TASK PRESENTATIONTASK PRESENTATION
TASK PRESENTATION
msitgeba535 views
Memoria y aprendizaje by EBAUTISTA
Memoria y aprendizajeMemoria y aprendizaje
Memoria y aprendizaje
EBAUTISTA3.5K views
Auxiliaries Ppt by msitgeba
Auxiliaries PptAuxiliaries Ppt
Auxiliaries Ppt
msitgeba1.5K views

Similar to uRequire@greecejs: An introduction to http://uRequire.org

Packing for the Web with Webpack by
Packing for the Web with WebpackPacking for the Web with Webpack
Packing for the Web with WebpackThiago Temple
835 views48 slides
JavaScript Modules Done Right by
JavaScript Modules Done RightJavaScript Modules Done Right
JavaScript Modules Done RightMariusz Nowak
5.4K views95 slides
Modules and EmbedJS by
Modules and EmbedJSModules and EmbedJS
Modules and EmbedJSJens Arps
1K views43 slides
Advanced Node.JS Meetup by
Advanced Node.JS MeetupAdvanced Node.JS Meetup
Advanced Node.JS MeetupLINAGORA
2K views59 slides
JavaScript Module Loaders by
JavaScript Module LoadersJavaScript Module Loaders
JavaScript Module Loaderszeroproductionincidents
954 views36 slides
IOC + Javascript by
IOC + JavascriptIOC + Javascript
IOC + JavascriptBrian Cavalier
5.5K views120 slides

Similar to uRequire@greecejs: An introduction to http://uRequire.org(20)

Packing for the Web with Webpack by Thiago Temple
Packing for the Web with WebpackPacking for the Web with Webpack
Packing for the Web with Webpack
Thiago Temple835 views
JavaScript Modules Done Right by Mariusz Nowak
JavaScript Modules Done RightJavaScript Modules Done Right
JavaScript Modules Done Right
Mariusz Nowak5.4K views
Modules and EmbedJS by Jens Arps
Modules and EmbedJSModules and EmbedJS
Modules and EmbedJS
Jens Arps1K views
Advanced Node.JS Meetup by LINAGORA
Advanced Node.JS MeetupAdvanced Node.JS Meetup
Advanced Node.JS Meetup
LINAGORA2K views
Intro To Node.js by Chris Cowan
Intro To Node.jsIntro To Node.js
Intro To Node.js
Chris Cowan13.7K views
Introduction to node.js GDD by Sudar Muthu
Introduction to node.js GDDIntroduction to node.js GDD
Introduction to node.js GDD
Sudar Muthu7.3K views
Voorhoede - Front-end architecture by Jasper Moelker
Voorhoede - Front-end architectureVoorhoede - Front-end architecture
Voorhoede - Front-end architecture
Jasper Moelker6.2K views
Preparing for java 9 modules upload by Ryan Cuprak
Preparing for java 9 modules uploadPreparing for java 9 modules upload
Preparing for java 9 modules upload
Ryan Cuprak1.7K views
Beyond DOMReady: Ultra High-Performance Javascript by aglemann
Beyond DOMReady: Ultra High-Performance JavascriptBeyond DOMReady: Ultra High-Performance Javascript
Beyond DOMReady: Ultra High-Performance Javascript
aglemann2.7K views
Rails Engine | Modular application by mirrec
Rails Engine | Modular applicationRails Engine | Modular application
Rails Engine | Modular application
mirrec6.3K views
Let's run JavaScript Everywhere by Tom Croucher
Let's run JavaScript EverywhereLet's run JavaScript Everywhere
Let's run JavaScript Everywhere
Tom Croucher3.5K views
Beautiful Maintainable ModularJavascript Codebase with RequireJS - HelsinkiJ... by Mikko Ohtamaa
 Beautiful Maintainable ModularJavascript Codebase with RequireJS - HelsinkiJ... Beautiful Maintainable ModularJavascript Codebase with RequireJS - HelsinkiJ...
Beautiful Maintainable ModularJavascript Codebase with RequireJS - HelsinkiJ...
Mikko Ohtamaa3.6K views
JS & NodeJS - An Introduction by Nirvanic Labs
JS & NodeJS - An IntroductionJS & NodeJS - An Introduction
JS & NodeJS - An Introduction
Nirvanic Labs6.5K views
Introducing the Seneca MVP framework for Node.js by Richard Rodger
Introducing the Seneca MVP framework for Node.jsIntroducing the Seneca MVP framework for Node.js
Introducing the Seneca MVP framework for Node.js
Richard Rodger4.4K views

Recently uploaded

How To Make Your Plans Suck Less — Maarten Dalmijn at the 57th Hands-on Agile... by
How To Make Your Plans Suck Less — Maarten Dalmijn at the 57th Hands-on Agile...How To Make Your Plans Suck Less — Maarten Dalmijn at the 57th Hands-on Agile...
How To Make Your Plans Suck Less — Maarten Dalmijn at the 57th Hands-on Agile...Stefan Wolpers
49 views38 slides
aATP - New Correlation Confirmation Feature.pptx by
aATP - New Correlation Confirmation Feature.pptxaATP - New Correlation Confirmation Feature.pptx
aATP - New Correlation Confirmation Feature.pptxEsatEsenek1
225 views6 slides
Mobile App Development Company by
Mobile App Development CompanyMobile App Development Company
Mobile App Development CompanyRichestsoft
6 views6 slides
predicting-m3-devopsconMunich-2023-v2.pptx by
predicting-m3-devopsconMunich-2023-v2.pptxpredicting-m3-devopsconMunich-2023-v2.pptx
predicting-m3-devopsconMunich-2023-v2.pptxTier1 app
14 views33 slides
Top-5-production-devconMunich-2023-v2.pptx by
Top-5-production-devconMunich-2023-v2.pptxTop-5-production-devconMunich-2023-v2.pptx
Top-5-production-devconMunich-2023-v2.pptxTier1 app
9 views42 slides
Supercharging your Python Development Environment with VS Code and Dev Contai... by
Supercharging your Python Development Environment with VS Code and Dev Contai...Supercharging your Python Development Environment with VS Code and Dev Contai...
Supercharging your Python Development Environment with VS Code and Dev Contai...Dawn Wages
9 views51 slides

Recently uploaded(20)

How To Make Your Plans Suck Less — Maarten Dalmijn at the 57th Hands-on Agile... by Stefan Wolpers
How To Make Your Plans Suck Less — Maarten Dalmijn at the 57th Hands-on Agile...How To Make Your Plans Suck Less — Maarten Dalmijn at the 57th Hands-on Agile...
How To Make Your Plans Suck Less — Maarten Dalmijn at the 57th Hands-on Agile...
Stefan Wolpers49 views
aATP - New Correlation Confirmation Feature.pptx by EsatEsenek1
aATP - New Correlation Confirmation Feature.pptxaATP - New Correlation Confirmation Feature.pptx
aATP - New Correlation Confirmation Feature.pptx
EsatEsenek1225 views
Mobile App Development Company by Richestsoft
Mobile App Development CompanyMobile App Development Company
Mobile App Development Company
Richestsoft 6 views
predicting-m3-devopsconMunich-2023-v2.pptx by Tier1 app
predicting-m3-devopsconMunich-2023-v2.pptxpredicting-m3-devopsconMunich-2023-v2.pptx
predicting-m3-devopsconMunich-2023-v2.pptx
Tier1 app14 views
Top-5-production-devconMunich-2023-v2.pptx by Tier1 app
Top-5-production-devconMunich-2023-v2.pptxTop-5-production-devconMunich-2023-v2.pptx
Top-5-production-devconMunich-2023-v2.pptx
Tier1 app9 views
Supercharging your Python Development Environment with VS Code and Dev Contai... by Dawn Wages
Supercharging your Python Development Environment with VS Code and Dev Contai...Supercharging your Python Development Environment with VS Code and Dev Contai...
Supercharging your Python Development Environment with VS Code and Dev Contai...
Dawn Wages9 views
Bootstrapping vs Venture Capital.pptx by Zeljko Svedic
Bootstrapping vs Venture Capital.pptxBootstrapping vs Venture Capital.pptx
Bootstrapping vs Venture Capital.pptx
Zeljko Svedic17 views
Top-5-production-devconMunich-2023.pptx by Tier1 app
Top-5-production-devconMunich-2023.pptxTop-5-production-devconMunich-2023.pptx
Top-5-production-devconMunich-2023.pptx
Tier1 app10 views
Unlocking the Power of AI in Product Management - A Comprehensive Guide for P... by NimaTorabi2
Unlocking the Power of AI in Product Management - A Comprehensive Guide for P...Unlocking the Power of AI in Product Management - A Comprehensive Guide for P...
Unlocking the Power of AI in Product Management - A Comprehensive Guide for P...
NimaTorabi219 views
tecnologia18.docx by nosi6702
tecnologia18.docxtecnologia18.docx
tecnologia18.docx
nosi67026 views
How to build dyanmic dashboards and ensure they always work by Wiiisdom
How to build dyanmic dashboards and ensure they always workHow to build dyanmic dashboards and ensure they always work
How to build dyanmic dashboards and ensure they always work
Wiiisdom18 views
predicting-m3-devopsconMunich-2023.pptx by Tier1 app
predicting-m3-devopsconMunich-2023.pptxpredicting-m3-devopsconMunich-2023.pptx
predicting-m3-devopsconMunich-2023.pptx
Tier1 app10 views
JioEngage_Presentation.pptx by admin125455
JioEngage_Presentation.pptxJioEngage_Presentation.pptx
JioEngage_Presentation.pptx
admin1254559 views

uRequire@greecejs: An introduction to http://uRequire.org

  • 1. The JavaScript Universal Module & Resource Converter “Write modular JavaScript code once, run everywhere” is a reality. uRequire.org
  • 2. • Why Modularity • JavaScript module systems • uRequire primer • A modules & dependencies builder • Build config usage uRequire.org
  • 3. Why modularity • Maintainable & reusable code – Organize code in logical parts – Clearly stated dependencies – Reusability, Replace-ability, Testability etc • Employ standards and trusted tools – Unit Testing, Versioning, Regression Testing • Have a dynamic code loading mechanism. • End the damnation of – Authoring “OneHuge.js” file – .js file concatenation uRequire.org
  • 4. • Why Modularity • JavaScript module systems & woes • uRequire primer • A modules & dependencies builder • Build config usage uRequire.org
  • 5. CommonJS (nodejs) var dep1 = require("../some/path/dep1"), dep2 = require("../other/path/dep2"), localDep = require("localDep");// ‘localDep’ in node_modules // do stuff with dep1, dep2 & localDep // `return` module value module.exports = {my: "module"} // or set properties on `exports` exports.my = "module" // `exports` is a pre-given {} uRequire.org
  • 6. AMD (browser) Asynchronous Module Definition define([“../some/path/dep1”, “other/path/dep2”,“localDep”], function(dep1, dep2, localDep) { // do stuff with dep1, dep2, localDep return {my:'module'} } ); uRequire.org
  • 7. • Many woes on Module formats & incompatibilities • Verbose syntax, boilerplate ceremony & intricacies (especially AMD) • execution environment (AMD only for Web, CommonJs only for nodejs) • capabilities, dependency/path resolutions, plugins, semantics etc are a mess • UMD is a semi-standard boilerplate, far from usable. • U need a bridge to enjoy the richness of modules. uRequire.org Why do JavaScript developers hate modules ?
  • 8. Mixing AMD & CommonJs ? define(['main/dep1', 'main/helpers/dep2'], function(dep1, dep2) { var dep3 = require('moredeps/dep3'); if (dep3(dep1) === 'wow'){ require(['./dep4'], function(dep4) { // asynchronously do things with dep4 }); } // do stuff with dep1, dep2, dep3 return {my:'module'} } ); uRequire.org Too many woes AMD: “require” needs to be in [] dependencies 1st (& fn params) AMD: “moredeps/dep3” not listed as [] dependency, halts nodejs: ‘define’ is unknown (use amdefine ?) nodejs: async ‘require’ not working nodejs: bundleRelative paths not working
  • 9. UMD: Universal Module Definition // https://github.com/umdjs/umd/blob/master/returnExports.js (function (root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(['b'], factory); } else if (typeof exports === 'object') { // Node. Does not work with strict CommonJS, but // only CommonJS-like environments that support module.exports, like Node. module.exports = factory(require('b')); } else { // Browser globals (root is window) root.returnExports = factory(root.b); } }(this, function (b) { // use b in some fashion. // Just return a value to define the module export. // This example returns {}, but can return a function as the exported value. return {}; })); uRequire.org Not really a “Universal” one but … … 10s of proposed module templates, for different scenarios.
  • 10. Dependency path resolution: • nodejs: relative to requiring file (fileRelative) only: • AMD: relative to bundle (bundleRelative) also: • Both are useful (at times). Can we use both ? uRequire.org AMD + CommonJS = neighbors from hell var replace = require(“../../../string/replace"); • define(["utils/string/replace"], ...);
  • 11. • Why Modularity • JavaScript module systems & woes • uRequire primer • A modules & dependencies builder • Build config usage uRequire.org
  • 12. uRequire primer • Convert from any format to any other: – from AMD and CommonJS (.js, .coffee, .iced, .coco, .ls) – to AMD, CommonJS, UMD, Combined for nodejs-Web/AMD- Web/Script – Control conversion features (runtimeInfo, globalWindow etc) • Forget the woes or Module formats incompatibilities – Resolve paths, fill missing deps from [], inject ‘require’ etc • Eliminate boilerplate & write modular Javascript code once, run everywhere : Web/Script, Web/AMD, nodejs • A Universal Module Format with the power, goodies & standards from all. • Convert to a single combined.js, that runs everywhere & is super optimized uRequire.org
  • 13. • Why Modularity • JavaScript module systems & woes • uRequire primer • A modules & dependencies builder • Build config usage uRequire.org
  • 14. A Modules & Dependencies aware builder. • Exporting modules to global (like window.$) with no boilerplate. • Want noConflict(), baked in? Its a simple declaration away. • The same in a config: • Export to bundle: uRequire.org // file `uberscore.js` - export it to root (`window`) as `_B` ({ urequire: { rootExports: '_B', noConflict: true }}); module.exports = {...} dependencies: { exports: { root: { 'uberscore': '_B' }}} dependencies: { exports: { bundle: { ‘lodash': '_' }}}
  • 15. Manipulate module dependencies • Replace deps with mocks or alternative versions: • With a ResourceConverter callback: uRequire.org // underscore is dead, long live _ dependencies: { replace: { lodash: 'underscore'}} function(m){ m.replaceDeps('models/PersonModel','mock/models/PersonModelMock'); }
  • 16. Manipulate Module Code Inject, replace or delete code fragments or AST nodes: • Delete matching code of code skeleton • Traverse matching nodes, replace or delete them • Inject code before (or after) each module's body: uRequire.org function(m){ m.replaceCode('if (debug){}') } function(m){ m.replaceCode('console.log()', function(nodeAST){}) } function(m) { m.beforeBody = 'var VERSION = ‘1.0’;' }
  • 17. Manipulate Module Code Inject common or merged statements: • beforeBody can be calculated per module • Before main body at each module: • Like above, but merge code on 'combined' template: uRequire.org bundle: commonCode: 'var expect = chai.expect;' function(m) { m.mergedCode = '"var p1 = myModule.p1, p2 = myModule.p2;"' } function(m) { m.beforeBody = "var l = new _B.Logger('" + m.dstFilename + "');"; }
  • 18. • Why Modularity • JavaScript module systems & woes • uRequire primer • A modules & dependencies builder • Build config usage uRequire.org
  • 19. uRequire config uRequire.org uberscore: path: 'source' dstPath: 'build' filez: ['**/*', (f)-> f isnt 'badfile'] copy: [/./] runtimeInfo: ['!**/*', 'Logger'] dependencies: exports: bundle: 'lodash': '_' root: 'uberscore': '_B' resources: [ ['+inject:VERSION', ['uberscore.js'], (m)-> m.beforeBody = "var VERSION ='0.0.15';"] ] template: banner: "// uBerscore v0.0.15" read files from ‘source’ save to ‘build’ filter some filez copy all other files affect template selectively inject ‘lodash’ in each module export ‘uberscore’ as `window._B` with noConflict() inject ‘VERSION = ..’ before body banner after template/optimize Can be gruntjs, .coffee / .js nodejs module, .json, .yml & more
  • 20. Deriving a config uRequire.org min: derive: ['uberscore'] filez: ['!', /RegExpSpecs/] template: 'combined' dstPath: 'build/uberscore-min.js' optimize: true inherit deeply & modify filter more filez change template optimize through Uglify2. Can also pass an options {} • Deeply inherit / extend all properties change destination filez: ['**/*', (f)-> f isnt 'badfile', '!', /RegExpSpecs/] • Either overwriting or appending props:
  • 21. Declarative template options uRequire.org globalWindow: false runtimeInfo: ['Logger'] useStrict: true injectExportsModule: ['circular/Dependency'] bare: true allNodeRequires: ['/data/preCached'] noRootExports: true scanAllow: false window === global always __isWeb, __isNode & __isAMD inject 'use strict;‘ inject ‘exports’ & ‘module’ no enclosing function & more… • per module (minimatch of module path) • whole bundle (true)
  • 22. • Why Modularity • JavaScript module systems & woes • uRequire primer • A modules & dependencies builder • Build config usage •Thank you uRequire.org