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

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!

Related

Typescript imports destroys lookup?

I am trying to use a nodejs library like uuid in my typescript app. This simple import works just fine if I want to only use it in a specific class:
import { v4 } from "uuid";
class MyClass {
...
}
However, this makes the class MyClass not "discoverable" by any other files in my solution. Sure I could export it, but that forces me to import the class in every usage, and the problem spreads like a cancer to every file. Do I really have to import/export every single class/file in my application just because I want to produce a simple UUID?
I saw that I can use require instead, however typescript doesn't know what that keyword is. I found this question but neither installing #types/node nor the quick and dirty declare var require any works.
It really seems like I am jumping through a lot of unnecessary hoops just to generate a uuid in typescript. Am I doing something very wrong?
Thanks

importing typescript functions from one file to another

I am trying to import a function for use in my main.ts file, but i either get 'is not a module' or 'unexpected import token' when i use node main.ts to run my file.
These are not node modules and i'm not using any framework.
// main.ts
import * as forms from "./script/form";
forms.autoForm();
// form.ts
export function autoForm() {
// something
}
They are modules, and depending on your typescript configuration can be emitted as many different module formats.
Typescript is a compile time language, in order to run it it must be transformed into javascript first.
You can also see this question for details on how to run typescript files directly with node using tsc watch mode.

Using node require with Electron and Webpack

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

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());
};

Resources