Search code examples
javascriptnode.jsbrowserify

Using Browserify/Babel/node.js can you require a file based on a variable string


Accoring to this question you can require a path based on a string at runtime in node.js.

Strangely this seems to work for me okay in node server side, but doesn't seem to work client side using Babel/Browserify

For this particular error, I basically had a lot of mock json data I wanted to require for testing, when the actual API was down.

  // slug comes into the function and could for example be 'movies'
  let modulePath = '../mock/products/' + slug + '.js'
  let data = require(modulePath)

This gives me the following error

  Failed! Error: Cannot find module '../mock/products/movies.js'

If I change it to let modulePath = '../mock/products/movies.js' it will be no problem retrieving the data... and as I mention if I run this server side it has no problem, but is no good when I run the code client side.

I am using babel/babelify to transpile the ES6 code to ES5

Using the following command to build with browserify

browserify --debug -t [babelify] client.js > public/js/bundle.js

My Dev devDependencies in my package.json are as follows:

  "devDependencies": {
    "browserify": "^8.0.3",
    "babel": "^4.0.1",
    "babelify": "~6.1.2"
  }

Solution

  • Browserify can only compute the dependencies if they are statically analyzable. It cannot know which modules to bundle if you are generating the import dynamically.