Skip to content

Instantly share code, notes, and snippets.

@n0nick
Last active June 25, 2017 05:24
Show Gist options
  • Save n0nick/7881ed97aa367167305958d19b26ca37 to your computer and use it in GitHub Desktop.
Save n0nick/7881ed97aa367167305958d19b26ca37 to your computer and use it in GitHub Desktop.
Webpack plugin for copying JS assets from Ruby gems (in a Webpacker/Rails project)
// config/webpack/plugins/copy_gem_assets_plugin.js
const copy = require('copy');
const path = require('path');
const { execSync } = require('child_process');
const { settings } = require('../configuration.js');
function CopyGemAssetsPlugin(options) {
this.gemsList = options.gems || [];
this.outPath = options.outPath || path.join('vendor', 'gems');
}
CopyGemAssetsPlugin.prototype.apply = function(compiler) {
const destination = path.resolve(settings.source_path, this.outPath);
const gemPaths = this.gemsList.map(gem =>
execSync(`bundle show ${gem}`).toString().trim()
);
compiler.plugin('compile', function(params) {
gemPaths.forEach(gemPath => {
copy(
`${gemPath}/{app,vendor}/assets/javascripts/*`,
destination,
{
flatten: true
},
err => {
if (err) throw err;
}
);
});
});
};
module.exports = CopyGemAssetsPlugin;
// USAGE EXAMPLE -- in a Rails/Webpacker project this will be in config/webpack/shared.js
// ...
plugins: [
// ...
new CopyGemAssetsPlugin({
gems: [
'js-routes',
'client_side_validations',
'client_side_validations-simple_form'
]
})
],
// ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment