How to use the require function and TypeScript modules with tsify and watchify?

94 Views Asked by At

I am using tsify with watchify and VS Code. The compilation is successful without any warning or error.

I use this command:

cd html/wp-content/themes; watchify custom-theme/assets/ts/main.ts -p [ tsify ] -o custom-theme/assets/js/bundle.js -v

The utils.ts contents:

export module Utils {
    function getBrowserLanguage() : string {
        ...
    }

    function formatTime(secs: number): string {
        ...
    }
}

In each file where I use Utils, I put this:

const Utils = require("./utils");

at the top of the file.

The problem is that in the browser I get this console error:

ReferenceError: Utils is not defined (bundle.js)

All the TypeScript files are in the same folder.

This is my tsconfig.json file:

{
    "compilerOptions": {
        "removeComments": true,
        "preserveConstEnums": true,
        "sourceMap": true,
        "outDir": "wp-content/themes/custom-theme/assets/js",
        "watch": true,
        "allowJs": true,
        "lib": ["ES2020", "DOM"]
    },
    "include": [
        "wp-content/themes/custom-theme/assets/ts"
    ],
    "exclude": [
        "node_modules",
        "**/*.spec.ts"
    ]
}

What can I do to make the code work in the browser without that error?

Thank you.

Update 1

This is the repo with a simplified example.

0

There are 0 best solutions below