Search code examples
javascriptnode.jswebpackrolluprollupjs

Rollup optional input


Is there a way in Rollup to skip an input if it was not found? At the moment the build fails with Error: Could not resolve entry module (src/index.js) as soon as the file was not found.

I went through the documentation and searched around, but I can't seem to find an option or hook to achieve this. In the simplified example below, I would like to continue to the next page.js build when the src/index.js was not found.

export default [
    {
        input: 'src/index.js',
        output: [
            {
                file: 'dist/esm/index.esm.js',
                format: 'esm',
            },
            {
                file: 'dist/cjs/index.js',
                format: 'cjs',
            },
        ],
        plugins: [
            // ...
        ],
    },
    {
        input: 'page.js',
        output: [
            {
                file: 'dist/esm/page.esm.js',
                format: 'esm',
            },
            {
                file: 'dist/cjs/page.js',
                format: 'cjs',
            },
        ],
        plugins: [
            // ...
        ],
    },
];

Solution

  • no idea if this will work or not, code to illstrate further what I'm talking about as a potential solution.

    const fs = require('fs');
    const path = 'src/index.js';
    
    const config = [
    {
            input: 'page.js',
            output: [
                {
                    file: 'dist/esm/page.esm.js',
                    format: 'esm',
                },
                {
                    file: 'dist/cjs/page.js',
                    format: 'cjs',
                },
            ],
            plugins: [
                // ...
            ],
    }];
    
    const determineFileExistsForConfig = () => {
      try {
         // if index exists, add to the config
         if (fs.existsSync(path)) {
           config.push({
            input: 'src/index.js',
            output: [
                {
                    file: 'dist/esm/index.esm.js',
                    format: 'esm',
                },
                {
                    file: 'dist/cjs/index.js',
                    format: 'cjs',
                },
            ],
            plugins: [
                // ...
            ],
        });
         }
      } catch(err) {
        return config;
      }
    }
    
    
    const finalConfig = determineFileExistsForConfig();
    export default finalConfig;