zkat / npx

execute npm package binaries (moved)
https://github.com/npm/npx
Other
2.63k stars 105 forks source link

require a package provided by npx #177

Open fparga opened 6 years ago

fparga commented 6 years ago

I'm trying to do something probably a bit weird, and some might consider this an abuse of what npx is made for. Basically I want to run jest in a non-js project and take advantage of the snapshot functionality.

To run jest in a folder, I can just do npx jest and assuming I have a jest config file in this folder it will work.

But to run my tests I also need shelljs, hence I have this require in my test:

const shelljs = require(shelljs);

Of course, I don't have shelljs installed, neither locally nor globally and ideally I don't want to.

So I have made it work by calling:

npx -p shelljs -p jest -c "jest"

And having the require like this in my script:

const _ = process.env._;
const dir = path.join(path.dirname(_), '../lib/node_modules');

const shelljs = require(path.join(dir, "shelljs"));

But is there a proper way of doing this?

zkat commented 6 years ago

Have you considered using https://github.com/shelljs/shx instead of shelljs? npx isn't really meant to make npm packages available. You'll have to actually add a package.json to your project and make it a dependency to make it usable node-side.

kellyselden commented 6 years ago

For projects that don't have a bin file, but I wish they did, it would be nice to do something like

npx tmp --script "console.log(require('tmp').dirSync());" > ...

I understand this may be outside the scope of npx, but I thought I would provide more context.

johnknoop commented 5 years ago

I'm also a bit confused as to what can be done using npx -p.

For example, I was hoping it would be possible to run:

npx -p myNpmDependency ./test.js

and then simply require myNpmDependency inside test.js. But I discovered that it will not find that module, even though it seems npx is installing it before executing test.js.

Can @zkat confirm that this isn't really possible using npx?

alahijani commented 5 years ago

For a second I though I had a flash of genius,

npx -p right-pad -- node -e 'require("right-pad")'

But not really.