Neena Vivek
Neena Vivek

Reputation: 717

How can I use a npm modules directly in my projects?

I have never used npm before so I may not be asking the question how it should be asked but I could not find this information anywhere. Let's say I am interested in using this module. The author asks me to install the module which I do by typing the following in command line.

npm install --save critical 

I am lost after that. The author writes a bunch of lines but I have no idea where to put them.

var critical = require('critical');

and

critical.generate({
  inline: true,
  base: 'test/',
  src: 'index.html',
  dest: 'index-critical.html',
  width: 1300,
  height: 900
});

Where do I put this code and how do I run it. I tried creating a file called criticaldemo.js and put all this code there but running it through command line did nothing. TO run it through command line I used the following command:

$ criticalfile.js

Can anyone please help me understand how to use npm modules?

Upvotes: 2

Views: 1042

Answers (1)

nem035
nem035

Reputation: 35491

Let's assume your project directory structure looks like:

project
  criticaldemo.js

You should navigate to project and run

npm init

This will create package.json inside your project. You can just press enter for each question to use the default values.

If you prefer, you can also manually create package.json based on the requirements.

Here's how it should look, as a bare minimum (must have at least a name and version):

{
  "name": "my-cool-project",
  "version": "1.0.0"
}

Either way, at this point your directory should look like:

project
  criticaldemo.js
  package.json

Next, you run:

npm install --save critical 

This will create a directory node_modules with your package inside of it:

Directory structure:

project
  criticaldemo.js
  package.json
  node_modules

Now inside your criticaldemo.js, you put the code as the package author said:

var critical = require('critical'); // this loads the package from node_modules/critical

critical.generate({
  inline: true,
  base: 'test/',
  src: 'index.html',
  dest: 'index-critical.html',
  width: 1300,
  height: 900
});

Finally you run the program using node:

node criticaldemo.js

Upvotes: 4

Related Questions