zkwsk
zkwsk

Reputation: 2136

Using require within an NPM package

I've written a custom NPM package that will spin up a mocked Apollo GraphQL server for me with some custom settings.

In my /bin folder I have a file, server.js which is responsible for spinning up the server.

In package.json I've set up my command like this:

...
"bin": {
  "mock-server": "./src/server.js"
},
...

So when I run the command mock-server from the parent project it will execute the server.js file.

All good so far, but the problem is that once I start trying to require dependencies I run into this error:

$ use-env mock-server
/Users/dev/projects/share-vde-frontend/node_modules/.bin/mock-server: line 1: syntax error near unexpected token `('
/Users/dev/projects/share-vde-frontend/node_modules/.bin/mock-server: line 1: `const { ApolloServer  } = require("apollo-server");'
error Command failed with exit code 2.

My knowledge of writing npm modules is just based on what I've seen in packages I've been using in the past, so maybe I'm missing something key. Do I need some special measures when requiring imports? Or do I need to build and transpile the code? I'm using ES6 syntax, but I feel confident that anyone using this package will be on modern Node.js versions (the package is private and only to be used within our organisation).

Upvotes: 1

Views: 45

Answers (1)

zkwsk
zkwsk

Reputation: 2136

Based on the comment from @jonrsharpe above, I solved it by added shabang to the start of the server.js file:

#!/usr/bin/env node
const { ApolloServer } = require("apollo-server");
...

Upvotes: 0

Related Questions