Skip to content

Using JS components from Rails engines

Tomáš Celizna edited this page Oct 25, 2017 · 3 revisions

See a discussion on this topic here https://github.com/rails/webpacker/issues/21.

Follow conventions of rails/webpacker and have your engine export built JS as a NPM module.

To do so, add package.json in your engine along these lines:

{
  "name": "@user/engine",
  "version": "1.0.0",
  "description": "",
  "main": "package/dist/index.js",
  "files": [
    "package"
  ],
  "repository": {
    "type": "git",
    "url": "git+https://github.com/user/engine.git"
  },
  "author": "",
  "license": "",
  "homepage": "",
  "scripts": {
    "build": "webpack"
  },
  "dependencies": {
    "@rails/webpacker": "^3.0.1",
    "babel-preset-react": "^6.24.1",
    "coffee-loader": "^0.8.0",
    "coffeescript": "^2.0.1",
    "prop-types": "^15.5.10",
    "react": "^15.6.1",
    "react-dom": "^15.6.1",
    "webpacker-react": "^0.3.2"
  },
  "devDependencies": {
    "babel-preset-env": "^1.6.0",
    "babel-preset-es2015": "^6.24.1",
    "webpack-dev-server": "^2.8.2"
  }
}

Configure webpack using webpack.config.js. (The configuration below processes CoffeeScript files, however it can be easily adjusted for .jsx etc.)

const path = require('path');
const webpack = require('webpack')

module.exports = {
  module: {
    rules: [
      {
        test: /\.coffee$/,
        use: ['babel-loader', 'coffee-loader']
      }
    ]
  },
  entry: './package/src/index.js',
  output: {
    library: '@user/engine',
    libraryTarget: 'umd',
    umdNamedDefine: true,
    filename: 'index.js',
    path: path.resolve(__dirname, 'package/dist')
  },
  resolve: {
    extensions: ['.coffee', '.js']
  }
};

This configuration assumes source code under package/src, however feel free to adjust the location as necessary. Similarly, the compiled JS will be stored in package/dist as index.js entrypoint.

Build the components using yarn build.

If open source, you can publish the package via NPM and yarn add @user/engine it to your main app. Alternatively you can simply store the built JS in the GitHub repo and yarn add git+https://github.com/user/engine.git the package from the repo in your main app.

In development, it is possible to use combination of yarn link and yarn build --watch in the engine dir and yarn link @user/engine in the main app dir to have the engine's JS code automatically rebuilt on update and changes visible in the main app.