Reputation: 1269
EDIT :
02/09 - It seems that the import code is fine (like the one in the response), but my class code is not good (bad ES6 ? bad transpilation ?)
Initial post :
I'm trying to import a remote class from my electron app.
Is it possible ?
I found some solution like :
var vm = require('vm')
var concat = require('concat-stream');
require('http')
.get(
{
host: 'localhost',
port: 8123,
path:"/dist/SomeViewModel.js"
},
function(res) {
res.setEncoding('utf8');
res.pipe(concat({ encoding: 'string' }, function(remoteSrc) {
vm.runInThisContext(remoteSrc, 'remote_modules/SomeViewModel.js')
}));
} );
it seems to tun without error, but I don't understand how to use it ...
var someVM = new SomeViewModel()
doesn't work for example (not surprised ...).
Here is SomeViewModel :
export default class SomeViewModel {
constructor(options) {
this.element1 = options.element1,
this.element2 = options.element2
};
}
The class is babelized and becomes that :
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var SomeViewModel = function SomeViewModel(options) {
_classCallCheck(this, SomeViewModel);
this.element1 = options.element1, this.element2 = options.element2;
};
exports["default"] = SomeViewModel;
module.exports = exports["default"];
},{}]},{},[1]);
//# sourceMappingURL=SomeViewModel.js.map
Is that a good way to go ? (I know about security, it's just how to)
Upvotes: 1
Views: 1765
Reputation: 832
In this case I would download the file and store it on disk, and once it is finished, require the file.
var http = require('http'),
fs = require('fs');
var file = fs.createWriteStream('./tmp/SomeViewModel.js');
http.get({
// your options
}, function (res) {
// set encoding, etc.
res.pipe(file);
file.on('finish', function() {
file.close(function() {
// do stuff
// var SomeViewModel = require('./tmp/SomeViewModel.js');
});
});
});
Upvotes: 1