1
votes

I'm trying to get typescript and lodash to work in my app but when I run

tsc --module commonjs lodash-test.ts

Im always getting

lodash-test.ts(2,20): error TS2307: Cannot find module 'lodash'.

This still produces a lodash-test.js file

"use strict";
//lodash test that will be injected in index.html
var _ = require("lodash");
console.log('This is your lodash ts file');
console.info(_.chunk(['a', 'b', 'c', 'd'], 2));

Now when I run my index.html file in my browser, I'm getting

lodash-test.js:3 Uncaught ReferenceError: require is not defined

on line 3 of the file.

Index.html file

<!DOCTYPE html>
<html>    
<head>
    <meta charset=utf-8 />
    <title></title>
    <script type="text/javascript" src="bower_components/lodash/dist/lodash.min.js"></script>
    <script type="text/javascript" src="lodash-test.js"></script>    
</head>    
<body>
    <h3>Hey</h3>
</body>    
</html>

I have the lodash type definition in my typings folder. How can I make sure that Typescript can find this lodash/index.d.ts file? Also how can I fix the "require is not defined" error?

This is my file structure:

enter image description here

thanks for the help

1
Try to import d.ts typings file with a /// <reference path="" /> command on top of your TypeScript file. Because for now, tsc has now clue that you have typings files. So it can't find it. - Blackus
@Blackus I have changed my lodash-test.ts to imgur.com/n8Kp5pv and it produced what is on the right side of the image. I've also removed the <script> lodash library in my index.html. I am still getting the same error - gerl

1 Answers

0
votes

var _ = require("lodash"); is not necessary with the way you are loading your scripts.

In your <head> you have the line:

<script type="text/javascript" src="bower_components/lodash/dist/lodash.min.js"></script>

which loads _ into the global namespace. require("lodash") is a module loader that loads lodash at runtime.

So:

A) remove the require statement and just use the var _ as though it were already loaded (since it is). You may have to do some tricky stuff with the declare keyword to get tsc to not complain that _ is undefined.

B) Remove the <script> for lodash in your <head> and setup require properly so that it knows what "lodash" is. Otherwise you might be able to simple do something like var _ = require('bower_components/lodash/dist/lodash.min');