已發布·持續改進
JavaScript 指南 · 4/6
本章目前僅提供英文版。
As a program grows you split it into files and pull in libraries written by others. JavaScript has two module systems: the standard ES modules (ESM) and CommonJS, which Node.js used for years before ESM existed. This chapter compares them and then covers npm, package.json, scripts and the basics of bundling.
ES modules are part of the language standard and work in both browsers and Node.js. You export from one file and import in another. A file can have many named exports but only one default export.
// math.js
export const PI = 3.14159;
export function circleArea(r) {
return PI * r * r;
}
export default function sum(...nums) {
return nums.reduce((a, b) => a + b, 0);
}// main.js
import sum, { circleArea, PI as pi } from "./math.js";
import * as math from "./math.js";
console.log(sum(1, 2, 3)); // 6
console.log(circleArea(2)); // 12.56636
console.log(pi === math.PI); // true
// dynamic import loads on demand and returns a Promise
const { readFile } = await import("node:fs/promises");A few things set ES modules apart:
import declarations let tools drop unused code (tree shaking).await is allowed.<script type="module" src="main.js">, and relative imports must include the .js extension.CommonJS uses require and module.exports. You will still meet it in plenty of packages and older projects.
// greet.cjs
function greet(name) {
return `Hello, ${name}`;
}
module.exports = { greet };
// app.cjs
const { greet } = require("./greet.cjs");
const path = require("node:path");
console.log(greet("Mina"));
console.log(path.join("logs", "today.txt"));Node.js decides how to treat a file with these rules:
| File | Treated as |
|---|---|
.mjs | ES module |
.cjs | CommonJS |
.js with "type": "module" in the nearest package.json | ES module |
.js with no "type" or "commonjs" | CommonJS |
For new projects, set "type": "module" and write ESM. ES modules can import CommonJS packages; going the other way, a dynamic import() is the most reliable route. Prefix built-ins with node: (, ) so they never get confused with npm packages.
node:fsnode:pathnpm downloads packages into node_modules and records each one, with an allowed version range, in package.json.
npm install zod # runtime dependency
npm install -D vitest # development-only dependency
npm uninstall zod
npm outdated # list packages with newer releases
npm ci # clean install straight from the lock file (for CI){
"name": "todo-api",
"version": "0.1.0",
"type": "module",
"scripts": {
"start": "node src/server.js",
"dev": "node --watch src/server.js",
"test": "node --test"
},
"dependencies": {
"zod": "^3.23.0"
},
"devDependencies": {
"vitest": "^2.0.0"
}
}A caret (^) allows newer minor and patch releases within the same major version; a tilde (~) allows only patch releases. The exact versions actually installed land in package-lock.json, so committing it keeps teammates and servers in sync.
Anything under scripts runs with npm run <name>. start and test also have shortcuts. Inside a script, tools installed in node_modules/.bin are available without a path.
npm run dev
npm test
npm start
# run a tool once without adding it to the project
npx prettier --write srcBrowser apps quickly grow to hundreds of files plus npm dependencies. A bundler follows the imports, combines everything into one or a few files, and handles minification, tree shaking and code splitting along the way.
| Tool | Known for |
|---|---|
| Vite | Fast dev server and minimal config; a common default for new apps |
| esbuild | Extremely fast bundling and transforms |
| Rollup | Clean output for publishing libraries |
| webpack | Long track record and a huge plugin ecosystem |
# scaffold a new project with Vite
npm create vite@latest my-web
# bundle and minify a single entry with esbuild
npx esbuild src/main.js --bundle --minify --outfile=dist/app.jsServer code that only runs on Node.js usually works fine unbundled. Bundlers matter most for code you ship to browsers.
"type": "module" in package.json.require, module.exports) in older code.dependencies from devDependencies and commit package-lock.json.scripts and run them with npm run.
0 則留言
登入 · 登入後即可留言。
來留下第一則留言吧。