Search code examples
javascriptbundlerollupjs

Use glob or regex pattern for rollup.js externals


Is it possible to use a glob or regex pattern for the externals in my rollup config? With this config:

export default {
  ...
  external: [
    'prop-types',
    'react',
    'prettier/standalone',
    'prettier/parser-babylon',
    'react-syntax-highlighter/prism-light',
    'react-syntax-highlighter/languages/prism/jsx',
    'react-syntax-highlighter/styles/prism/tomorrow',
    'react-element-to-string'
  ],
  ...
};

I would like to do something like:

export default {
  ...
  external: [
    'prop-types',
    'react',
    'prettier/**',
    'react-syntax-highlighter/**',
    'react-element-to-string'
  ],
  ...
};

Solution

  • This is not possible at the moment. You can however use a function to achieve something similar:

    export default {
      ...
      external(id) {
        return [
          'prop-types',
          'react',
          'prettier',
          'react-syntax-highlighter',
          'react-element-to-string'
        ].includes(id.split('/')[0]);
      },
      ...
    };
    

    You should avoid costly computations in this function as it will be called a lot (once for every import in every file to be precise).

    Another option is to add the rollup-pluginutils package as a dependency which contains a createFilter function for glob support:

    import { createFilter } from 'rollup-pluginutils';
    
    const external = createFilter([
      'prop-types',
      'react',
      'prettier/**',
      'react-syntax-highlighter/**',
      'react-element-to-string'
    ], null, {resolve: false});
    // {resolve: false} will make sure these filters are not passed to
    // path.resolve first and resolved against the current working directory
    
    export default {
      ...
      external,
      ...
    };