@vercel/ncc

repository·main·Indexed 27 days ago

https://github.com/vercel/ncc

A simple CLI and programmatic API for compiling a Node.js module and all its dependencies into a single file. It supports CommonJS, ES Modules, and TypeScript, providing features such as minification, source maps, and a build cache. Includes commands for building, running, and managing the cache, as well as specific configuration guidance for packages like sequelize and @google-cloud/vision.

Tokens
3.7K
Snippets
11
Records
18
Agent score
93%

What's inside @vercel/ncc

  1. Build a Node.js module with ncc

    main

    Use the build command to compile an input file and its dependencies into a single output file. By default, the output is placed in a dist directory. If the input is an .mjs or .js file within a package marked as "type": "module", an ES module output is created automatically. If the input uses a .cjs extension, the output will also use .cjs.

    $ ncc build input.js -o dist
  2. Configure `@google-cloud/vision` for ncc support

    main

    To ensure @google-cloud/vision works correctly when bundled with ncc, you must add google-proto-files as a dependency in your package.json.

    {
      "name": "example",
      "main": "index.js",
      "dependencies": {
        "@google-cloud/vision": "1.1.1",
        "google-proto-files": "1.0.1"
      }
    }
  3. Configure `sequelize` for ncc support

    main

    When using sequelize with ncc, you must explicitly define the dialectModule in your Sequelize constructor to ensure the database dialect (e.g., mariadb) is correctly bundled. This prevents issues with dynamic requires that ncc might otherwise miss.

    const Sequelize = require('sequelize');
    const db = new Sequelize({
      dialect: 'mariadb',
      dialectModule: require('mariadb')
    });
  4. Build TypeScript projects with ncc

    main

    To use TypeScript, point ncc directly to your .ts or .tsx files. A tsconfig.json file must be present in your project. If typescript is found in your devDependencies, ncc will use that version. It is recommended to set your target to es2015 in your tsconfig.json.

    {
      "compilerOptions": {
        "target": "es2015",
        "moduleResolution": "node"
      }
    }
  5. Run a Node.js module with ncc

    main

    For testing and debugging, use the run command to build a file into a temporary directory and execute it immediately with full source map support.

    $ ncc run input.js
  6. Use @vercel/ncc programmatically

    main

    You can import @vercel/ncc in your Node.js application to perform builds programmatically. The function returns a Promise that resolves to an object containing the compiled code, map, and assets.

    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)
    })
  7. Use ncc watch mode programmatically

    main

    When watch: true is passed to the programmatic API, the return value is not a Promise, but a watcher object with handler, rebuild, and close methods.

    {
      // 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 ();
    }
  8. Reference: ncc CLI Options

    main

    Options for the build and run commands:

      -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
  9. Use ncc in watch mode

    main

    To watch for file changes and trigger rebuilds, pass watch: true or a custom watcher object to ncc(). When using watch mode, ncc returns a controller object to manage the watcher.

    Controller API:

    • close(): Closes the watcher.
    • handler(callback): Sets a callback that is invoked when a rebuild completes.
    • rebuild(callback): Sets a callback that is invoked when a rebuild is triggered.
  10. Compile Node.js modules with ncc()

    main

    The ncc function is the core API for compiling Node.js modules into a single file (or a small set of files) with all dependencies bundled. It supports both CommonJS (CJS) and ES Modules (ESM), TypeScript, minification, source maps, and V8 caching.

    Returns: A Promise that resolves to an object containing:

    • code: The bundled source code as a string.
    • map: A JSON string of the source map (if sourceMap is enabled).
    • assets: An object mapping file paths to their content and permissions.
    • symlinks: An object mapping symlink paths to their targets.
    • stats: Webpack compilation statistics.