You structure a Node project with package.json, ES modules, npm dependencies, and scripts.
Open this lesson in KodokonA real project doesn't fit in a single file: you split it into modules, files that export what they offer and import what they need. You already know the import / export syntax from the JavaScript track; let's see how Node enables it. It all starts with package.json, your project's ID card: a file in JSON format that describes its name, its version, and its settings. To create it, move into an empty folder and run npm init -y (the -y option accepts all the default answers). Then add the line "type": "module": it tells Node that your .js files use ES modules.
{
"name": "my-project",
"version": "1.0.0",
"type": "module",
"scripts": {
"start": "node main.js",
"dev": "node --watch main.js"
}
}Let's create two files in this folder: math.js exports a function, main.js imports it. A detail specific to Node: importing a local file must begin with ./ and end with the .js extension. Both are required, unlike what some web tools tolerate.
// math.js
export function add(a, b) {
return a + b;
}
// main.js
import { add } from "./math.js";
console.log(add(2, 3));npm's great strength is its worldwide library of packages: code written by others, ready to use. The npm install command downloads a package into your project's node_modules folder and adds it to the dependencies section of package.json: the list of packages your project needs to work. A package-lock.json file, created automatically, records the exact versions installed, so everyone gets the same thing. Let's try with chalk, a package that colors the text shown in the terminal.
npm install chalkOne last pillar: npm scripts, command shortcuts declared in the scripts section of package.json. npm run dev runs the command saved under the name dev, however long the real command may be. Our dev script uses node --watch, an option that automatically restarts the program every time a file changes: very comfortable during development.
npm run start
npm run dev