Node.js Notes
Requiring and Including Modules
https://medium.freecodecamp.org/requiring-modules-in-node-js-everything-you-need-to-know-e7fbd119be8
Write some code like this and save it in a file called bar.js
module.exports = {
foo: function() {}
};
Then, require it and use it like this:
const bar = require('./foo.js');
bar.foo();
Notice that we use the ./
. If you don't specify the path to a file, then node will search directories listed inside the module.paths
variable.
Node Package Manager (NPM)
Use npm init
to create a new project
Adding dependencies
Use npm install <foo>
to install a library in local directory as a production dependency
Use npm -D install <foo>
or npm install --save-dev <foo>
to save as a dev dependency
Running Scripts
You can run the special lifecycle scripts like test
, start
, restart
, stop
by simply typing npm start
, for example.
The behavior of each of these script commands is defined in package.json
under the scripts
section.
You can also add custom scripts, like for example you could define a repl
script. But in order to run, use npm run repl
.
npx
npx
is a command line tool that comes with node to run command line tools like webpack
. For example, you could either run npx webpack
, or set up scripts
with a build
key so that you can run `npm run build to run
webpack`.
webpack
When writing javascript for the front end, you often end up with several js files along with images, and css that you want to present in an html page. It can get tedious and cumbersome to create html files that include all the css/js/img files. webpack
is a tool that helps with this. You tell webpack
where all your js/css/js/html files are, and it combines them all to produce a final version to use.