Getting Monaco to work with Vuejs and electron - javascript

I'm interested in using the Monaco editor in a Vue.js backed Electron project.
Thus far:
Microsoft provides an Electron Sample (which I've run and works correctly)
There are a variety of vue.js npm repos for monaco - yet none of them seem to fully support Electron right out of the box.
The one that looks most promising is vue-monaco but I've run into issues correctly integrating it.
AMD Require?
This is the code from the Microsoft sample for using with Electron
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Monaco Editor!</title>
</head>
<body>
<h1>Monaco Editor in Electron!</h1>
<div id="container" style="width:500px;height:300px;border:1px solid #ccc"></div>
</body>
<script>
// Monaco uses a custom amd loader that overrides node's require.
// Keep a reference to node's require so we can restore it after executing the amd loader file.
var nodeRequire = global.require;
</script>
<script src="../node_modules/monaco-editor/min/vs/loader.js"></script>
<script>
// Save Monaco's amd require and restore Node's require
var amdRequire = global.require;
global.require = nodeRequire;
</script>
<script>
// require node modules before loader.js comes in
var path = require('path');
function uriFromPath(_path) {
var pathName = path.resolve(_path).replace(/\\/g, '/');
if (pathName.length > 0 && pathName.charAt(0) !== '/') {
pathName = '/' + pathName;
}
return encodeURI('file://' + pathName);
}
amdRequire.config({
baseUrl: uriFromPath(path.join(__dirname, '../node_modules/monaco-editor/min'))
});
// workaround monaco-css not understanding the environment
self.module = undefined;
// workaround monaco-typescript not understanding the environment
self.process.browser = true;
amdRequire(['vs/editor/editor.main'], function() {
var editor = monaco.editor.create(document.getElementById('container'), {
value: [
'function x() {',
'\tconsole.log("Hello world!");',
'}'
].join('\n'),
language: 'javascript'
});
});
</script>
</html>
The module I'm using allows for something like this:
<template>
<monaco-editor :require="amdRequire" />
</template>
<script>
export default {
methods: {
amdRequire: window.amdRequire
// Or put this in `data`, doesn't really matter I guess
}
}
</script>
I can't seem to figure out how to get the correct amdRequire variable defined in Electon + vue. I believe if i can conquer this everything else becomes simple.
The Electron FAQ mentions something about this (i think): I can not sue jQuery/RequireJS/Meteor/AngularJS in Electron
Sample Code
I put a sample project up on GitHub https://github.com/jeeftor/Vue-Monaco-Electron with the "offending" component being in ./src/renderer/components/Monaco.vue
Summary
How can I get this Monaco Editor to load correctly inside of a Vue.js component that will be run inside electron?
Thanks for any help you can offer.

I'm doing nearly the same, just without the extra vue-monaco component. After struggling quite a bit, I could solve the problem:
function loadMonacoEditor () {
const nodeRequire = global.require
const loaderScript = document.createElement('script')
loaderScript.onload = () => {
const amdRequire = global.require
global.require = nodeRequire
var path = require('path')
function uriFromPath (_path) {
var pathName = path.resolve(_path).replace(/\\/g, '/')
if (pathName.length > 0 && pathName.charAt(0) !== '/') {
pathName = '/' + pathName
}
return encodeURI('file://' + pathName)
}
amdRequire.config({
baseUrl: uriFromPath(path.join(__dirname, '../../../node_modules/monaco-editor/min'))
})
// workaround monaco-css not understanding the environment
self.module = undefined
// workaround monaco-typescript not understanding the environment
self.process.browser = true
amdRequire(['vs/editor/editor.main'], function () {
this.monaco.editor.create(document.getElementById('container'), {
value: [
'function x() {',
'\tconsole.log("Hello world!");',
'}'
].join('\n'),
language: 'javascript'
})
})
}
loaderScript.setAttribute('src', '../node_modules/monaco-editor/min/vs/loader.js')
document.body.appendChild(loaderScript)
}
I've just taken the electron-amd sample and adjusted it a bit. I call the loadMonacoEditor function in the components' created function.
In order to not get the Not allowed to load local resource: file:///C:/.../node_modules/monaco-editor/min/vs/editor/editor.main.css problem, you also have to set
webPreferences: {
webSecurity: false
}
in your instance of the BrowserWindow.

Related

Creating a JS library with IIFE namespacing

If we don't want to use ES6 import nor any third party libraries (like require.js etc.) nor any package builder, what is the classical way to pack a library so that the user can use it with what seems to be a library-namespace?
index.html (from the perspective of the user of the library)
<canvas id="mycanvas"></canvas>
<script src="canvas.js"></script>
<script>
canvas.setup({"config1": true, "config2": false});
var mycanvas1 = canvas.get("#mycanvas");
</script>
I sometimes see code similar to
// canvas.js
(function (window, something, else) {
window.canvas.setup = function() { ... } // how to export functions setup and get?
})(window, ..., ...);
How to do this IIFE properly to create this canvas.js library example?
Note: with ES6 import, we can package this way a library called canvas.js:
const canvas = {
setup: config => { console.log("config"); },
get: id => { console.log("get"); }
};
export default canvas;
and use it a index.html this way:
<canvas id="mycanvas"></canvas>
<script type="module">
import canvas from "./canvas.js";
canvas.setup({"config1": true, "config2": false});
var mycanvas1 = canvas.get("#mycanvas");
</script>
but in this question here I am curious about the pre-ES6 solution.
A solution seems to be:
// canvas.js
canvas = (function(window) { // assign the result of the IIFE to a global var to make
// it available for the user of the lib
var internal_variable; // not accessible to the user of the lib
var state; // this variable will be available to the user of the lib
function setup(arg) {
console.log("setup");
}
function get(arg) {
console.log("get"); // + other lines using window object
}
return {setup: setup, get: get, state: state}; // important: here we choose what we
// export as an object
})(window);
Now the user can use the library this way:
<canvas id="mycanvas"></canvas>
<script src="canvas.js"></script> // object canvas is now available
<script>
canvas.setup({"config1": true, "config2": false});
var mycanvas1 = canvas.get("#mycanvas");
console.log(canvas.state);
</script>

ES6: Classes: Can't get external JS class to work

Just so I'm clear, here's what I have, maybe someone can confirm.
1) ES6 Classes defined inside an HTML file work fine. let x = new glob(213); // works good
2) But total failure, once I move class glob code to an external JS and reference it with . The new glob(213); fails. Even if I Babel glob.js to create ES5 code.
Is this the current state of play with ES6 classes? I'm not using import but do have export. Or do I need to use a bundler, like Webpack, to smoosh everything into a single all.js to get external classes to work?
Rather disappointed if this is the current state of play, or am I being overly demanding. (We've been using external files use for decades.)
Thanks, from a frustrated JS coder.
INTERNAL version
<body style="font-family: sans-serif; line-height: 2">
<p id="showResults" style="font-size: 20pt;"></p>
<script>
class glob {
constructor(mass) {
this.mass = mass;
}
getMass() {
return this.mass;
}
}
let gg = new glob(213);
let gm = gg.getMass();
showAll = " ";
showAll += `glob mass = ${gm}<br>`
document.getElementById("showResults").innerHTML = showAll;
</script>
</body>
EXTERNAL VERSION
'use strict';
class glob {
constructor(mass) {
this.mass = mass;
}
getMass() {
return this.mass;
}
}
export default glob;
Then in HTML
<body style="font-family: sans-serif; line-height: 2">
<p id="showResults" style="font-size: 20pt;"></p>
<script src="build/glob.js"></script>
<script>
alert(1); //Shows
let gg = new glob(213);
alert(2); // Never shows
And Babel
npm run babel -silent -- --presets es2015 src/g*.js --out-dir build

Load module with parameter after bundle

I've got the following codeblock in the layout.js
import $ from "jquery";
import LayoutModel from 'js/models/LayoutModel';
let elements = {
$window: $(window),
$html: $('html'),
$content: $('#content')
};
let viewmodel = null;
export function init(options) {
viewmodel = new LayoutModel(options, elements);
ko.applyBindings(viewmodel, elements.$content[0]);
}
and I load it in the view with system.js and call the init() with options. The options contains values and it has to be in the view because some of it comes from the back-end model.
System.import('resources/javascript/layout').then(function(controller) {
var options = {
something: 'value'
};
controller.init(options);
});
This solution works while it's not bundled with jspm:
jspm bundle resources\javascript\layout resources\javascript\dist\layout.min.js --minify
In production I have to do it, but in this case I'm not able to use the system.import() and the .then(), because I have to load the bundled script with a normal <script> tag:
<script src="resources\javascript\dist\layout.min.js"></script>
So the question: How can I bundle and minify it and call the init() method with the options?
Thank you!

Defining Polymer element after importing ES6 code via System.js

I'm creating an HTML element using Polymer, and I want it to be able to work with an ES6 class I've written. Therefore, I need to import the class first and then register the element, which is what I do:
(function() {
System.import('/js/FoobarModel.js').then(function(m) {
window.FoobarModel = m.default;
window.FoobarItem = Polymer({
is: 'foobar-item',
properties: {
model: Object // instanceof FoobarModel === true
},
// ... methods using model and FoobarModel
});
});
})();
And it works well. But now I want to write a test HTML page to display my component with some dummy data:
<!DOCTYPE html>
<html lang="en">
<head>
<script src="/bower_components/webcomponentsjs/webcomponents.js"></script>
<script src="/bower_components/system.js/dist/system.js"></script>
<script>
System.config({
map:{
traceur: '/bower_components/traceur/traceur.min.js'
}
});
</script>
<link rel="import" href="/html/foobar-item.html">
</head>
<body>
<script>
(function() {
var data = window.data = [
{
city: {
name: 'Foobar City'
},
date: new Date('2012-02-25')
}
];
var view;
for (var i = 0; i < data.length; i++) {
view = new FoobarItem();
view.model = data[i];
document.body.appendChild(view);
}
})();
</script>
</body>
</html>
Which isn't working for one simple reason: the code in the <script> tag is executed before Polymer registers the element.
Thus I'd like to know if there's a way to load the ES6 module synchronously using System.js or even better, if it's possible to listen to a JavaScript event for the element registration (something like PolymerElementsRegistered)?
I've tried the following without success:
window.addEventListener('HTMLImportsLoaded', ...)
window.addEventListener('WebComponentsReady', ...)
HTMLImports.whenReady(...)
In the app/scripts/app.js script from the polymer starter kit, they use auto-binding template and dom-change event
// Grab a reference to our auto-binding template
var app = document.querySelector('#app');
// Listen for template bound event to know when bindings
// have resolved and content has been stamped to the page
app.addEventListener('dom-change', function() {
console.log('Our app is ready to rock!');
});
Also check this thread gives alternatives to the polymer-ready event.

How to setup a service from a base module to call a function on a service in a module that uses the base module in angularjs

I an writing a service that is to be used in multiple independent websites. However, at some points it needs to trigger different code depending on what website it is used in. I want to keep this per website code separate from the base service.
Here is some example code demonstrating the design I want (although it isn't working):
var baseModule = angular.module('baseModule', []);
baseModule.service('baseService', function() {
this.func = function() {
return ["first",
/* TODO somehow get from appropriate
service in website module */
"FIXME",
"end"];
};
});
var website1 = angular.module('website1', ['baseModule']);
website1.service('website1Service', function() {
this.someCustomValue = function() {
// Note that while this is a constant value, in
// the real app it will be more complex,
// so replacing this service with a constant provider won't work.
return "someValue";
}
});
// TODO : somehow link website1Service.someCustomValue to baseService
var website2 = angular.module('website2', ['baseModule']);
website2.service('website2Service', function() {
this.anotherValue = function() { return "anotherValue"; }
});
// TODO : somehow link website2Service.anotherValue to baseService
// Testing code:
function makeTestController(expected) {
return ['$scope', 'baseService', function($scope, baseService) {
var result = baseService.func();
if (angular.equals(result, expected)) {
$scope.outcome = "Test Passed!";
} else {
$scope.outcome = 'Test failed...\n' +
"Expected: " + angular.toJson(expected) + '\n' +
"But got : " + angular.toJson(result);
}
}];
}
website1.controller('TestController1',
makeTestController(['first', 'someValue', 'end']));
website2.controller('TestController2',
makeTestController(['first', 'anotherValue', 'end']));
// since this test uses multiple angular apps, bootstrap them manually.
angular.bootstrap(document.getElementById('website1'), ['website1']);
angular.bootstrap(document.getElementById('website2'), ['website2']);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<h3>Website 1</h3>
<div id='website1'>
<div ng-controller='TestController1'>
<pre>{{outcome}}</pre>
</div>
</div>
<div id='website2'>
<h3>Website 2</h3>
<div ng-controller='TestController2'>
<pre>{{outcome}}</pre>
</div>
</div>
I've thought of a few solutions to this, but none seem optimal.
The most obvious way would be to replace the baseService service with a provider, and allow it to be configured in each module. This seems to be the standard way of configuring services in other modules. However, I cannot access the website1Service and website2Service in in the provider functions, as services cannot be accessed in provider functions. This is noted in the docs:
During application bootstrap, before Angular goes off creating all services, it configures and instantiates all providers. We call this the configuration phase of the application life-cycle. During this phase, services aren't accessible because they haven't been created yet.
Another solution to work around this is use angular.injector to find the right service. However, the docs for angular.injector imply that you really only need this for interacting with third party libraries. So it appears there is a better way.
Finally, I could add a dependency to a nonexistant service (eg "baseServiceActions") in baseModule, and require a service with that name be implemented in website1 and website2. The dependency injection should then bind it all together when baseService is used. However, this is a pretty weird way of working, and would result in poor error messages if the baseServiceActions module wasn't implemented in a new website that used the baseModule module.
Is there a better way of doing this? If so, is it possible to change the example code I posted to get all the tests passing? Ideally none of the testing code should be changed.
I eventually worked out a fairly good solution to this. I created a service named "<serviceName>Settings", and added a setup function to it. I then call that setup function in a module run block in the module I want to use it in. Finally I have a validate method that is called in the service that uses the settings to ensure it is setup, and throws a nice error message if it isn't. This solved all the problems I had with the other solutions.
This is how my example problem would look with this solution:
var baseModule = angular.module('baseModule', []);
baseModule.service('baseService', ['baseServiceSettings', function(baseServiceSettings) {
baseServiceSettings.validate();
this.func = function() {
return ["first",
baseServiceSettings.getValue(),
"end"];
};
}]);
baseModule.service('baseServiceSettings', function() {
this.setup = function(getter) {
this.getValue = getter;
};
this.validate = function() {
if (!this.getValue) {
throw "baseServiceSettings not setup! Run baseServiceSettings.setup in a module run block to fix";
}
};
});
var website1 = angular.module('website1', ['baseModule']);
website1.run(['baseServiceSettings', 'website1Service', function(baseServiceSettings, website1Service) {
baseServiceSettings.setup(website1Service.someCustomValue);
}]);
website1.service('website1Service', function() {
this.someCustomValue = function() {
// Note that while this is a constant value, in
// the real app it will be more complex,
// so replacing this service with a constant provider won't work.
return "someValue";
}
});
var website2 = angular.module('website2', ['baseModule']);
website2.service('website2Service', function() {
this.anotherValue = function() { return "anotherValue"; }
});
website2.run(['baseServiceSettings', 'website2Service', function(baseServiceSettings, website2Service) {
baseServiceSettings.setup(website2Service.anotherValue);
}]);
// Testing code:
function makeTestController(expected) {
return ['$scope', 'baseService', function($scope, baseService) {
var result = baseService.func();
if (angular.equals(result, expected)) {
$scope.outcome = "Test Passed!";
} else {
$scope.outcome = 'Test failed...\n' +
"Expected: " + angular.toJson(expected) + '\n' +
"But got : " + angular.toJson(result);
}
}];
}
website1.controller('TestController1',
makeTestController(['first', 'someValue', 'end']));
website2.controller('TestController2',
makeTestController(['first', 'anotherValue', 'end']));
// since this test uses multiple angular apps, bootstrap them manually.
angular.bootstrap(document.getElementById('website1'), ['website1']);
angular.bootstrap(document.getElementById('website2'), ['website2']);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<h3>Website 1</h3>
<div id='website1'>
<div ng-controller='TestController1'>
<pre>{{outcome}}</pre>
</div>
</div>
<div id='website2'>
<h3>Website 2</h3>
<div ng-controller='TestController2'>
<pre>{{outcome}}</pre>
</div>
</div>

Categories

Resources