简体   繁体   中英

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

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM