Saturday, June 1, 2024
 Popular · Latest · Hot · Upcoming
94
rated 0 times [  96] [ 2]  / answers: 1 / hits: 19594  / 8 Years ago, fri, july 22, 2016, 12:00:00

I'll preface by saying I don't have advanced knowledge of TypeScript or JavaScript.



What I did



I'm making a barebones TypeScript algorithmic toy-box that implements algorithms from Fundamentals of Algorithmics (Brassard and Bratley). What I do is open a local HTML file and the transpiled TypeScript modifies the DOM to show the output (just like the Greeter example on the TypeScript webpage).



Everything was going fine until I decided to use separate files for each class. I used one of the many ways available to reference TypeScript files, but I'm not sure if it was the best suited. I also created a default tsconfig.json file with the Atom TypeScript plugin thinking that the compiler would now assume all .ts in the directory are the same module or something, but I guess that wasn't the case.



main.ts:



import { Monticulo } from ./stuff/monticulo.ts
import { ProgDin } from ./programacion-dinamica.ts

let arr5_13 = [1,6,9,2,7,5,2,7,4,10]
let mon1 = new Monticulo(arr5_13)
// ...

document.body.innerHTML = mon1.console_debug


The problem



When I open the HTML file on a browser, the console says Uncaught ReferenceError: require is not defined.



Sure enough, the transpiled code has a require() call:



main.js:



var monticulo_ts_1 = require(./stuff/monticulo.ts);
var arr5_13 = [1, 6, 9, 2, 7, 5, 2, 7, 4, 10];
// ...

document.body.innerHTML = mon1.console_debug;


What I've tried



I initially ran it on Firefox 47.0, then I tried running in Chromium 51.0 (in case it was browser related) but I got the same error. I'm on Ubuntu 16.04 for the sake of completeness.



I've read that require() is a function that is not implemented client-side, yet Node has it implemented and it's needed for using npm modules in-browser, but why would TypeScript need to call any npm module? Why doesn't main.js just reference the transpiled .js instead of the .ts itself? I'm pretty sure I'm missing one or more pieces of information.


More From » typescript

 Answers
13

You are probably compiling down to the commonJS module format (check your tsconfig.json)



That means it generates require function calls for you and it is your responsibility to provide a commonjs loader. You also probably want to bundle all your files into one. It just so happens that webpack does both and is very often used together with typescript :)


[#61280] Wednesday, July 20, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
minab

Total Points: 701
Total Questions: 104
Total Answers: 91

Location: Saint Pierre and Miquelon
Member since Fri, Jan 28, 2022
2 Years ago
;