0

I'm working on a pure frontend project using VS Code. I have a folder for typescript and another one for sass. I'm compiling those with Gulp in separate folders for js and css.

I faced a problem when I tried to use var something = require('some-node-module'); and got an error both in typescript and browser console. I added @types for this but it didn't worked as I still got an error in browser console. I searched more and found this question, I understood what the problem is and I used Browserify from there. Now typescript is compiled without errors and I have to make a bundle everytime I change something. Is there anything I can do to get rid of Browserify and still be able to use require() in typescript. As this is my first pure frontend project I want to keep it simple and clean, not to use a lot of plugins/modules to make it work.

My tsconfig.json:

{
"files": [
    "ts/main.ts"     
],
"compilerOptions": {
    "noImplicitAny": true,
    "target": "es5",
    "outDir": "js"
}
}

Is there any way I can use types without the need to install more node modules to make it work?

Chris
  • 6,105
  • 6
  • 38
  • 55

2 Answers2

1

When you use require() or import, then you are using modules. When you use modules, you need a module bundler such as browserify or webpack.

But you don't HAVE to use modules in a typescript project. The typescript compiler automatically concatenates all your separate .ts files into one .js bundle already. You need to set the output file in tsconfig.json:

{
    "compilerOptions": {
        "sourceMap":  true,
        "removeComments": true,
        "target":"es5",
        "out": "dist/js/main.js"
    }
}

A separate .ts file might look like this:

class Test {
   constructor(){
      console.log("hi!");
   }
}

The difference with using modules is that your Test class will be placed in the global scope, but you could prevent that by using a namespace where you put all your classes:

namespace Game {
    export class Test {
       constructor(){
          console.log("hi!");
       }
    }
}

Now there is only one object called 'Game' in the global scope and you don't need a module bundler to create that single .js file.

Kokodoko
  • 26,167
  • 33
  • 120
  • 197
1

Every Front End project needs Browserify or Webpack (recommended) which will bundle your modules into browser compatible script. require() is nodejs' function which imports other modules/scripts but it doesn't exist in browser ecosystem.

Read about webpack here.

Michał Pietraszko
  • 5,666
  • 3
  • 21
  • 27