1

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"
  }
2
  • Can you elaborate on the client side part? Browsers don't implement the CommonJS module system. Are you using browserify? Commented Jun 22, 2015 at 4:39
  • yep using browserify with babelify transform will update Commented Jun 22, 2015 at 4:43

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.