Using node require with Electron and Webpack - node.js

I am building a project with Electron, and using Webpack to build the (Angular 2) render process app.
In this app, I need to dynamically require some files at run-time which do not exist at build-time. The code looks something like this:
require("fs").readdirSync(this.path).forEach(file => {
let myModule = require(path.join(this.path, file));
// do stuff with myModule
});
The problem is that the Webpack compiler will convert the require() call to its own __webpack_require__() and at run-time, it will look in its own internal module registry for the dynamic "myModule" file, and of course will not find it.
I have tried using the "externals" config option, but since this is a dynamic require, it doesn't seem to be processed by "externals".
Anyone else had success in solving this problem?

As suggested in a comment to my question by #jantimon, the solution is to use global.require:
require("fs").readdirSync(this.path).forEach(file => {
let myModule = global.require(path.join(this.path, file));
// do stuff with myModule
});

I came across this article and for some other reason the author needs node modules which gets not transpiled by webpack. He suggested to use
new webpack.IgnorePlugin(new RegExp("^(fs|ipc)$"))
in the webpack.config.js file. This should prevent to transpile the module fs and ipc so it can be used (required) in code.
I am not really sure if this hits also your problem but it might help.
The original article for more context can be found here: https://medium.com/#Agro/developing-desktop-applications-with-electron-and-react-40d117d97564#.927tyjq0y

Related

How to use multiple compiled ts files in a node module?

Currently I am trying to use TypeScript to create JavaScript-Files which are then required in a index.js file. I am using VS 2015 Update 3 with node.js tools 1.2 RC. Sadly it is not working like I thought it would.
To begin with here is my initial idea:
I have a node module (to be precise, it is a deployd module http://docs.deployd.com/docs/using-modules/). This module is handling payment providers like paypal or stripe. Now I want to use TypeScript to write interfaces, classes and use types to make it easier to add new payment providers. The old .js files should still be there and used. I want to migrate step by step and use the self-written and compiled .js files together. So I thought I can create .ts files, write my code, save, let VS compile to js and require the compiled js file in another js file. Okay, that is my idea... Now the problem
I have a PaymentProvider.ts file which looks like this
import IPaymentProvider = require("./IPaymentProvider.ts"); // Interface, can't be realized in JavaScript, just TypeScript
export abstract class PaymentProvider implements IPaymentProvider.IPaymentProvider
{
providerName: string;
productInternalId: number;
constructor(providerName : string)
{
this.providerName = providerName;
}
//... some methods
};
The other file is PaypalPaymentProvider.ts
import PaymentProvider = require("./PaymentProvider.ts");
export class PaypalPaymentProvider extends PaymentProvider.PaymentProvider
{
constructor()
{
super("paypal");
}
// more methods
}
VS 2015 doesn't show any errors. The js and .js.map files are generated. Now I thought I could require the files and that's it. I tried to use the PaypalPaymentProvider.js like this const PaypalPaymentProvider = require("./lib/payment-provider/PaypalPaymentProvider.js"); (yes, it is located there) but it's not working. When starting the index.js via node I get the following error:
...\Path\PaymentProvider.ts:1 (function (exports, require, module, __filename, __dirname) { import IPaymentProvider = require("./IPaymentProvider.ts"); Unexpected token import....
I find it strange that this is the error, because JavaScript doesnt't have Interfaces. The compiled IPaymentProvider.js is empty.
Also I thought that TypeScript is mainly for development and the compiled JavaScript for production. So why it is requiring a ts-file? I thought imports in typescript will be converted to require of the compiled js-file?
Do I need to require all compiled js files and not only the one I currently try to use? (I don't think so...)
To be honest, I think the main problem is that I am new to TypeScript and make something wrong from the very beginning.
Any help/advice? Thanks!
I have the solution... Thanks to Paelo's links I was able to see that I need to omit the file ending! So the really simple solution was to write
import IPaymentProvider = require("./IPaymentProvider");
instead of
import IPaymentProvider = require("./IPaymentProvider.ts");
When I changed that in every ts file it worked perfectly!

how can I import json file in typescript

I am using typescript and requirejs. For the most part the amd modules are generated beautifully. I am however stuck with loading using requirejs json or for that matter text plugin.
define(["json!sometextfile.json"], function(myJson)
How can I do this in typescript. I am using TS 1.6 at the moment.
I'm not sure I have understood your question, but I think you want to know how to call require directly without getting a compiler error... for example:
require(["json!sometextfile.json"], function(myJson) {
});
The quick fix for this is to supply a very open definition for the require function:
declare var require: any;
require(["json!sometextfile.json"], function(myJson) {
});
You can improve upon this crude fix by using the full RequireJS type definition from the Definitely Typed project.

How to compile TypeScript code in the browser?

Is it possible to run the TypeScript compiler in the browser for transpiling TS to JS 100% in the browser. The use case would be implementing an online TypeScript IDE that runs 100% client side and it has a "Play" button to execute the project. So I need to transpile the project to JavaScript in order for the browser to execute the code.
I presume it should be as simple as loading the relevant typescript JS files, creating an instance of the right class (compiler?) and calling a method or two.
What would be the means suitable to load the Compiler in the browser? Where is the TypeScript Compiler API Reference Documentation ? Where should I start digging in ?
This isn't asking for any specific tool, but ANY way to do this with this particular computer language, and thus is on topic.
You can use typescript-script : https://github.com/basarat/typescript-script
However do not do this in production as it is going to be slow.
You can use webpack (or a similar module bundler) to load npm packages in the browser.
Transpiling ts to js is as simple as loading the typescriptServices.js file from typescript repo or npm, and using it's window.ts.transpile(tsCode)
JSFiddle
<script src="https://unpkg.com/typescript#latest/lib/typescriptServices.js"></script>
<script>
const tsCode = 'let num: number = 123;';
const jsCode = window.ts.transpile(tsCode);
document.write(jsCode);
</script>
Outputs:
var num = 123;
You can also pass the ts compiler options object as second argument to ts.transpile() to specify whether output js should be es2020, es5, es6, and other stuff, though for meaning of values you'll likely have to dive into the source code.
Since this question got re-opened (just as planned >:D), I'm also re-posting my comment here.
#basarat's solution was great; even though his lib is outdated and abandoned, it helped me a lot in writing another, self-sufficient modern lib with support for sub-dependencies: ts-browser
Usage: (given you use relative paths in all your ts files)
<!-- index.html -->
<script type="module">
import {loadModule} from 'https://klesun.github.io/ts-browser/src/ts-browser.js';
loadModule('./index.ts').then(indexModule => {
return indexModule.default(document.getElementById('composeCont'));
});
</script>
// index.ts
import {makePanel} from './utils/SomeDomMaker'; // will implicitly use file with .ts extension
export default (composeCont) => {
composeCont.appendChild(makePanel());
};

Typescript/RequireJS having issues with an MVC application

I have the following code in Visual Studio, in an MVC application;
/scripts/bin/models/ViewModel.ts
export class ViewModel {
// view model code
}
Now, I have downloaded requirejs, and set the build mode for typescript to AMD type, so that its output looks such as....
define(["require", "exports"], function(require, exports) {
And so on ...
So then I declare my app/config.js file like so;
require.config({
baseUrl: '/scripts/bin'
});
And I try to load this up, I have requirejs loaded into the scripts, and attempt to call it...
require(['models/ViewModel'], function (viewModel) {
console.log("test");
});
And I am simply told that it is an invalid call. No other details. The path that it shows is completely correct, too. Is there some kind of additional configuration required? The requirejs documentation is extremely vague about this.
SOLUTION
This turned out to have nothing to do with requirejs, but instead had to do with IIS.
By default, IIS has a rule known as hiddenSegments. It does not allow you to bring in any code from a folder with bin in the path. I simply renamed the folder from bin to something else, and it worked fine.
Using require.js with TypeScript is a combination of your .html, require.config, module exports and imports.
For a step-by-step guide on moving from CommonJs TypeScript to AMD and require.js, have a look here.
Have fun.
The TypeScript compiler doesn't have any knowledge of your require.config - so when you use paths relative to that baseUrl they look invalid to the compiler.
Until something is done to bridge that slight mismatch (i.e. make the compiler super-clever so it can look for require.config sections and use them to check paths) it is easier not to set a baseUrl and use the full path in your import statements:
import vm = require('./scripts/bin/models/ViewModel');
Are you sure that the require call is done with [] and not just
require('models/ViewModel', function (viewModel) { // this is an error
console.log("test");
});
See : http://requirejs.org/docs/errors.html#requireargs

RequireJs optimization of template script

I have some client javascript and scala page template.
I have to init some js stuff in the template (by params provided to template using scala).
But now we try to migrate to requirejs and we don't want to use global variables (like window.funnyVar) and we want to do all js stuff in the modules.
So, there is the following problem: how to init stuff in the module by params provided to scala template.
I do it in the following way. In the template code I define new module and pass all params to it:
define("templateModule", ["lib/helper"],
function(helper){
helper.init(#param);
return {};
});
In the main js file I do all other stuff after the initialization:
require(["lib/helper", "templateModule"],
function(helper, tpl) {
// do stuff
}
);
It works fine until I run prod mode.
In the prod mode I have the following error:
JavaException: java.io.FileNotFoundException: /home/gkalabin/app/target/scala-2.10/classes/public/javascripts-min/templateModule.js (No such file or directory)
In module tree:
main
How can I resolve this issue?
upd
Possible solution to switch from module (define) to require. But may be there are another solutions?
Thank for your attention. Have a good day!

Resources