How to set as external all node modules in rollup?

I want to have all modules imported from node_modules as external. What is the configuration for this?

I tried without success :

import path from "path";
import glob from "glob";
import multiEntry from "rollup-plugin-multi-entry";

export default {
    entry: "src/**/*.js",
    format: "cjs",
    plugins: [
        multiEntry()
    ],
    external: glob.sync("node_modules/**/*.js").map(file => path.resolve(file)),
    dest: "dist/bundle.js"
}];

or

import multiEntry from "rollup-plugin-multi-entry";

export default {
    entry: "src/**/*.js",
    format: "cjs",
    plugins: [
        multiEntry()
    ],
    external: id => id.indexOf("node_modules") !== -1,
    dest: "dist/bundle.js"
}];

Solution 1:

You can accomplish that using package.json dependencies field:

const pkg = require('./package.json');

export default {
    // ...
    external : Object.keys(pkg.dependencies),
    // ...
}

Solution 2:

UPDATE:

Use rollup-plugin-auto-external.


Thank @IsidroTorregrosa for his answer (and @maxkueng ofcourse). I improved it by adding node built-in modules (like fs and path) and also peerDependencies. Use:

import builtins from 'builtin-modules/static'
const pkg = require('./package.json')
// ...
export default {
    external: builtins.concat(Object.keys(pkg.dependencies || {})).concat(Object.keys(pkg.peerDependencies || {})),
    // ...
}

See builtin-modules on npmjs.com and also see:

https://github.com/rollup/rollup-plugin-node-resolve#resolving-built-ins-like-fs

Solution 3:

Using rollup 2.63 this works for me

export default {
    // ...
    external: [/node_modules/],
    // ...
}