Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript importing exported class emits require(...) which produces browser errors

Tags:

I've googled around and apparently not stumbled across the explanation. I'm writing in Typescript with the end-goal of having a .js file (or numerous) that I can reference via script tags in the HTML.

button.ts

...
import * as BF fro "./button-form.ts";
...

... emits ...

button.js

...
var BF = require("./button-form");
...

... which doesn't run in the browser because require() is not defined.

Similarly...

button-form.ts

...
export class ButtonForm {
...

... emits ...

button-form.js

...
exports.ButtonForm = ButtonForm;
...

The Problem

I can't execute this javascript in the browser because of the 'require' and 'exports'. It seems to me it's appropriate in TS to export and import class references but the output isn't something I can use. There must be a knowledge gap here but I'm not sure what I'm looking for.

like image 499
Ronan M Avatar asked May 15 '16 18:05

Ronan M


2 Answers

If you don't intend to use a module system (such as requirejs) then you don't need to import but use /// <reference path="..." />

For example:

A.ts

namespace A {
    export function echo(value: any): void {
        console.log(`A.echo: ${ value }`);
    }
}

B.ts

/// <reference path="A.ts" />

namespace B {
    export function echo(value: any): void {
        A.echo(value);
        console.log(`B.echo: ${ value }`);
    }
}

And in your html:

<head>
    <script src="A.js"></script>
    <script src="B.js"></script>
    <script>
        B.echo("hey");
    </script>
</head>

You can read more about it here: Namespace and Modules

like image 64
Nitzan Tomer Avatar answered Sep 28 '22 03:09

Nitzan Tomer


You can use https://www.npmjs.com/package/require-bro

First include require-bro.js then the rest of the js, last you can use require. Function require simply search in global window object.

<script src="require-bro.js"></script>
<script src="example-one.js"></script>
<script src="example-two.js"></script>

In example-two.js you can do something like:

var exampleOne = require('example-one');
var exampleTwo = {} // do your magic
like image 26
Emilio Platzer Avatar answered Sep 28 '22 03:09

Emilio Platzer