Using require within an NPM package - node.js

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).

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");
...

Related

Cannot use import statement outside a module with #pusher/push-notifications-web nodejs - beams

I am trying to follow this tutorial using nodejs and express: https://pusher.com/docs/beams/reference/web/#npm-yarn
First I did: npm install #pusher/push-notifications-web before adding the code.
But when I add this code in the index.js file:
import * as PusherPushNotifications from "#pusher/push-notifications-web";
const beamsClient = new PusherPushNotifications.Client({
instanceId: "<YOUR_INSTANCE_ID_HERE>",
});
beamsClient.start().then(() => {
// Build something beatiful 🌈
});
I get this error:
SyntaxError: Cannot use import statement outside a module
It's also not very clear to me from the tutorial if the code has to be in the frontend or the backend. I tried both but got the same result.
How can I fix this problem?
The error is caused by the fact that you're trying to use ES module specific features in a regular CommonJS file (the default behavior in Node.js). However, what you're looking at is the Web SDK for Pusher which won't help you achieve your goals.
You need the server SDK for Node.js - https://pusher.com/docs/beams/reference/server-sdk-node/.
Verify that you have the latest version of Node.js installed and you have 2 ways of fixing that
Set "type" field with a value of "module" in package.json. This will ensure that all .js and .mjs files are interpreted as ES modules.
// package.json
{
"type": "module"
}
Use .mjs as file extension instead of .js.

Error: Identifier 'Reader' has already been declared while bundling fstream with rollup.js

I'm new with configuring stuff with Rollup, I'm trying to configure a node CLI app to be bundled in a single cli.bundle.js file that would be executable with a simple node cli.bundle.js without needing to npm install anything before.
On a side note, we already have succeed in doing so with zeit/pkg, but we would rather note have all the nodejs executable bundled inside, so we are trying work with rollup instead of pkg.
The problem we encounter is that when going through the different node_modules of the application, rollup.js crash with error:
[!] Error: Identifier 'Reader' has already been declared
../../common/js-common/node_modules/fstream/lib/file-reader.js (7:4)
5: var fs = require("graceful-fs")
6: , fstream = require("../fstream.js")
7: , Reader = fstream.Reader
^
8: , inherits = require("inherits")
9: , mkdir = require("mkdirp")
Error: Identifier 'Reader' has already been declared
at error (/home/.../src/external-data/external-data-etl/node_modules/rollup/dist/shared/node-entry.js:5400:30)
at Module.error (/home/.../src/external-data/external-data-etl/node_modules/rollup/dist/shared/node-entry.js:9820:16)
at tryParse (/home/.../src/external-data/external-data-etl/node_modules/rollup/dist/shared/node-entry.js:9713:23)
at Module.setSource (/home/.../src/external-data/external-data-etl/node_modules/rollup/dist/shared/node-entry.js:10076:33)
at Promise.resolve.catch.then.then.then (/home/.../src/external-data/external-data-etl/node_modules/rollup/dist/shared/node-entry.js:12362:20)
While looking for this error with rollup, it seems people were having it more at execution time than at bundle time, so I have no clue of what I can do. This duplicated identifier is in a 3rd party code I don't control :(
Here is my rollup.config.js
Edit: I tried with the new #rollup/plugins to see if there were a fix in them, but I have still the same issue.
import commonjs from '#rollup/plugin-commonjs';
import resolve from '#rollup/plugin-node-resolve';
import json from '#rollup/plugin-json';
export default {
input: 'dist/index.js',
output: {
format: 'cjs',
file: './cli.bundle.js'
},
plugins: [
commonjs(),
resolve(),
json() // asked and added when parsing 'got' package imported by 'download' package
]
};
And our building process is :
transpile from typescript (src) to js (dist) with tsc
bundle (dist) app into single runnable file
We would rather not include babel or typescript plugin to transpile, to stay independant, and certainly the (dist) app is enough (as it was enough for zeit/pkg).
Is there something we are doing wrong ?
The Problem is your dependency it is not coded in the right way you will need to correct the code error they did.

Module not found error when trying to use a module as a local module

I am trying to understand as how to make a local module. At the root of node application, I have a directory named lib. Inside the lib directory I have a .js file which looks like:
var Test = function() {
return {
say : function() {
console.log('Good morning!');
}
}
}();
module.exports = Test;
I have modified my package.json with an entry of the path to the local module:
"dependencies": {
"chat-service": "^0.13.1",
"greet-module": "file:lib/Test"
}
Now, if I try to run a test script like:
var greet = require('greet-module');
console.log(greet.say());
it throws an error saying:
Error: Cannot find module 'greet-module'
What mistake am I making here?
modules.export is incorrect. It should be module.exports with an s.
Also, make sure after you add the dependency to do an npm install. This will copy the file over to your node_modules and make it available to the require function.
See here for a good reference.
Update:
After going through some examples to figure this out I noticed, most projects have the structure I laid out below. You should probably format your local modules to be their own standalone packages. With their own folders and package.json files specifying their dependencies and name. Then you can include it with npm install -S lib/test.
It worked for me once I did it, and it'll be a good structure moving forward. Cheers.
See here for the code.

using systemjs on node.js (& Angular 2)

Say I have a foo.ts and app.ts as follows:
foo.ts:
export interface Foo {
id: number;
label: string;
};
app.ts:
import {Foo} from './foo'
var myfoo: Foo = { "id": 1, "label": "One" };
console.log(JSON.stringify(myfoo));
After compiling, executing 'node app.js' from the command line runs as expected if I use "module"="commonjs" in my tsconfig.json. Cutting to the chase, what I would like to do is is use my Foo interface client-side with Angular 2, and server-side with node. Inconveniently, the Angular 2 quickstart I am modeling on here wants "module"="system" in tsconfig.json. This configuration causes an error when trying to run 'node app.js':
System.register([], function(exports_1) {
^
ReferenceError: System is not defined`
I have tried following the instructions for using systemjs with node on github, but at this point I am just mashing keys and could use some help. How do I either (a) get my app.ts code running on the server-side using systemjs, or alternately, (b) get the Angular 2 quickstart running with commonjs?
I am going to wrap this up with an answer, even if the question hasn't been up-voted. The solution appears to be to use Gulp to compile the common typescript code (like interface Foo) differently for the client ("module"="system") and the server ("module"="commonjs"). If there is a way to compile the typescript code in the OP with "module"="system" I'd still like to know. But it appears to be kind of academic since everyone manages their project with Gulp or something similar anyway.

'Cannot find module' error using karma-browserify on Windows

I'm attempting to set up unit testing on an Angular/Browserify project using Karma, Karma-Jasmine, and Karma-Browserify. I'm on a Windows machine, for reference. karma-cli is on my global npm path, and karma, karma-jasmine, karma-browserify, and browserify are all local npm installs, using -D.
I'm trying to pull in a single spec file, which looks like:
var PhoneListCtrl = require('../../../public/js/app/controllers/phone-list');
describe('PhoneListCtrl', function() {
var scope,
ctrl;
beforeEach(function() {
scope = {};
ctrl = new PhoneListCtrl(scope);
});
it('should create "phones" model with 3 phones', function() {
expect(scope).not.toBe(undefined);
});
});
And I get the following error every time:
Uncaught Error: Cannot find module 'Cc/gGH'
I get this exact same error after cloning the following repos, installing karma and all plugins, and attempting to run their example test suites:
https://github.com/xdissent/karma-browserify
https://github.com/waye929/angular-browserify
What on earth am I doing wrong? The test spec module is found correctly, and karma seems to be finding all necessary plugins/preprocessors, but it appears that karma-browserify is tripping on the require statement in a spec every time, for reasons I cannot fathom.
I've uninstalled and reinstalled karma and all related plugins numerous times now, to no avail.
I managed to find a solution. The issue was caused by karma-browserify's own module name hashing function, which is incompatible with newer versions of browserify. There's a fork that deals with it by using browserify's hashing function:
https://github.com/voidlock/karma-browserify/commit/3afe3b7485f2e4723bba5ad1c5a730d560b8c234
There's a pull request pending but in the meantime you can use the fork by placing
"karma-browserify": "https://github.com/voidlock/karma-browserify/tarball/use-browserify-hash-function"
in your package.json (dev)dependencies section.

Resources