简体   繁体   中英

typescript + lodash - cannot find module

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:

在此输入图像描述

thanks for the help

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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM