简体   繁体   中英

cannot find module chai though it exists in node modules folder

I tried install chai using the following command.

 npm install --save-dev chai

Then I ran my unit test class with the following imports.

import {assert} from 'chai';
import {expect} from 'chai';

It throws the below errors.

test\main\MessageBroker.spec.ts(3,22): error TS2307: Cannot find module 'chai'.
[05:38:45] [Typescript] TypeScript error: test\main\MessageBroker.spec.ts(3,22): error TS2307: Cannot find module 'chai'.
test\main\MessageBroker.spec.ts(4,22): error TS2307: Cannot find module 'chai'.
[05:38:45] [Typescript] TypeScript error: test\main\MessageBroker.spec.ts(4,22): error TS2307: Cannot find module 'chai'

What am I doing wrong here? I can see chai folder inside node_modules folder as well.

When I say var chai = require('chai'); it works! why doesn't import work?

I have not installed a typing for chai, that is I haven't referred chai from DefinitelyTyped but have installed it as a node module. Therefore I had to call it using a require statement in my typescript code.

 var chai = require('chai');

You are probably using something like Babel behind the scenes to transpile to ES5.

If that is the case it's actually executing require over Node, CommonJS style.

This way you may succeed if you just append the path with ./ just like we do in CommonJS.

Please give it a try, I hope this fix your issue:

import {assert} from './chai';
import {expect} from './chai';

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