4

I am struggling to load a .js module which is in the same folder as my .ts file. I have 4 file in the same folder:

index.ts

/// <reference path="./node.d.ts" />
/// <reference path="./foo.d.ts" />

import foo = require('./foo.js');

node.d.ts

Copied from https://github.com/borisyankov/DefinitelyTyped/blob/master/node/node.d.ts

foo.d.ts

declare module "foo" {
    export function hello(): void;
}

foo.js

module.exports = {
    hello: function() {
        console.log('hello');
    }
};

When I run tsc index.ts --module commonjs, I get the following error:

index.ts(4,22): error TS2307: Cannot find module './foo.js'.

2 Answers 2

4

Since node.js will resolve foo via relative path rather than looking for it in the node_modules directory like it would with a module you'd installed via npm, you need to drop declare module "foo" in foo.d.ts. Also, in index.ts, drop the .js extension when calling require.

foo.d.ts

export function hello(): void;

index.ts

/// <reference path="./node.d.ts" />
/// <reference path="./foo.d.ts" />

import foo = require('./foo');
Sign up to request clarification or add additional context in comments.

Comments

1

Try to use require without relative path

var foo = require('foo');

See related article for details.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.