Integrate ECMAScript-6 into existing AngularJS project - javascript

I'm trying to integrate ECMA6 into existing Angular project.
And I'm looking for a best practise for some issues we have.
All components (and we have a lot) have following file structure:
-app/
--components/
--somemodul/
--somemodul.mdl.js
--somemodul.drv.js
--somemodul.ctrl.js
--somemodul.srv.js
--somemodul.tmpl.html
-app.js
//somemodul.mdl.js
(function () {
angular.module('somemodul', []); //initiate module
})()
//somemodul.drv.js
(function () {
angular.module('somemodul')
.directive('someModuleDrv', someModuleDrv); //add to module
function someModuleDrv() {
// CODE
}
})()
//somemodul.ctrl.js
(function () {
angular.module('somemodul')
.controller('someModuleCtrl', someModuleCtrl); //add to module
function someModuleCtrl() {
// CODE
}
})()
//somemodul.srv.js
(function () {
angular.module('somemodul')
.service('someModuleSrv', someModuleSrv); //add to module
function someModuleSrv() {
// CODE
}
})();
On build, Gulp do concat and everything works fine.
With ECMA6 We need to import all these modules into app.js.
And now I see two options:
1) To concate myself all 'somemodul' files into single file:
//somemodul.js
export default angular.module('somemodul', [])
.directive('someModuleDrv', someModuleDrv)
.service('someModuleSrv', someModuleSrv)
.controller('someModuleCtrl', someModuleCtrl);
function someModuleDrv() { };
function someModuleSrv() { };
function someModuleCtrl() { };
2) Import all submodules into 'somemodule.mdl.js':
//somemodul.mdl.js
import someModuleDrv from './somemodul.drv.js'
import someModuleSrv from './somemodul.srv.js'
import someModuleCtrl from './somemodul.ctrl.js'
export default angular.module('somemodul', [
someModuleDrv.name,
someModuleSrv.name,
someModuleCtrl.name
]);
//somemodul.drv.js
export default angular.module('somemodul.drv', [])
.directive('someModuleDrv', someModuleDrv);
function someModuleDrv() {
// CODE
}
//somemodul.srv.js
export default angular.module('somemodul.srv', [])
.directive('someModuleSrv', someModuleSrv);
function someModuleSrv() {
// CODE
}
//somemodul.ctrl.js
export default angular.module('somemodul.ctrl', [])
.directive('someModuleCtrl', someModuleCtrl);
function someModuleCtrl() {
// CODE
}
Both options works.
Unfortunately both options requires a lot of hands-on work.
So I'm looking for possible other solution.....
Thanks.

Found solution is using require.context().
In my case it will looks like this:
//somemodul.js
export default angular.module('somemodul', [])
/**
* Requires all directives from subdirectories.
* #param requireContext
* #returns {*}
*/
function requireAll(requireContext) {
return requireContext.keys().map(requireContext);
}
requireAll(require.context(".", true, /^\.\/.*\.js$/));
I tried do not use require and stay only with (export/import), but looks like it's only one way.

Related

How to extend core modules of Vue Storefront

I want to override an action from cart module store. I am trying to extend this CartModule by following this link
Extending and Overriding Modules Doc
I have created a file /src/modules/cart/index.ts with following code
import { VueStorefrontModuleConfig, extendModule, VueStorefrontModule } from '#vue-storefront/core/lib/module'
import { CartModule } from '#vue-storefront/core/modules/cart'
import { cartModule } from './store'
const cartExtend: VueStorefrontModuleConfig = {
key: 'cart',
store: {modules: [{key: 'cart', module: cartModule}]},
afterRegistration: function () {
console.log('Cart module extended')
}
}
extendModule(cartExtend)
export const registerModules: VueStorefrontModule[] = [CartModule]
I am getting error that CarModule type does not match with VueStorefrontModule
Also I don't know what to do next in order to make it effective. Docs are not clear about it. Please help. Thanks
If you want to overwrite action of module you don't want to extend module but store.
Here is example:
Vuestorefront has CartModule (in core) and you need to change code of action refreshTotals.
Code your in file /src/modules/cart/index.ts:
import {StorefrontModule} from '#vue-storefront/core/lib/modules';
import {extendStore} from '#vue-storefront/core/helpers';
const cartModule = {
action: {
async refreshTotals({dispatch}, payload) {
//
// your new (and better!) code ;-)
//
}
},
}
export const MyAwesomeCart: StorefrontModule = function () {
extendStore('cart', cartModule);
}
In last step register this your new module under /src/modules/client.ts:
..
...
import {CartModule} from '#vue-storefront/core/modules/cart';
import {MyAwesomeCart} from "modules/cart/index";
export function registerClientModules() {
registerModule(CartModule); // original module
registerModule(MyAwesomeCart); // your new overwiritng module
...
..

Can i write firebase real time database triggers in other files instead of index.js?

I would like to split large index.js file into multiple files. To organize the code can i write firebase triggers in multiple js files? If so please help me with how to write properly
child.js
exports.testFunction = functions.database.ref(`/test/`).onWrite((snap, context) => {
console.log(snap.val());
return null;
});
...
index.js
const childFunction = require('./child.js');
...
Basically what you need to do is separate your functions in different files and import them in your index.js like:
1.) In the .js file to be imported such as ‘modA.js’
module.exports = {
func1: function () {
// function 1
},
func2: function () {
// function 2
}
};
2.) Import it in your index.js:
var moduleA = require('./modA');
3.) Run it like:
moduleA.func1();

Load JavaScript file in angular2 app

I'm working on a angular2 application written in TypeScript.
This works:
I have a module called plugin-map.ts which looks something like this:
import { Type } from '#angular/core';
import { SomeComponent } from './plugins/some.component';
export const PluginMap: { [key: string]: Type<any> } = {
'e690bec6-f8d1-46a5-abc4-ed784e4f0058': SomeComponent
};
It gets transpiled to a plugin-map.js which looks something like this:
"use strict";
var some_component_1 = require('./plugins/some.component');
exports.PluginMap = {
'e690bec6-f8d1-46a5-abc4-ed784e4f0058': some_component_1.SomeComponent
};
//# sourceMappingURL=plugin-map.js.map
And in other modules I'm importing my PluginMap like this:
import { PluginMap } from './plugin-map';
What I want:
Now I want to create plugin-map.js at runtime when my server starts. So I want to get rid of my plugin-map.ts and instead have only a (generated) plugin-map.js. And I don't want to have any transpile-time dependencies to that plugin-map.js.
What I tried:
In modules where I need to access the PluginMap I replaced the import statement with a declaration like this:
declare const PluginMap: { [key: string]: Type<any> };
Now of course at runtime I get a Error: (SystemJS) 'PluginMap' is undefined. So my next step was to load plugin-map.js explicitly from my index.html like this:
...
<script src="js/system.src.js"></script>
<script src="systemjs.config.js"></script>
<script>
System.import('./app/plugins/plugin-map.js').catch(function (err) { console.error(err); });
System.import('app').catch(function(err){ console.error(err); });
</script>
...
When I start my application I can see that the browser actually requests the plugin-map.js file. But I still get the Error: (SystemJS) 'PluginMap' is undefined.
Question:
How/where do I have to load my generated plugin-map.js so that this works?
I had to make sure that PluginMap is available in the global context. So the generated plugin-map.js has to look like this:
var some_component_1 = require('./plugins/some.component');
PluginMap = {
'e690bec6-f8d1-46a5-abc4-ed784e4f0058': some_component_1.SomeComponent
};
and not like this:
"use strict";
var some_component_1 = require('./plugins/some.component');
exports.PluginMap = {
'e690bec6-f8d1-46a5-abc4-ed784e4f0058': some_component_1.SomeComponent
};
//# sourceMappingURL=plugin-map.js.map
Now it seems to work.

How do I import a named SystemJS module from a bundle file?

I've got one file (app.js) with two named modules in it ("foo", and "bar" - where "bar" depends on "foo").
Question: How to I load "bar" it in the browser?
Disclaimer: I'm new to SystemJS and the docs look a little intimidating.
app.js
System.register("foo", [], function(exports_1) {
"use strict";
var App;
return {
setters:[],
execute: function() {
App = (function () {
function App() {
this.bar = 'Hello world.';
console.log(this.bar);
}
return App;
})();
exports_1("App", App);
;
}
}
});
System.register("bar", ["foo"], function(exports_1) {
"use strict";
var App;
return {
setters:[],
execute: function() {
App = (function () {
function App() {
this.bar = 'Mony a mickle maks a muckle.';
console.log(this.bar);
}
return App;
})();
exports_1("App", App);
;
}
}
});
Got the results I wanted by doing the following:
Added the <script src="app.js"> tag to my index file.
Also added System.import('bar'); to the page.
I wonder if this is the standard/recommended way of doing it.
Edit:
The issue with this approach is that I need two strategies for development and production.
In development I don't add the <script> tag and I import the module using System.import('path/app.js');
I think using a bare bones seed can help you out by showing a simple working example, this seed has a PRODUCTION and DEV MODE and you dont need to have 2 strategies, just choose between running it bundled or not
try:
npm i -g slush-jspm-react-seed

A good way of testing jsx components that used RequireJS define from jest

I want to test ReactJS component with jest but have a trouble because component using RequireJS define. This is example code (truncated).
// component.js
define(function(require){
var React = require('react');
// code
var _ = require('underscorejs');
var somename = React.createClass({
propTypes: {
},
getDefaultProps: function () {
return {
};
},
render: function () {
// implementation
}
});
return React.createClass({
// implementation
});
});
When I tried into test:
import ComponentName from '../path/to/ComponentName.jsx';
i receive this error:
Runtime Error
ReferenceError: define is not defined
I was think about to process source with preprocessor. It is possibillity to use scriptPreprocessor option but this is some kind of hacky from my point of view.
I would be very grateful for any ideas and recommendations.

Categories

Resources