Properly babel transpile a file in ember-cli-build withing additional tree - ember.js

I have some files in my project that I would like to move out of the normal app tree and only load in certain situations. Currently I used broccoli-stew to move the file and broccoli-babel-transpiler to transpile the destination file. However when I do this I end up with an extra default object on the imported files.
this code gets added to the top
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _Ember = _interopRequireDefault(_ember);
and this causes me to have to write the source file with references to ember as Ember["default"].Object etc. Would like to not have any odd references in the source files that makes it harder for other developers to understand.
This is my current ember-cli-build.js file
/* global require, module */
var stew = require('broccoli-stew');
var esTranspiler = require('broccoli-babel-transpiler');
var EmberApp = require('ember-cli/lib/broccoli/ember-app');
module.exports = function(defaults) {
var app = new EmberApp(defaults, {
storeConfigInMeta: false
});
var additionalTrees = [];
var appTree = app.appAndDependencies();
if (EmberApp.env() !== "production") {
var jQuery = stew.find(appTree, "bower_components/jquery/dist/jquery.min.js");
jQuery = stew.mv(jQuery, "bower_components/jquery/dist/jquery.min.js", "assets/jquery.js");
additionalTrees.push(jQuery);
}
function extractRouter(fileName) {
var router = stew.find(appTree, 'mobile-web/'+ fileName + '.js');
router = esTranspiler(router, {
modules: "amd",
moduleIds: true,
moduleId: "mobile-web/router"
});
router = stew.mv(router, 'mobile-web/'+ fileName + '.js', 'assets/'+ fileName + '.js');
additionalTrees.push(router);
}
extractRouter('router');
extractRouter('secure-router');
return app.toTree(additionalTrees);
};

Try configure your esTranspiler to use modules: "amdStrict":
router = esTranspiler(router, {
modules: "amdStrict",// here
moduleIds: true,
moduleId: "mobile-web/router"
});
It's similar to "commonStrict" as described in the docs. The amdScrict exists in the source code here.

Related

Embedded Node execute .node file

I've built an embedded instance of Node using the Embed_Test example from the Node repository.
Using this instance, I am trying to execute some C++ code.
I have a generated .node and .dll, and I have webpack'd my Javascript file.
When I run,
node dist/bundle.js
It runs fine. However, when I start up my embedded NodeJS application and attempt to run bundle.js, I get the following error (it's as if it cannot load the .node file?):
TypeError: Cannot read property 'testCppCode' of undefined
at evalmachine.<anonymous>:154:2305
at s.handle_request (evalmachine.<anonymous>:120:782)
at s (evalmachine.<anonymous>:113:879)
at p.dispatch (evalmachine.<anonymous>:113:901)
at s.handle_request (evalmachine.<anonymous>:120:782)
at evalmachine.<anonymous>:106:2533
at Function.v.process_params (evalmachine.<anonymous>:106:3436)
at g (evalmachine.<anonymous>:106:2476)
at evalmachine.<anonymous>:259:218
at s.handle_request (evalmachine.<anonymous>:120:782)
This is my App.js, before a webpack:
var myArgs = process.argv.slice(2);
var ip = myArgs.length >= 1 ? myArgs[0] : "localhost";
var port = myArgs.length >= 2 ? myArgs[1] : "5555";
var fs = require("fs");
var path = require("path");
const express = require("express");
var addon = require("../build/Release/test.node");
const server = express();
server.get("/", (req, res) => {
var res = addon.testCppCode("Sample", function (err, cpp) {
var capabilitiesResult = cpp;
if (err) {
console.log("Error!");
console.log(err);
console.log(cpp);
} else {
console.log("Success!");
}
});
});
I've tried sticking the test.node and test.dll in the same folder as the embedded instance of node, I've tried putting it in the same dir as the webpack, I've tried sticking it in a relative dir to the embedded node (so it would be at ../build/Release/) -- but the error is always the same. What do I need to do in order to get it to "see" the .node file?

Modify how ember-i18n localizations are loaded, split localization strings from main app.js

I am trying to modify the way ember-i18n localizations are loaded. What I want to do is have the localizations in a separate file from the main app javascript file.
Ideally, the structure would remain the same as now. So I would have app/locales/fr/translations.js and app/locales/de/translations.js , each having content similar to this:
export default {
key: "value"
}
So I thought I need to write a custom addon, which would alter the build process. This addon would need to:
Ignore app/locales from final build
Compile all the translation files into one
Transpile the new file with babel
Copy the file in dist/assets/translations.js
The combined translation file would look something like this:
export default {
fr: {
key: "value"
},
de: {
key: "value"
}
This way, I would be able to use and instance initializer and simply import and use this module:
import Translations from 'my-translations';
export function initialize(instance) {
const i18n = instance.lookup('service:i18n');
for(let lang in Translations) {
if(Translations.hasOwnProperty(tag)) {
i18n.addTranslations(tag, Translations[tag]);
}
}
}
Also, index.html would be:
<script src="assets/vendor.js"></script>
<script src="assets/translations.js"></script>
<script src="assets/my-app.js"></script>
Well, I started writing the custom addon, but I got stuck. I managed to ignore the locales, and I wrote code that parses all the localizations, but I do not know how to write the new translations file in dist. What hook do I neeed to use, to be able to write into dist? Any help? Thank you so much.
Here is the code I wrote:
Stuff I use
var Funnel = require('broccoli-funnel');
var stew = require('broccoli-stew');
var fs = require('fs');
var writeFile = require('broccoli-file-creator');
var mergeTrees = require('broccoli-merge-trees');
preprocessTree: function(type, tree) {
if(type !== 'js') {return tree;}
var treeWithoutLocales = new Funnel(tree, {
exclude: ['**/locales/*/translations.js']
});
var translations = {};
var files = fs.readdirSync('app/locales');
files.forEach((tag) => {
if(tag !== 'fr') {return;}
let contents = fs.readFileSync('app/locales/' + tag + '/translations.js', 'utf8');
contents = contents.replace(/^export default /, '');
contents = contents.replace(/;$/, '');
contents = JSON.parse(contents);
translations[tag] = contents;
});
// Should do something with this .. how to write in dist? and when? I need it compiled with babel
var fileTree = writeFile('/my-app/locales/translations.js', 'export default ' + JSON.stringify(translations) + ';');
return treeWithoutLocales;
}
I am not sure if you actually asked a question; but here goes some kind of answer.
Why complicate? Just use James Rosen's i18n addon used by a lot of projects.

trees:{ mergetrees(['src',external js file])} in ember-cli-build.js is not working

In glimmer application, I want to bundle the external Js file with app.js file. I want to use svg in glimmer application. Instead of ember-inline-svg,I used broccoli-flatiron and broccoli-merge-trees packages to bundle external js file with app.js.
My code in ember-cli-build.js is
const GlimmerApp = require('#glimmer/application-pipeline').GlimmerApp;
const merge = require('merge');
const fs = require('fs');
const Funnel = require('broccoli-funnel');
const flatiron = require('broccoli-flatiron');
const mergeTree = require('broccoli-merge-trees');
module.exports = function(defaults) {
var options=merge(true, {}, {
paths: ['src/ui/styles/svgs']
});
var svgs = mergeTree(options.paths.filter(function(path) {
return fs.existsSync(path);
}));
svgs = new Funnel(svgs, {
include: [new RegExp(/\.svg$/)]
});
svgs = flatiron(svgs, {
outputFile: 'svgs.js',
trimExtensions: true,
variableName : "const svgs = "
});
let app = new GlimmerApp(defaults, {
trees:{
src:mergeTree(['src',svgs])
}
});
return app.toTree();
};
But it gives an error "The type of module 'svgs' could not be identified"...
I want to bundle svgs with app.js.
Try to merge the trees like this instead:
…
module.exports = function(defaults) {
…
let app = new GlimmerApp(defaults, {
});
return mergeTree([app.toTree(), svgs]);
};

How to generate icon for onesignal using ionic

I am using ionic 2.
I need generate the icon for one signal notification.
I tried to this
Add a file to your hooks directory inside the after_prepare folder called 030_copy_android_notification_icons.js
Put the following code in it:
var filestocopy = [{
"resources/android/icon/drawable-hdpi-icon.png":
"platforms/android/res/drawable-hdpi/ic_stat_onesignal_default.png"
}, {
"resources/android/icon/drawable-mdpi-icon.png":
"platforms/android/res/drawable-mdpi/ic_stat_onesignal_default.png"
}, {
"resources/android/icon/drawable-xhdpi-icon.png":
"platforms/android/res/drawable-xhdpi/ic_stat_onesignal_default.png"
}, {
"resources/android/icon/drawable-xxhdpi-icon.png":
"platforms/android/res/drawable-xxhdpi/ic_stat_onesignal_default.png"
}, {
"resources/android/icon/drawable-xxxhdpi-icon.png":
"platforms/android/res/drawable-xxxhdpi/ic_stat_onesignal_default.png"
} ];
var fs = require('fs');
var path = require('path');
// no need to configure below
var rootdir = process.argv[2];
filestocopy.forEach(function(obj) {
Object.keys(obj).forEach(function(key) {
var val = obj[key];
var srcfile = path.join(rootdir, key);
var destfile = path.join(rootdir, val);
//console.log("copying "+srcfile+" to "+destfile);
var destdir = path.dirname(destfile);
if (fs.existsSync(srcfile) && fs.existsSync(destdir)) {
fs.createReadStream(srcfile).pipe(
fs.createWriteStream(destfile));
}
});
});
I have no idea.
Kindly advice me,
Thanks
I have faced with same issue. Your way is correct, putting 030_copy_android_notification_icons.js file under {root}/hooks/after_prepare. Also note that, filename is not important.
Then to run script you need to run below comment:
ionic cordova prepare android
With this, your script will be run. But maybe your problem may be similar to mine. If you use windows, while coping files from resources/android/icon/ to platforms/android/res/, because of missing of target folders, script is not able to copy operation. That's why a simple code should be added to code.
var destdir = path.dirname(destfile);
if (!fs.existsSync(destdir)){
fs.mkdirSync(destdir);
}

How to generate a self-dependent typescript file and reference it in html?

I'm using gulp-typescript task to generate a single js file with all needed requires. The next step is that I need to reference this file in html. How can I do this?
**project**
|
+-dist
|
+- output.js
+-src
|
+- a.ts
+- b.ts
gulpfile.js
var gulp = require('gulp')
var ts = require('gulp-typescript');
var concat = require('gulp-concat');
var sourcemaps = require('gulp-sourcemaps');
var config = {
app: 'src',
dist: 'dist',
fileName: 'output.js'
};
gulp.task('default', function () {
var tsRes = gulp.src(config.app + '/scripts/**/*.ts')
.pipe(sourcemaps.init())
.pipe(ts({
noImplicitAny: true,
out: config.fileName,
isolatedModules: false,
module: 'amd'
}));
return tsRes.js
.pipe(concat(config.fileName))
.pipe(sourcemaps.write())
.pipe(gulp.dest(config.dist));
});
output.js
define(["require", "exports"], function (require, exports) {
var Greeter = (function () {
function Greeter(message) {
this.greeting = message;
console.log('Greeter constructor has been called');
}
Greeter.prototype.greet = function () {
return "Hello, " + this.greeting;
};
return Greeter;
})();
exports.Greeter = Greeter;
});
define(["require", "exports", './Greeter'], function (require, exports, model) {
var greeter = new model.Greeter("world");
console.log(greeter);
var button = document.createElement('button');
button.textContent = "Say Hello";
button.onclick = function () {
alert(greeter.greet());
};
document.body.appendChild(button);
});
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIkdyZWV0ZXIudHMiLCJtYWluLnRzIiwicG9ydGZvbGlvZGFzaGJvYXJkLndvcmtlci5qcyJdLCJuYW1lcyI6WyJHcmVldGVyIiwiR3JlZXRlci5jb25zdHJ1Y3RvciIsIkdyZWV0ZXIuZ3JlZXQiXSwibWFwcGluZ3MiOiI7SUFBQTtRQUVJQSxpQkFBWUEsT0FBZUE7WUFDdkJDLElBQUlBLENBQUNBLFFBQVFBLEdBQUdBLE9BQU9BLENBQUNBO1lBQ3hCQSxPQUFPQSxDQUFDQSxHQUFHQSxDQUFDQSxxQ0FBcUNBLENBQUNBLENBQUNBO1FBQ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LmdyZWV0aW5nO1xyXG4gICAgfVxyXG59IiwiaW1wb3J0IG1vZGVsID0gcmVxdWlyZSgnLi9HcmVldGVyJyk7XHJcbnZhciBncmVldGVyID0gbmV3IG1vZGVsLkdyZWV0ZXIoXCJ3b3JsZFwiKTtcclxuY29uc29sZS5sb2coZ3JlZXRlcik7XHJcblxyXG52YXIgYnV0dG9uID0gZG9jdW1lbnQuY3JlYXRlRWxlbWVudCgnYnV0dG9uJyk7XHJcbmJ1dHRvbi50ZXh0Q29udGVudCA9IFwiU2F5IEhlbGxvXCI7XHJcbmJ1dHRvbi5vbmNsaWNrID0gZnVuY3Rpb24oKSB7XHJcblx0YWxlcnQoZ3JlZXRlci5ncmVldCgpKTtcclxufVxyXG5cclxuZG9jdW1lbnQuYm9keS5hcHBlbmRDaGlsZChidXR0b24pO1xyXG4iLG51bGxdLCJzb3VyY2VSb290IjoiL3NvdXJjZS8ifQ==
I guess that I need to reference it using require.js, but since this is a single file I have no idea how can I call a required module.
What I need ideally is just a single *.min.js file without require.js at all.
EDIT:
I have made a research and found this great article:
http://www.davidkudera.com/2015/02/28/typescript-gulp-bower-browserify/
You need to:
Load require.jsusing a <script> tag.
Create a require.config.js file and load it using a <script> tag.
Load your file output.js using a <script> tag.
Another option is to compile your modules into CommonJS modules (The following is an example from one of my projects):
var gulp = require("gulp"),
browserify = require("browserify"),
source = require("vinyl-source-stream"),
buffer = require("vinyl-buffer"),
tsc = require("gulp-typescript");
var tsProject = tsc.createProject({
removeComments : false,
noImplicitAny : false,
target : "ES5",
module : "commonjs",
declarationFiles : false
});
gulp.task("build-source", function() {
return gulp.src(__dirname + "/source/**/**.ts")
.pipe(tsc(tsProject))
.js.pipe(gulp.dest(__dirname + "/build/source/"));
});
You can then use Browserify to create one single file that you can load directly in your browser:
gulp.task("bundle-source", function () {
var b = browserify({
standalone : 'inversify',
entries: __dirname + "/build/source/inversify.js",
debug: true
});
return b.bundle()
.pipe(source("inversify.js"))
.pipe(buffer())
.pipe(gulp.dest(__dirname + "/bundled/source/"));
});