Search code examples
node.jstypescriptrequirejs

How to load external modules from node


I'm a bit stuck without really knowing what to do next, being searching for an answer without really find any working solution after all attempts I've tried...

I've made a very simple project to demonstrate my current issue, you can see it on github or even downloaded and run it on your machine.

This final idea is to have a /dist/clients.js file with the project itself, so I can use it in an HTML file (/dist/index.html) and as I can't use CommonJs as my typescript load module (I have several files and not only one) I've chosen amd loader (hence the requirejs call in the HTML file).

<html>
    <head></head>
    <body>
        <h1>TS Testing...</h1>
        <script src="//cdnjs.cloudflare.com/ajax/libs/require.js/2.3.3/require.min.js" type="text/javascript"></script>
        <script src="client.js" type="text/javascript"></script>
        <script type="text/javascript">
            require(['clients/client'],
                function(require) {
                    var sc = new require();
                }
            );
        </script>
    </body>
</html>

typescript runs fine from grunt ts and creates the client.js with mapping

The problem I have is that it does not load the entire project, throwing an error:

that comes from the file /libs/core/tc-cookies.ts:

var JsCookie: Cookies.CookiesStatic = require("js-cookie");

How can I load the npm module in a way that I can use my project correctly? I have moduleResolution: "node" in the ts-loader options, but does not seem to do the right job...


Github project available for this question


Solution

  • The problem is that the order of loading the context in not known in the current state of your project, you can write some code to provide a proper order of module loading or use some sort of module loader, like webpack or browserify. What I strongly suggest is to choose webpack and ts-loader which is common one choice for typescript module loading.

    Steps to get rid of that error:

    1. Change your tsconfig.json, it should look like this:
    {
      "compilerOptions": {
        "target": "es6",
        "module": "commonjs",
        "sourceMap": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "removeComments": false,
        "noImplicitAny": false,
        "rootDir": "."
        },
        "compileOnSave": false,
        "exclude": [
          "node_modules"
        ]
    }
    
    1. Delete all script tags in your html.

    2. Create webpack.config.js file. See example of how webpack.config.js should look like on ts-loader npm's page. (section configuration)

    3. Create script tag in your html with a path of webpack's output.