One way of doing this would be to write a simple rails task that generates a JavaScript file containing translations.
namespace :translations do
desc "Create a JavaScript File containing translations"
task :generate => :environment do
locale = ARGV[1] || I18n.default_locale
keys = ['hello', 'goodbye'] # ...
I18n.with_locale(locale) do
data = Hash[keys, keys.map { |k| I18n.t!(k) }]
end
begin
f = File.open(Rails.root.join('app/assets/javascript/translations.js') , 'w')
f.write("export default #{data.to_json}")
ensure
f.close
end
end
end
This would create an ES6 module that looks like this:
export default {
hello: 'Ola',
goodbye: 'Tchau'
}
Which you then import where you need it:
import Translations from 'translations';
If you're not using Webpack you could use the same approach with Sprockets but it don't really see the point as it will process ERB files which is a much simpler solution. You could also potentially use the ERB loader for Webpack to do this.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…