Do all npm packages need an export? - node.js

I am new to nodejs packages and what I understood was that to share code you had to do a module.export (in addition to adding a package.json)
For example bootstrap-select does not have an export function but is available on npm.
So my question is do all modules require an export and also can I do a require('bootstrap-select') in my code?

no, all npm modules do not require an export. npm is now being used more generally for not only javascript packages intended for use under node.js but front end code for browsers, CSS libraries, etc. At the very least, an npm package could just deliver a payload of files not even including any javascript, such as some images, some CSS, some HTML, etc.
So you can only do require('some-module') if that package has either an index.js file or has set the main property in it's package.json file properly.
However if you are authoring a javascript module for node.js, then yes you'll need to export something in order for your module to load properly.

No, npm modules do not require doing something with module.exports. If you do not touch that object, requireing your module will return an empty object (since that is the default for module.exports. However, this can be useful if your module is only intended to be required for side effects, rather than a return value.
For example, the module you linked to modifies global state by attaching a jQuery event handler.

As per i know ,
1.All npm modules are not required to build an app.
2.If we use var bootStrap = require('bootstrap-select'); using bootStrap variable you can access bootStrap module.
so we can pass that object in anywhere of your code
3.To install a dependency modules,
In package.json give dependency block as like this
"dependencies": {
"express": "2.3.12",
"jade": "latest",
"redis": "0.6.0"
}
you can change and edit your packages. then enter a command npm install in command prompt it will install only dependency modules.
If i made any mistakes please correct me Thanks.

Related

How to include dependencies in J2V8

How to include dependencies in J2V8? I would like to use certain dependencies in the javascript file for instance the crypto package.
var crypto = require('crypto');
function foo(){ return crypto.createHash('md5').update('Apple').digest("hex");}
However, I got the following error saying require keyword is undefined.
undefined:1: ReferenceError: require is not defined
var crypto = require('crypto');
^
ReferenceError: require is not defined at <anonymous>:1:14
com.eclipsesource.v8.V8ScriptExecutionException
at com.eclipsesource.v8.V8._executeVoidScript(Native Method)
Can anyone tell me how to import an package into J2V8?
Unless you're working with Node, require is not a feature. Usually, you want to use a bundler like webpack to pack your structured source code into one large file so that it can be understood by browsers. This way you can use require and npm packages for your frontend code, which makes development easier, and a bundler turns it with every build (or live update) into a different format, that's hard to read for humans, but is valid Javascript.
I have had success using node modules in J2v8, please check out this blog :http://eclipsesource.com/blogs/2016/07/20/running-node-js-on-the-jvm/
NodeJs nodeJS = NodeJs.createNodeJs();
After registering callbacks
nodeJs.exec(File thescripttoexecute)
Make sure you have the proper path to the node modules in the require() command.
You may have to make a nodejs package that takes dependencies and exports what you need. Then, You have to execute npm install manually.
or You can just npm install what-you-need.
Create Node JS Runtime, and use require with your your-package-dir/index.js or exact location of module that you need. like this:
V8Object module = nvm.require(file);
Now you can call the function likes:
module.executeJSFunction("test");
To deliver entire dependencies you have to bundlize module directory your self.
What if you have to support cross-platform, refer https://www.npmjs.com/package/node-pre-gyp also.

How to fetch modules from npm as standalone AMD/CommonJS modules

So, I'm not using Node or WebPack serverside, but would still like to use modules from npm every now and then. My clientside uses requirejs, so I would need the modules in either AMD (preferred) or CommonJS.
What I want to archieve is a script that takes the module name + "external dependencies" as arguments and creates a module that contains all the other deps.
E.g.
sh npmtoamd.sh draft-js react react-dom
It creates an ES5 AMD module that contains draft-js and all of it's dependencies excluding react and react-dom. If it's not possible to eg. include css files and other non-js content in the module, providing them in eg. draft-js.css is tolerable.
While I don't use Node or Webpack serverside, we can use npm and webpack in the said script.
Fetching the module from npm is the trivial part, but I'm pretty lost in how to do the webpack parts. I know for a fact that it's possible though, as I managed to do it earlier with help, just don't have it down anywhere and no idea how it went.
I think as elmigranto commented, Browserify is what you're looking for. Unlike its name implies, it can be used in both the browser environment and the node environment. In a nutshell, it does this:
Browserify starts at the entry point files that you give it and searches for any require() calls it finds using static analysis of the source code's abstract syntax tree.
For every require() call with a string in it, browserify resolves those module strings to file paths and then searches those file paths for require() calls recursively until the entire dependency graph is visited.
Each file is concatenated into a single javascript file with a minimal require() definition that maps the statically-resolved names to internal IDs.
This means that the bundle you generate is completely self-contained and has everything your application needs to work with a pretty negligible overhead.
If you check out some of the demos you can see that all the dependencies (and their co-dependencies) are bundled into one file.
A simple example:
browserify main.js -o bundle.js
In regards to using AMD as well Browserify supports it by using deamdify.
Using AMD modules:
browserify -t deamdify main.js -o bundle.js
I ended up doing the npm fetch thingy in java instead of a batch script and finally got it working. Didn't get browserify to work however.
Heres what I do:
creating the following webpack.config.js
module.exports = {
entry: './main.js',
output: {
filename: 'bundle.js',
library:"<modulename>",
libraryTarget:"amd"
},
externals: {
react: "React",
"react-dom": "ReactDOM",
immutable:"Immutable",
moment:"Moment"
}
};
npm install <modulename>
Creating the following main.js
define('FOOBAR', ['<modulename>'], function(Foo) {
return Foo;
});
Running webpack main.js

What is the correct way of adding a dependency to react in your package.json for a react component

I have made a few simple reusable react components and wanted to know the correct way to include a dependency to react in my package.json for publishing with npm.
I am currently doing this:
Assuming my component will use the most recent version of react and I have tested and it works with that version. e.g. 0.13.3
"peerDependencies": {
"react": "^0.13.3"
},
For reusable components:
Put a react dependency in both peerDependencies and devDependencies.
Never put a react dependency in dependencies.
peerDependencies specifies which version(s) of React your reusable component supports/requires. When using npm 2 this also adds React to the list of modules to be installed, but this is no longer the case with npm 3.
devDependencies ensures React will be installed when you run npm install while developing your component, or when running tests on Travis or similar.
Putting react in dependencies will cause multiple versions of React to be installed if somebody uses your component but has a different version of React in their own package.json - having multiple versions of React not only bloats the build, but also causes errors when different versions try to interact.
The selected answer is definitely the prescribed approach here however I've started favoring the use of inversion of control as opposed to relying on npm peer dependencies for my libraries dependencies and its served me well.
Libraries are easier if you build them functional. It seems to be easier to maintain libraries that export a single function which takes in an object with all of their heavy dependencies and export an object containing each of your libraries typical exports.
Library 'injected'
lib/index.js
export default ({ React }) => {
const InjectedComponent = props => (
<p style={{color: props.color}}>This component has no React npm dependencies.</p>
)
/** other stuff */
return { InjectedComponent }
}
Consuming App
app.js
import React from 'react'
import { render } from 'react-dom'
/** Import the default export factory from our library */
import createInjectedComponent from 'injected'
/** Call the factory, passing its dependencies (guaranteed to match what we're bundling) and get back our component */
const { InjectedComponent } = createInjectedComponent({ React })
render(<InjectedComponent color="blue" />, document.getElementById('root'))
If your component only works with a given version of react or some other dependency, you can write some assertions around the version for the React parameter that is passed in. Overall, building libraries in this fashion should be less prone to new build issues appearing anytime version of React is published and will more importantly ensure that you are not causing your library consumers to bundle multiple versions of React and other heavy libraries. This pattern works well with npm link (I generally have 16+ libraries running from npm link simultaneous and experienced issues when I didn't use this pattern).
In your main app I would recommend always splitting out react, react dom and any react lib components you use into a vendor bundle (webpack) and mark it as external in your main bundle so that you do not unintentionally bundle two versions.
You can have react in either peerDependencies or in dependencies. The difference being that with a peerDependencies, react is only installed once for the package using your package. If you put it in dependencies, react will be installed twice, one time for the package using your package, and once time for your package.
React itself seems to favor peerDependencies for some reason. You obviously don't want two separate versions of react in your Javascript bundle (which happens by default if you use dependencies), but that is easy to fix with npm dedupe.
So there's no correct way to do it, both peerDependencies and dependencies work. Using dependencies is more in line with the node/NPM way, but using peerDependencies is friendlier to users of your package that doesn't know about npm dedupe and why it's needed.

Using localForage and angular-localForage with Browserify causing errors with require statements

I am attempting to install localForage into a node.js application (with Angular) and Browserify.
Here is a link to the localForage documentation
It appears that using localForage and angular-localForage causes a problem with browserify based around the use of 'require'
If I require the localforage.js file in the src file I get the following error:
Warning: module "promise" not found from "/Users/mgayhart/Sites/epson- receipts/bower_components/localforage/src/localforage.js" Use --force to continue.
If I require the localforage.js file in the dist file, I get the following error:
Warning: module "./drivers/indexeddb" not found from "/Users/mgayhart/Sites/epson- receipts/bower_components/localforage/dist/localforage.js" Use --force to continue.
Anyone know of a workaround to be able to move forward with these libraries?
There is an issue on github with this problem: https://github.com/ocombe/angular-localForage/issues/26
I'll be working on it soon, you can subscribe to the github notifs on this issue to know when it's fixed !
For me installing it through bower and using it with browserify-shim worked. So in package.json:
"browser": {
"localforage":"./src/lib/vendor/localforage/dist/localforage.min.js"
},
"browserify-shim": {
"localforage":"localforage"
}
And to expose it as an angular-service (if you don't want to use angular-localforage):
app.factory "localforage",-> require 'localforage'
I've just been having this issue myself tonight, but I think I found a fix.
Instead of trying to get the bower modules to work with browserify, why not just use npm like its made for?
npm install localforage
and then when you use require you don't have to give it the path
but it still didn't work for me until I copied the folder:
localforage/src/drivers TO localforage/dist/drivers
Then it found all the dependencies and worked like a champ!
Alternatively if you must use bower you could try to use the debowerify tranform w/ gulp:
https://github.com/eugeneware/debowerify

How to NodeJS require inside TypeScript file?

How do I load a regular NodeJS module (from node_modules) from within a TypeScript class?
When I try to compile .ts file that contains:
var sampleModule = require('modulename');
Compiler prompts that I can't use require in this scope. (That line is at the beginning of the file).
Typescript will always complain when it is unable to find a symbol. The compiler comes together with a set of default definitions for window, document and such specified in a file called lib.d.ts. If I do a grep for require in this file I can find no definition of a function require. Hence, we have to tell the compiler ourselves that this function will exist at runtime using the declare syntax:
declare function require(name:string);
var sampleModule = require('modulename');
On my system, this compiles just fine.
The correct syntax is:
import sampleModule = require('modulename');
or
import * as sampleModule from 'modulename';
Then compile your TypeScript with --module commonjs.
If the package doesn't come with an index.d.ts file and its package.json doesn't have a "typings" property, tsc will bark that it doesn't know what 'modulename' refers to. For this purpose you need to find a .d.ts file for it on http://definitelytyped.org/, or write one yourself.
If you are writing code for Node.js you will also want the node.d.ts file from http://definitelytyped.org/.
The best solution is to get a copy of Node's type definitions. This will solve all kinds of dependency issues, not only require(). This was previously done using packages like typings, but as Mike Chamberlain mentioned, Typings are deprecated. The modern way is doing it like this:
npm install --save-dev #types/node
Not only will it fix the compiler error, it will also add the definitions of the Node API to your IDE.
Use typings to access node functions from TypeScript:
typings install env~node --global
If you don't have typings 😲 install it:
npm install typings --global
when loading typescript module I use module name with extension i.e.
".ts"
const sampleModule = require('modulename.ts');
FYI, in my case "node" command (v14.17.1) using ".ts" files directly without generating "*.js" files.

Resources