native-addon-loader
raw JSON → 2.0.1 verified Sat Apr 25 auth: no javascript
A webpack loader for bundling .node native addon files. Version 2.0.1 supports configuring output filename and path relative to webpack's output path. It is designed for Node.js or Electron main process targets. Unlike generic file loaders, it ensures .node binaries are emitted intact and correctly referenced in the bundle. Stable API with simple options: 'name' for filename template and 'from' for adjustment of relative path from output directory to emitted file. Last updated in 2021; low maintenance cadence.
Common errors
error Module parse failed: Unexpected character '\x7f' (1:0) ↓
cause Webpack is trying to parse the .node file as JavaScript.
fix
Ensure the rule with native-addon-loader has test: /\.node$/ and no other loaders match .node files.
error Error: Cannot find module './path/to/addon.node' ↓
cause The emitted .node file is not in the expected output directory.
fix
Check the 'name' option matches the require path in your code. Use name: '[name].[ext]' to keep the same filename.
error TypeError: loaderContext.getOptions is not a function ↓
cause Using an older version of webpack (before 4.x) that doesn't support getOptions.
fix
Upgrade to webpack 4 or 5, or use native-addon-loader@1.x for webpack < 4.
Warnings
breaking Webpack 5 may require additional configuration for asset modules. ↓
fix Use type: 'javascript/auto' in the rule to disable asset module handling for .node files.
deprecated Version 2.x is the latest and stable. ↓
fix No action needed; if using older version, upgrade to 2.x.
gotcha The 'from' option is relative to webpack's output path, not the source file location. ↓
fix Set 'from' to the path where your JavaScript bundles are output relative to output.path (e.g., 'js').
Install
npm install native-addon-loader yarn add native-addon-loader pnpm add native-addon-loader Imports
- default config wrong
module.exports = { module: { rules: [ { test: /\.node$/, loader: 'file-loader' } ] } }correctmodule.exports = { module: { rules: [ { test: /\.node$/, loader: 'native-addon-loader' } ] } }
Quickstart
// webpack.config.js
const path = require('path');
module.exports = {
target: 'node',
output: {
path: path.join(__dirname, 'dist'),
filename: 'js/[name].js'
},
module: {
rules: [
{
test: /\.node$/,
use: [
{
loader: 'native-addon-loader',
options: {
name: 'addons/[name]-[hash].[ext]',
from: 'js'
}
}
]
}
]
}
};