JavaScript Essentials for React Native - #6 Node.js, npm, package.json
Node.js basics required for React Native projects - npm, import/export
Table of contents
Node.js basics
Node.js is a runtime to run JavaScript code outside your browser.
You can not only run JavaScript code but create JavaScript projects, use open source JavaScript modules in your project, write both client and server side code in the same language i.e. JavaScript
Download Node.Js from their official website and run JavaScript code directly on your machine.
Create a new Node.js project on your machine using command
npm init -y
by running it inside a new project folder.This creates a
package.json
file which is basically your project config fileIt has project
name
Project current
version
to maintain versioningmain
,scripts
sectionauthor
,license
etcAnd a
dependencies
which stores the list of packages downloaded fromnpm
server.
You can also add other tools like - code linter, code bundler, code formatters, version control system etc and their respective files would be added to your project.
And once you install packages from npm, one more folder named
node_modules
is generated. And all the dependency files are downloaded here. This is the folder that is bulky and will eat up a lot of your system space if you have a lot of node projects on your system.Don't push this folder to
Github
. Add this to.gitignore
You could also delete this folder in your older projects, just to free system space. And later just run
npm install
in that respective project to re-download it'snode_modules
files.
require vs import, export
When working with modular JavaScript code, two prevalent approaches for including and exposing functionality across files are require()
and import/export
.
1. CommonJS with require():
Syntax:
// To import a module
const myModule = require('./myModule');
// To export a module
module.exports = myModule;
Usage:
CommonJS, primarily used in Node.js environments.
Synchronous, loading modules at runtime.
Dynamic dependencies possible.
Example:
// math.js
const add = (a, b) => a + b;
module.exports = add;
// main.js
const addFunction = require('./math');
console.log(addFunction(2, 3)); // Outputs: 5
2. ES6 Modules with import/export: ( This approach in React Native Projects )
Syntax:
// To import a module
import myModule from './myModule';
// To export a module
export default myModule;
Usage:
ES6 Modules, widely used in modern JavaScript (frontend, bundlers like Webpack).
Asynchronous, allowing for static analysis and tree-shaking.
Static dependencies enforced.
Example:
// math.js
const add = (a, b) => a + b;
export default add;
// main.js
import addFunction from './math';
console.log(addFunction(2, 3)); // Outputs: 5
Summary
In this blog, we talked about Node.js, npm, package.json and the use of require, import, export.
Thanks for Reading!