2

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:

  • Bundle the library in a bundle.js file
  • Create a my-js-script.js file that logs to the console the object exported by the .ts file
  • Create a index.html file
  • Import both the bundle.js and my-js-script.js files
  • Serve the index.html file and see the object in the console.

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" }
        ]
    }
}

1 Answer 1

3

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).

Sign up to request clarification or add additional context in comments.

6 Comments

I've tried your solution, it works partially. I can successfully log the object in console, but all the properties and methods are encapsulated inside the prototype. Any chances to have them accessible via: myModule.met() instead of myModule.__proto__.constructor.met()?
This is how objects are supposed to work in JavaScript. Did you mean to access ClassA?
Did you mean that you are not able to do myModule.anyMethod()? Because that is not a normal behaviour.
Have you tried just to call myModule.met();? It should work.
Use TypeScript instead of JavaScript.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.