From brunch to webpack: require() replacement

I am trying to understand how to switch my project to webpack.

I originally set things up based on the guide here: https://phoenixframework.org/blog/static-assets

I have a bunch of different javascript files, and when I need the code from one of the files, I require() it on the page where I need code from that file

I understand that “require()” is in fact part of Brunch’s “bootstrapper” code, but what I haven’t figured out is what the equivalent is in Webpack.

require is part of the CommonJS module standard used by Node.js and webpack has no problem dealing with it.

The sample JS files that are part of the Phoenix 1.4 distribution use the more recent ES2015 module standard which is the currently recommended standard for use with client side code (which requires the inclusion of babel-loader in the webpack configuration).

So you should be able to get your current JS code to work with webpack - in fact for the time being the webpack.config.js is easier to maintain in the CommonJS style.

However eventually you should familiarize yourself with ES2015 modules and update your client side code (import / export, JavaScript Modules, Modular JavaScript).


Modern JavaScript Explained For Dinosaurs

2 Likes