Typescript: require.main.require imports do not work

Created on 12 Oct 2017  路  6Comments  路  Source: microsoft/TypeScript




TypeScript Version: 2.6.0-dev.201xxxxx

From: https://github.com/Microsoft/vscode/issues/35489#issuecomment-335689358

Code

const myModule = require.main.require('./file.js')

Run go to definition on myModule

Expected behavior:
Goes to defintion of myModule

Actual behavior:
Nothing happens. Looks like we don't understand require.main.require style imports

Awaiting More Feedback JavaScript Suggestion VS Code Tracked

Most helpful comment

I realise this may be a big feature for you, but consider that it is a widely-used alternative to requiring crazy paths like ../../../../../../foo/bar/baz.js. So many people are using this approach now.

I hope you can find a way to get this to work.

All 6 comments

the analysis of module imports in .js files is limited to the known require call. require.main is not a pattern the compiler looks for. it is also early in the compilation process to know that require.main.require is an alias to require.

This is currently a design limitation.

@mhegazy Worse yet, require.main.require isn't strictly an alias to require - it's a require relative to the package entrypoint... Something we don't currently define.

I realise this may be a big feature for you, but consider that it is a widely-used alternative to requiring crazy paths like ../../../../../../foo/bar/baz.js. So many people are using this approach now.

I hope you can find a way to get this to work.

I am looking forward to this feature too. Intellisense is not able to understand require.main.require as alias for require. But this method helps a lot for readability of code when you have files in deeper folder structures.

I am not sure if this is the same issue, but what I want is to have the types in the current package, but I want the root package to include 'mongodb'.

When I do the following:

import mongo = require.main.require('mongodb')

I get the following error:

Cannot find namespace 'require'.

However, the following works, but isn't what I want:

import mongo = require('mongodb')

Apparently require.main.require is referencing the Main package of your program, i. e., the entry script. When running with vscode code & debug tool, this package appears to be something else rather than my node js main process, because it fails to find the module require inside the main.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

weswigham picture weswigham  路  3Comments

siddjain picture siddjain  路  3Comments

wmaurer picture wmaurer  路  3Comments

dlaberge picture dlaberge  路  3Comments

Zlatkovsky picture Zlatkovsky  路  3Comments