Caius
Caius

Reputation: 2264

Export object from typescript through webpack and use it in JS

What I'm trying to do is to bundle a library that I've wrote in Typescript with Webpack 2 and to be able to use this library even with vanilla JS. The building goes fine and without errors, but when it comes to use the exported object it appears like an empty object {}.

So what I've tried to do is the following:

Typescript file

import {SomeStuff} from 'some-stuff';

export class ClassA {
    constructor(){
        // Does other stuff with SomeStuff
    }
}

// What I want to achieve is something like this
export const myModule = new ClassA();

I thought that creating an html file that imports the bundle and my-js-script file were enough in order to have access to the myModule constant. But unfortunately it wasn't enough.

index.html

<html>
    <head>
        <script src="./bundle.js"></script>
        <script src="./my-js-script.js"></script>
    </head>
    <body>
    </body>
</html>

Javascript file

myModule.doSomething();

What am I missing? Or there's simply non chances to do that? The webpack configuration is dead simple

var path = require("path");

module.exports = {
    entry: "./src/web-onion.ts",
    output: {
        path: path.resolve(__dirname, 'dist/'),
        filename: "bundle.js"
    },
    resolve: {
        extensions: [".webpack.js", ".web.js", ".ts", ".tsx", ".js"]
    },
    module: {
        loaders: [
            { test: /\.tsx?$/, loader: "ts-loader" }
        ]
    }
}

Upvotes: 2

Views: 1294

Answers (1)

lilezek
lilezek

Reputation: 7374

You can't do that this way. myModule won't be exported as a global. If you want to export something globally, use in the TypeScript file:

window.something = myModule

Note: you will have to either extend Window interface or use (window as any).

Upvotes: 3

Related Questions