ncc
Compile a Node.js project into a single file. Supports TypeScript, binary addons, dynamic requires.
Top Related Projects
An extremely fast bundler for the web
Next-generation ES module bundler
A bundler for javascript and friends. Packs many modules into a few bundled assets. Code Splitting allows for loading parts of the application on demand. Through "loaders", modules can be CommonJs, AMD, ES6 modules, CSS, Images, JSON, Coffeescript, LESS, ... and your custom stuff.
The zero configuration build tool for the web. 📦🚀
A JavaScript checker and optimizer.
Quick Overview
Vercel/ncc is a simple CLI tool for compiling a Node.js module into a single file, together with all its dependencies. It's designed to produce a compact, self-contained JavaScript file that can be easily deployed or distributed without the need for a node_modules
folder.
Pros
- Simplifies deployment by bundling all dependencies into a single file
- Reduces package size by eliminating unnecessary files and code
- Improves startup time by avoiding the need to resolve dependencies at runtime
- Supports TypeScript and other languages that compile to JavaScript
Cons
- May increase the size of small projects due to bundling all dependencies
- Some dynamic imports or complex module structures might not be compatible
- Limited customization options compared to more complex bundlers
- Potential issues with native modules or platform-specific dependencies
Getting Started
To use vercel/ncc, first install it globally:
npm i -g @vercel/ncc
Then, compile your Node.js application:
ncc build input.js -o dist
This will create a single file dist/index.js
containing your application and its dependencies. You can then run this file directly with Node.js:
node dist/index.js
For more advanced usage, you can add scripts to your package.json
:
{
"scripts": {
"build": "ncc build src/index.js -o dist"
}
}
Then run the build process with:
npm run build
Competitor Comparisons
An extremely fast bundler for the web
Pros of esbuild
- Significantly faster build times due to its Go-based implementation
- Supports a wider range of input formats, including TypeScript and JSX
- More actively maintained with frequent updates and improvements
Cons of esbuild
- Less focused on single-file output, which is ncc's primary use case
- May require additional configuration for certain Node.js-specific use cases
- Larger file size for the esbuild binary compared to ncc
Code Comparison
ncc:
const ncc = require('@vercel/ncc')
ncc('input.js', {
minify: true,
sourceMap: false
}).then(({ code, map, assets }) => {
console.log(code)
})
esbuild:
const esbuild = require('esbuild')
esbuild.build({
entryPoints: ['input.js'],
bundle: true,
minify: true,
outfile: 'output.js',
}).then(() => console.log('Build complete'))
Both tools aim to bundle JavaScript code, but they have different focuses. ncc is designed specifically for creating single-file Node.js applications, while esbuild is a more general-purpose bundler and minifier. esbuild offers superior performance and broader language support, but ncc may be simpler for specific Node.js bundling tasks.
Next-generation ES module bundler
Pros of Rollup
- More flexible and configurable, allowing for fine-tuned bundling
- Better support for ES modules and tree-shaking
- Extensive plugin ecosystem for various optimizations and transformations
Cons of Rollup
- Steeper learning curve due to its flexibility and configuration options
- May require more setup time for complex projects
- Less optimized for Node.js applications compared to NCC
Code Comparison
Rollup configuration example:
export default {
input: 'src/main.js',
output: {
file: 'bundle.js',
format: 'cjs'
}
};
NCC usage example:
ncc build input.js -o dist
Rollup offers more granular control over the bundling process, while NCC provides a simpler, more streamlined approach for Node.js applications. Rollup excels in creating optimized bundles for browser-based applications and libraries, whereas NCC is specifically designed for Node.js projects and offers better compatibility with Node.js-specific features and modules.
Both tools have their strengths, and the choice between them depends on the specific requirements of your project, such as target environment, complexity, and desired level of optimization.
A bundler for javascript and friends. Packs many modules into a few bundled assets. Code Splitting allows for loading parts of the application on demand. Through "loaders", modules can be CommonJs, AMD, ES6 modules, CSS, Images, JSON, Coffeescript, LESS, ... and your custom stuff.
Pros of webpack
- Highly configurable and flexible, supporting a wide range of project types and sizes
- Extensive ecosystem with numerous plugins and loaders
- Powerful code splitting and dynamic imports for optimized loading
Cons of webpack
- Steeper learning curve and more complex configuration
- Slower build times for large projects
- Larger bundle sizes if not properly optimized
Code Comparison
webpack configuration:
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [
{ test: /\.js$/, use: 'babel-loader' },
],
},
};
ncc usage:
ncc build input.js -o dist
Summary
webpack is a powerful and flexible bundler with a vast ecosystem, suitable for complex projects. It offers advanced features like code splitting and dynamic imports but comes with a steeper learning curve and potentially slower build times.
ncc, on the other hand, provides a simpler, zero-configuration approach for bundling Node.js projects. It's faster and easier to use but lacks the extensive customization options of webpack.
Choose webpack for larger, more complex projects that require fine-tuned control over the build process. Opt for ncc when you need a quick, straightforward bundling solution for Node.js applications with minimal configuration.
The zero configuration build tool for the web. 📦🚀
Pros of Parcel
- Zero configuration bundling for multiple languages and file types
- Built-in support for CSS, SCSS, TypeScript, and more
- Hot module replacement and automatic code splitting
Cons of Parcel
- Larger bundle sizes compared to more specialized bundlers
- Slower build times for complex projects
- Less control over the bundling process
Code Comparison
Parcel:
// No configuration needed, just run:
parcel index.html
NCC:
// Compile a project:
ncc build input.js -o dist
Key Differences
Parcel is a full-featured, zero-config bundler supporting multiple languages and file types, while NCC is focused on compiling Node.js projects into single files. Parcel offers more out-of-the-box features and broader language support, but NCC provides smaller bundle sizes and faster compilation for Node.js applications.
Parcel is ideal for web projects with diverse asset types and developers who prefer minimal configuration. NCC is better suited for Node.js projects, especially those targeting serverless environments or requiring single-file distribution.
Choose Parcel for ease of use and broad language support in web development, or NCC for efficient Node.js application bundling and deployment.
A JavaScript checker and optimizer.
Pros of Closure Compiler
- Advanced optimization techniques for JavaScript, resulting in smaller and faster code
- Supports type checking and annotation, enhancing code quality and maintainability
- Extensive configuration options for fine-tuning compilation process
Cons of Closure Compiler
- Steeper learning curve and more complex setup compared to NCC
- Slower compilation times, especially for large projects
- Requires specific coding practices and annotations for optimal results
Code Comparison
Closure Compiler:
/** @const */
var MY_CONSTANT = 'hello';
/** @param {string} name */
function greet(name) {
console.log(MY_CONSTANT + ', ' + name);
}
NCC:
const MY_CONSTANT = 'hello';
function greet(name) {
console.log(`${MY_CONSTANT}, ${name}`);
}
Closure Compiler focuses on advanced optimizations and type checking, requiring specific annotations. NCC, on the other hand, aims for simplicity and ease of use, allowing developers to write standard JavaScript without additional syntax.
While Closure Compiler offers more powerful optimization capabilities, NCC provides a straightforward approach to bundling Node.js applications with minimal configuration. The choice between the two depends on project requirements, team expertise, and the desired level of optimization and type safety.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
ncc
Simple CLI for compiling a Node.js module into a single file, together with all its dependencies, gcc-style.
Motivation
- Publish minimal packages to npm
- Only ship relevant app code to serverless environments
- Don't waste time configuring bundlers
- Generally faster bootup time and less I/O overhead
- Compiled language-like experience (e.g.:
go
)
Design goals
- Zero configuration
- TypeScript built-in
- Only supports Node.js programs as input / output
- Support all Node.js patterns and npm modules
Usage
Installation
npm i -g @vercel/ncc
Usage
$ ncc <cmd> <opts>
Eg:
$ ncc build input.js -o dist
If building an .mjs
or .js
module inside a "type": "module"
package boundary, an ES module output will be created automatically.
Outputs the Node.js compact build of input.js
into dist/index.js
.
Note: If the input file is using a
.cjs
extension, then so will the corresponding output file. This is useful for packages that want to use.js
files as modules in native Node.js using a"type": "module"
in the package.json file.
Commands:
build <input-file> [opts]
run <input-file> [opts]
cache clean|dir|size
help
version
Options:
-o, --out [dir] Output directory for build (defaults to dist)
-m, --minify Minify output
-C, --no-cache Skip build cache population
-s, --source-map Generate source map
-a, --asset-builds Build nested JS assets recursively, useful for
when code is loaded as an asset eg for workers.
--no-source-map-register Skip source-map-register source map support
-e, --external [mod] Skip bundling 'mod'. Can be used many times
-q, --quiet Disable build summaries / non-error outputs
-w, --watch Start a watched build
-t, --transpile-only Use transpileOnly option with the ts-loader
--v8-cache Emit a build using the v8 compile cache
--license [file] Adds a file containing licensing information to the output
--stats-out [file] Emit webpack stats as json to the specified output file
--target [es] ECMAScript target to use for output (default: es2015)
Learn more: https://webpack.js.org/configuration/target
-d, --debug Show debug logs
Execution Testing
For testing and debugging, a file can be built into a temporary directory and executed with full source maps support with the command:
$ ncc run input.js
With TypeScript
The only requirement is to point ncc
to .ts
or .tsx
files. A tsconfig.json
file is necessary. Most likely you want to indicate es2015
support:
{
"compilerOptions": {
"target": "es2015",
"moduleResolution": "node"
}
}
If typescript is found in devDependencies
, that version will be used.
Package Support
Some packages may need some extra options for ncc support in order to better work with the static analysis.
See package-support.md for some common packages and their usage with ncc.
Programmatically From Node.js
require('@vercel/ncc')('/path/to/input', {
// provide a custom cache path or disable caching
cache: "./custom/cache/path" | false,
// externals to leave as requires of the build
externals: ["externalpackage"],
// directory outside of which never to emit assets
filterAssetBase: process.cwd(), // default
minify: false, // default
sourceMap: false, // default
assetBuilds: false, // default
sourceMapBasePrefix: '../', // default treats sources as output-relative
// when outputting a sourcemap, automatically include
// source-map-support in the output file (increases output by 32kB).
sourceMapRegister: true, // default
watch: false, // default
license: '', // default does not generate a license file
target: 'es2015', // default
v8cache: false, // default
quiet: false, // default
debugLog: false // default
}).then(({ code, map, assets }) => {
console.log(code);
// Assets is an object of asset file names to { source, permissions, symlinks }
// expected relative to the output code (if any)
})
When watch: true
is set, the build object is not a promise, but has the following signature:
{
// handler re-run on each build completion
// watch errors are reported on "err"
handler (({ err, code, map, assets }) => { ... })
// handler re-run on each rebuild start
rebuild (() => {})
// close the watcher
void close ();
}
Caveats
- Files / assets are relocated based on a static evaluator. Dynamic non-statically analyzable asset loads may not work out correctly
Top Related Projects
An extremely fast bundler for the web
Next-generation ES module bundler
A bundler for javascript and friends. Packs many modules into a few bundled assets. Code Splitting allows for loading parts of the application on demand. Through "loaders", modules can be CommonJs, AMD, ES6 modules, CSS, Images, JSON, Coffeescript, LESS, ... and your custom stuff.
The zero configuration build tool for the web. 📦🚀
A JavaScript checker and optimizer.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot