in JavaScript, Programming

Migrate from RequireJS to webpack

I started this year a small Backbone project used by me to learn front end development. It uses a combination of Apache and RequireJS configuration to locate and deliver the scripts to the browser. RequireJS is used to modularize the code and provide dependencies:

index.html:

Library.js:

and Apache to locate those sources on my disc:

/etc/apache2/sites-available/000-default.conf:

This setup works really well, especially for a small project like this one, but it was time to move on to webpack and my intention was to remove RequireJS configuration, add the webpack one and change the code only if it is really, really needed.

The first step was to add a package manager but this was already done in a previous post. I chose to use Yarn and I still had to use Bower as a post install script.

package.json:

The next step was to add needed dependencies for webpack and apply necessary changes to the project:

package.json:

index.html:

  • script tag was removed. It will be added dynamically by webpack.

Library.js:

  • RequireJS configuration is not needed anymore.

webpack.config.js:

  • I added resolve.modules and resolve.descriptionFiles to locate bower components.
  • I added src/main/resources/public/js to resolve.modules to be able to use require with full path to the script: Books = require('collections/Books')
  • alias is obvious. I did not wanted to change require('i18n'); with require('jquery-i18n-properties');.
  • raw-loader imports files as a string and by using text as its alias I could import backbone templates in the same way: searchBooksHtml = require('text!templates/SearchBooks.html').
  • I added context to change the path webpack uses to locate sources files.
  • entry specifies the script that loads the application and output the output bundle script. I also added devtool to be able to debug the application.
  • CleanWebpackPlugin deletes dist folder at every build.
  • HtmlWebpackPlugin is used to generate a bundle html file based on a template. In this case it will add the bundle script file: <script type="text/javascript" src="/index.js"></script></body>.
  • webpack.ProvidePlugin will load automatically jquery whenever it detects it as free variable in a module, in this case it is needed by jquery-i18n-properties.

This application is not complicated and migration went quite smooth. I hope you’ll find something useful for your project migration.

Your thoughts are welcome