how to rollupjs resolve imports to create bundle file ?
- User
how to rollupjs resolve imports to create bundle file ?
- Assistant
To create a bundle file with Rollup.js that resolves imports, you need to configure Rollup to:
- Resolve module imports (e.g., from
node_modulesor relative paths). - Bundle all dependencies into a single output file.
Here’s a step-by-step guide:
1. Install Rollup and plugins
You need Rollup and the
@rollup/plugin-node-resolveplugin to resolve imports fromnode_modulesor local files.npm install --save-dev rollup @rollup/plugin-node-resolveIf you also want to handle CommonJS modules (many npm packages are CommonJS), install the CommonJS plugin:
npm install --save-dev @rollup/plugin-commonjs
2. Create a Rollup config file (
rollup.config.js)import resolve from '@rollup/plugin-node-resolve'; import commonjs from '@rollup/plugin-commonjs'; export default { input: 'src/index.js', // Your entry file output: { file: 'dist/bundle.js', // Output bundle file format: 'iife', // Immediately Invoked Function Expression (for browsers) name: 'MyBundle', // Global variable name for IIFE/UMD bundles sourcemap: true // Optional: generate source maps }, plugins: [ resolve(), // Helps Rollup find node_modules packages commonjs() // Converts CommonJS modules to ES6, so Rollup can include them ] };
3. Run Rollup
Add a script to your
package.json:"scripts": { "build": "rollup -c" }Then run:
npm run build
What happens?
- Rollup starts from
src/index.js. - It follows all
importstatements. - The
resolveplugin allows Rollup to find modules innode_modules. - The
commonjsplugin converts CommonJS modules to ES modules. - Rollup bundles everything into a single file
dist/bundle.js.
Example
Suppose you have:
// src/index.js import _ from 'lodash'; console.log(_.join(['Hello', 'Rollup'], ' '));After running the build,
dist/bundle.jswill contain your code plus the lodash code, all bundled together.
If you want a minimal example without plugins (only local ES modules):
// rollup.config.js export default { input: 'src/index.js', output: { file: 'dist/bundle.js', format: 'esm' } };But this won’t resolve
node_modulespackages.
If you want me to help with a specific setup or error, just ask!
- Resolve module imports (e.g., from
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.