Modules, npm and Build Tooling
ES modules, package.json and npm scripts, dependencies and lockfiles, Vite, and linting and formatting with ESLint and Prettier.
A Project Grows Beyond One Script
A few lines can live in one script, but a real interface soon has separate concerns: reading data, validating form input, rendering a view, and making network requests. Keeping all of that in one file makes ownership unclear and makes changes risky. Modules let a file expose a small public interface and keep its implementation details local.
Modern JavaScript modules use import and export. Each module has its own scope, so a top-level variable in one file does not automatically become a global in another. This isolation makes modules easier to test and reuse.
Browsers support native modules through <script type="module">. Build tools such as Vite add a convenient development server and prepare assets for production. We will first learn the module syntax, then see where tooling fits.
Choose Named or Default Exports Intentionally
A named export gives an item an explicit exported name. Importers use braces and the same name (or an explicit alias). A module can expose several named helpers. A default export represents the main value from a module and can be imported under a chosen local name. Prefer a consistent style in each project.
export function formatRupees(amount) {
return new Intl.NumberFormat('en-IN', {
style: 'currency',
currency: 'INR',
}).format(amount)
}
export const DEFAULT_CATEGORY = 'Other'import { DEFAULT_CATEGORY, formatRupees } from './money.js'
export function expenseLabel(expense) {
const category = expense.category || DEFAULT_CATEGORY
return expense.description + ' · ' + category + ' · ' + formatRupees(expense.amount)
}Relative imports such as ./money.js refer to files near the current module. The exact extension and resolution rules depend on the environment and toolchain. Browser-native modules typically use explicit paths; bundlers can provide additional resolution behaviour based on configuration.
import { expenseLabel } from './expense-view.js'
const expense = { description: 'Bus fare', category: 'Travel', amount: 35 }
console.log(expenseLabel(expense))Load the Entry Point as a Module
A browser module is loaded with a module script. Modules are deferred automatically until HTML parsing is complete, and they use strict mode. The script below starts a small page from its entry file. Native module loading works well for simple demos, while a development server is needed to provide a smooth local workflow and production packaging.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Expense tracker</title>
</head>
<body>
<main id="app"></main>
<script type="module" src="/src/main.js"></script>
</body>
</html>Browser security restrictions can prevent modules from loading from some local file URLs. Serve the project over a local development server instead. In a Vite project, the HTML entry and imported source files are served as part of the application workflow.
- Choose one entry module, often named main.js or src/main.js.
- Import the modules it needs using clear relative paths.
- Export only the functions or values other files need.
- Keep browser-only operations near the UI layer and reusable logic independent where practical.
A clean entry point is not a requirement to have only one file; it is a place where application startup is visible. Keep initialization predictable and avoid side effects that start merely because a helper module was imported.
Use npm to Describe and Install Project Dependencies
npm is a package manager distributed with Node.js. A package is reusable project code with metadata. Thepackage.json file describes the project, scripts, and dependency ranges. A lockfile records a resolved dependency tree so installs can be more repeatable. Commit the lockfile for an application and use the package manager chosen by the team consistently.
npm init -y
npm install --save-dev viteThe first command creates a starter manifest; the second adds Vite as a development dependency. A development dependency is needed to work on and build the project, while runtime dependencies are packaged or required by the application itself. Review dependencies before adding them: every package is code your project chooses to trust.
{
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"devDependencies": {
"vite": "the range written by npm install"
}
}Treat the manifest as JSON: keys and string values use double quotes, and comments are not allowed. The actual dependency range should be generated by npm for the chosen installation, not copied from an unrelated tutorial. The lockfile captures the exact tree used by an install. Do not edit that generated file by hand.
| File or folder | Purpose | Team practice |
|---|---|---|
| package.json | Project metadata, scripts and declared dependencies | Review intentional manifest changes |
| package-lock.json | Resolved npm dependency tree | Commit it for a reproducible application install |
| node_modules/ | Installed package contents | Do not commit; recreate from the manifest and lockfile |
| src/ | Application source modules | Organize by feature or clear responsibility |
Create a Local Development Loop
Vite serves source modules during development and builds optimized assets for production. Its starter command opens an interactive prompt; choose a vanilla JavaScript template when following this lesson. The exact prompt may change, so follow the currently displayed choices instead of relying on an outdated numbered selection.
npm create vite@latest my-expense-app
cd my-expense-app
npm install
npm run devThe development command prints a local URL. Open that URL in a browser and keep the terminal running while you work. When files change, Vite updates the development page. The build script creates production assets, and the preview script can serve the built output locally for a final check. Neither command replaces testing in the actual hosting environment.
npm run build
npm run previewScripts are project commands, so they make the team's workflow discoverable. A new teammate can inspectpackage.json rather than guessing how to start or build the application. Keep scripts focused and document any extra setup that is not obvious.
Know What a Build Tool Does—and Does Not Do
A bundler follows imports, processes supported assets, and emits files that can be served to a browser. It may transform newer syntax for configured targets, but it does not automatically make every browser API available in every environment. Be clear about which runtime features your application uses and which transformations your project's configuration provides.
Vite's fast development experience is not a substitute for checking the production build. Development and production have different serving and optimization behaviour. Build regularly, test the output, and configure the hosting platform to serve the generated assets and route requests appropriately.
- Install the project dependencies from the manifest and lockfile.
- Start the development server and verify the feature in a browser.
- Run the project checks, such as tests and linting, when they are configured.
- Create a production build and inspect the output for missing assets or configuration.
- Deploy through a reviewed pipeline rather than uploading local node_modules.
Linters report patterns that are likely to be errors or inconsistent with a project's rules. Formatters make style consistent. They are separate tools with different jobs. Add them when a project needs them, follow the shared configuration, and avoid spending time debating formatting that can be automated.
Keep Package Boundaries and Secrets Clear
Every package adds code, updates, and potential risk. Before adding one, check whether the platform already provides the capability, whether the package is maintained, and whether its API fits the need. Pinning and updating policies should follow the team's release process rather than an arbitrary copy-paste convention.
Front-end source and built assets are visible to users. Environment values embedded in browser output are not secrets. Do not put database passwords, private API keys, or signing credentials in client-side environment variables. Secrets belong in a trusted server or deployment secret store, with the smallest required access.
Keep imports explicit and avoid a single giant utility module that exports everything. A module should have a focused responsibility, dependencies should generally flow in one direction, and application entry points should be easy to locate. These conventions matter more as multiple contributors work in parallel.
Common Mistakes
Using import syntax without a module environment
Why: The browser script was not loaded as a module or the project toolchain is not configured for modules.
Fix: Use type="module" in a native browser entry or follow the Vite entry and scripts.
Forgetting that imports need valid paths
Why: A typo or mismatched file extension breaks module resolution.
Fix: Check the relative path and follow the runtime or bundler resolution rules.
Committing node_modules
Why: It contains generated installed packages and can be large and platform-specific.
Fix: Use the manifest and lockfile to recreate dependencies; keep node_modules ignored.
Putting a secret in front-end configuration
Why: Bundled browser code and requests can be inspected by users.
Fix: Keep private credentials on a trusted server and expose only a safe application endpoint.
Split the Expense Tracker into Modules
Practice
Create a small, repeatable JavaScript project
- Create a Vite vanilla JavaScript project and inspect its generated manifest and source entry.
- Move rupee formatting into a module that exports a named formatRupees function.
- Create a second module that imports the formatter and renders one sample expense.
- Add or review dev, build, and preview scripts; run the production build and inspect the result.
- Explain why the lockfile is committed while node_modules is not.
- Identify a value that would be unsafe to place in browser-visible configuration and describe a server-side alternative.
Hint: Start with a small dependency graph: an entry module imports feature code, which imports a focused formatter.
🎯 Key Takeaways
- ✓ES modules use import and export, create file-local scope, and make dependencies explicit.
- ✓Choose named exports for clearly named APIs and use a consistent default-export convention where appropriate.
- ✓package.json declares project scripts and dependency ranges; the lockfile records a resolved dependency tree.
- ✓Use npm scripts to make development and build workflows discoverable.
- ✓Vite provides a development server and production build, but development success does not replace build checks.
- ✓Do not commit node_modules or put private secrets in browser-visible code.
Next
What comes next
Run JavaScript outside the browser: the Node.js runtime, CommonJS and ES modules, the fs and path modules, environment variables and a small CLI.
Lesson 11 · Node.js Fundamentals — Runtime, File System and Modules →HELP US IMPROVE
How was this lesson?
Your note is shared with the Chaduvuko team for review. Please don’t include personal or sensitive information.
Spotted a mistake or something unclear? Suggest a fix on GitHub or email us. Select the text first and it is quoted for you.
Discussion
0Have a better approach? Found something outdated? Share it — your knowledge helps everyone learning here.
