Module / Import

A file with private code and explicit exports that other files can bring in with import.

how do I use code from another fileexport this function to another filesplit JavaScript into filesthe import export thingdoes not provide an export named defaultmoduelrequire versus importcannot use import statement outside a module

What it is

A module is a file with its own scope that deliberately exposes values with export. Another module consumes them with import. In standard JavaScript modules, 'export const total = ...' creates a named export, 'export default ...' creates one default export, and 'import("./chart.js")' loads a module on demand.

Use modules to give code clear ownership: parsing lives in one file, UI components in another, and callers import only the public pieces they need. Static imports also give Vite, webpack, and other bundlers a graph they can split, reorder, and tree-shake. Browsers can run the same syntax directly from a script with type="module". This syntax landed in ES2015; the older require() and module.exports style you still meet in Node is CommonJS, a different system.

The common trap is confusing default and named exports, which produces errors that look like a missing file even when the path is right. Circular imports are worse: a module can observe another module before its values are initialized. Keep dependencies pointing in a clear direction, avoid work with side effects at module scope, and use dynamic import only when the code truly belongs behind a loading boundary.

Ask AI for it

Split this Vite TypeScript file into ES modules: move parsing, validation, and formatting into focused files with named exports, import those names explicitly at each call site, and reserve one default export for the page component. Replace the heavy chart import with dynamic import() behind the chart button, remove module-scope side effects, and verify the production bundle tree-shakes unused exports.

You might have meant

bundlertree shakingcode splittingside effect

Go deeper