Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expose Rails Env to Webpacker

I'm running Rails v5 with Webpacker v2. Everything's been smooth so far, but I've hit one hiccup: how to expose Rails helpers to my TypeScript.

I know Webpacker ships with rails-erb-loader, so I was expecting that I'd be able to add .erb to a TypeScript file, and then import that file elsewhere:

// app/javascript/utils/rails.ts.erb
export const env = "<%= Rails.env %>"

export function isEnv(envName: string) {
  return env == envName
}

// app/javascript/packs/application.ts
import { env } from "../utils/rails"

But Webpack can't find the "rails" file even if I modify the typescript loader to include ERB files:

module.exports = {
  test: /.ts(\.erb)?$/,
  loader: 'ts-loader'
}

All I see is:

error TS2307: Cannot find module '../utils/rails'.

What's the best way to go about exposing Rails helpers and variables to my JavaScript?

like image 234
fny Avatar asked Jun 26 '17 23:06

fny


Video Answer


2 Answers

Rails env comes from your environment variable. This means you configure it by setting (in bash for example) the variable in this way:

export RAILS_ENV=production

As a consequence, you don't need to deal with Rails at all.

// app/javascript/utils/rails.ts.erb
export const env = process.env.RAILS_ENV || "development"

export function isEnv(envName: string) {
  return env == envName
}

This comes with a great advantage: you don't have to load the whole rails app just to compile your javascript. Rails can become really slow on first load if your app grows.

Since you won't have access to process.env on the frontend (browser), you also need a way to make it exist. In webpack, this is done through the DefinePlugin:

Update your webpack configuration to use the plugin (in plugins section): new webpack.DefinePlugin({ "process.env": { RAILS_ENV: process.env.RAILS_ENV } }) and you will get a process.env.RAILS_ENV available in the client

like image 62
Francesco Belladonna Avatar answered Sep 29 '22 22:09

Francesco Belladonna


Rails Env can be accessed through:

process.env.RAILS_ENV
like image 20
Jeremy Lynch Avatar answered Sep 29 '22 23:09

Jeremy Lynch