2

Question: is there a way to tell webpack to tell built-in modules modules like fs to execute during build so the browser gets the result of this function, not the function call itself?

My Situation:

Currently I'm developing an application for the browser using webpack. I'm trying to use the node 'fs' module in one my files to require the index.js files from other directories. For example:

plugins
├──plugin1
│   ├── index.js (simply exports an object)
│
├──plugin2
│  ├── index.js (simply exports an object)
|
├──plugin3
│  ├── index.js (simply exports an object)
|
|──index.js (want to require all index.js from each plugin directory here)

I'm getting an error with webpack saying: Can't resolve 'fs' in somepath/node_modules/require-dir

My file index.js located at `plugins/index.js' which is simply trying to require my other files.

  //module from NPM which uses the 'fs' module ('im not explicity using it)
  const requireDir = require('require-dir');
  const allPlugins = requireDir('./plugins/'); 
  console.log(allPlugins); 

Can't resolve 'fs' in '/some_path/node_modules/require-dir'

Clifford Fajardo
  • 1,357
  • 1
  • 17
  • 28

2 Answers2

2

You have two options here.

  1. I haven't used this personally, but you can use node config value as specified here.

node: { fs: {true, "mock", "empty", false} }

Set fs to any of the above values.

  1. Don't use the fs module. It is a built/native modules which may or may not rely on native V8/C++ functions/libraries. Remember that webpack typically bundles assets for the browser. So instead of relying on a plugin, you can manually import your plugins like:

plugins/index.js

const plugin1 = require('./plugin1')
const plugin2 = require('./plugin2')

module.exports = {
  plugin1,
  plugin2
}

You could also use this answer to polyfill the require-dir module.

Cisco
  • 20,972
  • 5
  • 38
  • 60
  • Thanks for dropping the link to polyfill `require-dir` I found my solution there =). The requiring of each file also works too, totally forgot about that. – Clifford Fajardo Jul 26 '17 at 06:20
  • Starting with webpack 5, the first option is changed, now the ``resolve.fallback`` prop is used to polyfill node libraries. https://webpack.js.org/configuration/resolve/#resolvefallback – Lukas Bach Mar 12 '21 at 00:11
0

Thanks to Francisco Mateo's additional link about polyfilling require-dir, I learned about the context method that webpack adds to require.

This allows me to do dynamic requires like so in my plugins/index.js file:

  //require all index.js files inside of /plugins directory        
  let context = require.context('.', true, /\index\.js/);
  const loadPlugins = function(ctx){
    let keys = context.keys();
    let values = keys.map(context);
    return values;
  }
   //array of values from each index.js require
  console.log('loadPlugins', loadPlugins()); 
Clifford Fajardo
  • 1,357
  • 1
  • 17
  • 28