Modules, npm and Build Tooling

ES modules, package.json and npm scripts, dependencies and lockfiles, Vite, and linting and formatting with ESLint and Prettier.

Est. 30 min Updated Suggest a fix
// Part 01 — Why structure matters

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.

🎯 Pro Tip
Split files by responsibility, not by arbitrary line count. A tiny application does not need dozens of modules; a growing feature benefits when parsing, state, and rendering have clear boundaries.

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.

// Part 02 — Exports

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.

money.js
javascript
export function formatRupees(amount) {
  return new Intl.NumberFormat('en-IN', {
    style: 'currency',
    currency: 'INR',
  }).format(amount)
}

export const DEFAULT_CATEGORY = 'Other'
expense-view.js
javascript
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.

main.js
javascript
import { expenseLabel } from './expense-view.js'

const expense = { description: 'Bus fare', category: 'Travel', amount: 35 }
console.log(expenseLabel(expense))
💡 Note
Avoid circular dependencies: if module A imports B while B imports A, initialization order becomes harder to reason about. Move shared values into a small third module or change the responsibilities when a cycle appears.
// Part 03 — Browser modules

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.

html
<!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.

  1. Choose one entry module, often named main.js or src/main.js.
  2. Import the modules it needs using clear relative paths.
  3. Export only the functions or values other files need.
  4. 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.

// Part 04 — npm and packages

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.

bash
npm init -y
npm install --save-dev vite

The 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.

package.json (scripts excerpt)
javascript
{
  "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.

The files around a typical JavaScript project
File or folderPurposeTeam practice
package.jsonProject metadata, scripts and declared dependenciesReview intentional manifest changes
package-lock.jsonResolved npm dependency treeCommit it for a reproducible application install
node_modules/Installed package contentsDo not commit; recreate from the manifest and lockfile
src/Application source modulesOrganize by feature or clear responsibility
⚠️ Important
Do not casually delete or regenerate a lockfile in a team project. That can change many transitive dependency versions and create a much larger review than the manifest edit suggests.
// Part 05 — Run Vite

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.

bash
npm create vite@latest my-expense-app
cd my-expense-app
npm install
npm run dev

The 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.

bash
npm run build
npm run preview

Scripts 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.

📌 Real World Example
A real feature branch might run the dev server for quick feedback, run lint and tests before review, then create a production build in continuous integration. Each step catches a different class of problem.
// Part 06 — Toolchain

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.

  1. Install the project dependencies from the manifest and lockfile.
  2. Start the development server and verify the feature in a browser.
  3. Run the project checks, such as tests and linting, when they are configured.
  4. Create a production build and inspect the output for missing assets or configuration.
  5. 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.

🎯 Pro Tip
A lockfile makes dependency resolution more reproducible, but it is not a security guarantee. Keep dependencies maintained, review updates, and use the repository's standard checks before release.
// Part 07 — Maintainability

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.

⚠️ Important
A bundler can make code easier to ship, but it cannot hide credentials from the browser. If a browser needs a private service, call your own server and have that server protect the credential.
// Part 08 — Pitfalls

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.

// Part 09 — Practice

Split the Expense Tracker into Modules

Practice

Create a small, repeatable JavaScript project

  1. Create a Vite vanilla JavaScript project and inspect its generated manifest and source entry.
  2. Move rupee formatting into a module that exports a named formatRupees function.
  3. Create a second module that imports the formatter and renders one sample expense.
  4. Add or review dev, build, and preview scripts; run the production build and inspect the result.
  5. Explain why the lockfile is committed while node_modules is not.
  6. 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.

Choose your feedback

Spotted a mistake or something unclear? Suggest a fix on GitHub or email us. Select the text first and it is quoted for you.

Share

Discussion

0

Have a better approach? Found something outdated? Share it — your knowledge helps everyone learning here.

Continue with GitHub
Loading...