ilearnio / module-alias

Register aliases of directories and custom module paths in Node
MIT License
1.76k stars 69 forks source link

addPath in '-r script': require.main.paths undefined #40

Closed gkraser closed 6 years ago

gkraser commented 6 years ago

Error in addPath, if script in -r option.

Script (test.js):

require("module-alias").addPath('.')

run:

node -r ./test.js

error:

    addPathHelper(path, require.main.paths)
                                     ^

TypeError: Cannot read property 'paths' of undefined
    at Function.addPath (node_modules\module-alias\index.js:85:38)

run as simple script - no error:

node ./test.js
ilearnio commented 6 years ago

You're doing it wrong. You forgot to call the initializing function. This is how it should be

const moduleAlias = require('module-alias')('.') // <-- path to app's root
moduleAlias.addPath('~', __dirname)

or use with /register which will do the initialization for you, useful in es modules

import moduleAlias from 'module-alias/register'
moduleAlias.addPath('~', __dirname)
shlomiassaf commented 5 years ago

@ilearnio I think your answer might be wrong.

When addPath() is called in a preloaded startup module (-r, --require) it is called before the main module has loaded and so require.main is not populated yet, which is why the error happen.

This error will happen also when setting _moduleAliases in the package.json and doing

node -r 'module-alias/register' my-main-file.js

It is also misleading because init() returns undefined which means that require('module-alias')('.') returns undefined as well as import moduleAlias from 'module-alias/register'

The solution might be to register an alias (not a path) using a handler...

ivancuric commented 5 years ago

Same issue here. I'm using the following file to use babel-typescript:

// babel-register.js
require('@babel/register')({ extensions: ['.js', '.jsx', '.ts', '.tsx'] });

Which is then used like this in package.json:

"build-diagnostic-tools": "node -r ./babel-register.js ./_scripts/build-diagnostic-tools.ts",

This is the go-to usage when you want to use typescript with babel. Would be great if I could just put this in the babel-register.js instead of in every file that it's being used in.

Eg something like:

require("module-alias");
require('@babel/register')({ extensions: ['.js', '.jsx', '.ts', '.tsx'] });