score:1

Accepted answer

first of all: use that method if you doesn`t want create one more chunk. for example: for use different preview files in you package in different projects and want have fallback without include to main package`s chunk. for other cases create additional chunk is better way.

checking file for exist - not best idea. config file such better because:

  1. manipulate structure without remove files;
  2. easy detect changes;

for include to bundle only useful files i write theme-customize-loader. it`s webpack loader.

  1. add package $ npm install theme-customize-loader --save-dev
  2. add config file in your app

    const data = {
      mymodule: {
        single : 'app/components/single/single.jsx',
        preview: 'my-theme/preview',
      },
      othermodule: {
        preview: false,
      },
    };
    
    module.exports = data;
    

    value can be path to file or false for fallback file.

  3. add to webpack configuration to rules section

    {
      enforce: 'pre',
      test   : /\.jsx$/,
      exclude: /node_modules/,
      use    : [{ loader: 'theme-customize-loader', options: { config: customizeconfig } }],
    },
    

    don`t forget import config file: const customizeconfig = require('./app/configs/customize');

  4. use in file. important: in one string

    let loadcomponent;
    /* customize path: "mymodule.preview" var: "loadcomponent" name: "my-chunk-name" origin: "../components/originpreview.jsx" */
    

more info you can find here: https://www.npmjs.com/package/theme-customize-loader

score:0

a potential solution to your problem is to take advantage of the way that module resolution works.... no custom loader required!

if you leave off the extension and there is a file with the matching name then the file will be used, if the file is missing then it will check for a folder with the matching name and look for an index.js file in the folder. i have only tested this for typescript projects, and using import but it should work the same.
(see: https://webpack.js.org/concepts/module-resolution/#module-paths)

you could have something like this:

some-file.js:

const mymodule = require('./foo/myfile');
// ...

foo/myfile/index.ts: (note the .. below is necessary)

module.exports = require('../bar/myfile.jsx')

now, if foo/myfile.jsx doesn't exist then it would use the foo/myfile/index.js file which re-exports from the bar/myfile.jsx.

but, if foo/myfile.jsx exists then it would use that file. problem solved!

score:1

this should help you. it just uses fs package of node.

var fs = require('fs');

if (fs.existssync(path)) {
    // do something
}

score:3

you can use require.context and a regular expression to match files in the current folder, see the code below.

const requirecustomfile = require.context(
    './', false, /custom.js$/
)

requirecustomfile.keys().foreach(filename => {
    requirecustomfile(filename);
})

Related Query

More Query from same tag