Including third-party dependencies in your toolkit
Fabricator makes it easy to include a third-party library like jQuery in your toolkit.
Fabricator uses Webpack to bundle modules using the CommonJS module syntax:
/* src/assets/toolkit/scripts/my-module.js */
module.exports = {
foo: function() {
return 'bar';
}
};
/* src/assets/toolkit/scripts/toolkit.js */
var myModule = require('./my-module');
myModule.foo(); // 'bar'
In the above example, webpack will find all the dependencies and
output a single file that contains both my-module.js
and toolkit.js
.
It's recommended that you leverage either NPM or Bower to manage dependencies.
NPM is the recommended way to add third-party dependencies.
$ npm install --save-dev jquery
By default, if a require()
call is not prefixed with a path, webpack will
recursively search the node_modules
directories for the specified module.
// "./" tells webpack to search the current
// directory for "my-module"
var myModule = require('./my-module');
// no path was specified, so recursively search
// "node_modules" directories for "jquery"
var $ = require('jquery');
$('#my-button').hide();
Bower is a great tool for managing third party client side dependencies. Here's how to leverage Bower on a Fabricator instance:
$ npm install -g bower
$ npm install bower --save-dev
$ bower init
to initialize Bower for your project..bowerrc
config file to your project root..bowerrc
{
"directory": "bower_components"
}
package.json
scripts
object to hook into Bower install task.package.json
"scripts": {
"gulp": "gulp",
"bower": "bower",
"prestart": "npm install",
"build": "npm install && gulp",
"start": "gulp --dev",
"postinstall": "bower install",
"test": "npm run build"
},
Add bower_components
to .gitignore
.
Install dependencies with Bower.
$ bower install --save-dev jquery
webpack.config.js
// add the "resolve" property to the config
var config = {
/* other config properties */
resolve: {
modulesDirectories: ['node_modules', 'bower_components']
}
};
Unlike including NPM dependencies, Bower has no rules for how a module is structured. As a result, you will often have to specify a more specific path:
var myLibrary = require('myLibrary/dist/library');
Many Bower modules are just plain JavaScript files that don't use the CommonJS module syntax; an example might be a jQuery plugin.
Fabricator includes both the Imports Loader and the Script Loader to handle these cases.
// installed via NPM
var $ = require('jquery');
// installed via Bower
require('imports?$=jquery!somePlugin/dist/plugin');
$('#my-button').somePlugin();
This loader evaluates code in the global context, just like you would add the code into a script tag. In this mode every normal library should work. require, module, etc. are undefined.
Note: The file is added as string to the bundle. It is not minimized by webpack, so use a minimized version. There is also no dev tool support for libraries added by this loader.
require('script!anotherLib/lib/another-lib');