Webpack Node.js Addon Loader

2.1.0 · active · verified Sun Apr 19

node-loader is a Webpack loader designed to facilitate the bundling and usage of Node.js native add-ons (files with the `.node` extension) within Webpack-powered applications. It is particularly useful for projects targeting Node.js environments, including Electron's main and renderer processes. The current stable version is `2.1.0`, released in November 2024. The project generally follows an irregular release cadence, focusing on compatibility with newer Webpack and Node.js versions, as well as addressing specific issues like platform compatibility (e.g., macOS dlopen). Its primary differentiator is its specific focus on handling native Node.js modules, a niche that requires careful configuration within Webpack due to the binaries involved. It handles copying the native module to the output directory and ensures it can be dynamically loaded at runtime.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to configure webpack with `node-loader` to process native `.node` modules. It includes the essential `target: 'node'` and `node: { __dirname: false }` settings, and an example of importing a native module in application code.

const path = require('path');
const fs = require('fs');

// Create a dummy .node file for the quickstart
const dummyNodeModulePath = path.resolve(__dirname, 'dummy.node');
fs.writeFileSync(dummyNodeModulePath, '// This is a placeholder for a native Node.js module');

// webpack.config.js
module.exports = {
  mode: 'development',
  entry: './index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
  },
  resolve: {
    extensions: ['...', '.node'],
  },
  target: 'node', // Crucial for node-loader
  node: {
    __dirname: false, // Crucial for node-loader
  },
  module: {
    rules: [
      {
        test: /\.node$/,
        loader: 'node-loader',
        options: {
          name: '[name].[ext]'
        }
      },
    ],
  },
};

// index.js (application entry point)
// For demonstration, we'll pretend 'dummy.node' is a real native module
// In a real scenario, this would be a compiled C++ addon.
const nativeModule = require('./dummy.node'); 

console.log('Native module loaded:', nativeModule); 
// Expected output: Native module loaded: {}
// (Since dummy.node is empty, but the loader successfully processed it)

// To run:
// 1. npm install webpack webpack-cli node-loader
// 2. Save the webpack config above as `webpack.config.js`
// 3. Save the index.js content above as `index.js`
// 4. Create a dummy.node file (as shown in the config comments)
// 5. Run `npx webpack`
// 6. Then `node dist/bundle.js`

view raw JSON →