Chrome Extension Development with Bower, Grund and RequireJS


Development

I just wanted to start a chrome extension and figured I should check out what all the hype with the frontend tooling scene is all about. The ecosystem looks pretty amazing, however, it seemed like there wasn't a lot of content out there on how to make the chrome-extension work with require-js for modular JS, so I figured i'd write it down here.

My situation

Generally, you don't have many dependencies/modules, so you could just manage them manually by listing them in the correct order in the manifest.json (jquery, backbone, models, controllers, views). However, I expected to have a reasonably complex app, so I figured i want a module loader like require-js manage the dependency tree. It gets a little more complicated if you have more than just a contentscript (since you to encourage maximum code sharing), but in my case, it was fine to just squash everything into one contentscript.js at the end.

Basically, you have to

Generate the scaffold

You can do that by simply following the instructions on https://github.com/yeoman/generator-chrome-extension and https://github.com/gruntjs/grunt-contrib-requirejs for initial setup.

Additions to Gruntfile.js:

Basically, this tells to grunt to resolve the dependencies as expressed in contentscriptsrc with almond, with specified R.js config at contentscriptconfig.js and output everything into contentscript.js in the requirejs:contentscript task.

You'd probably also add this under the watch task to recompile anytime a significant file has changed:

Additions to contentscrupt_config.js:

You wanna tell it about libs that aren't covered by the baseUrl. You can decide whether you want to load dependencies into the contentscript.js or just in the manifest.json.

comments powered by Disqus