Webpack + Jade: data separation, i18n

Slava K
2 min readMar 10, 2017

--

It is always good to have your project code organised and decomposed into multiple files/folders. Certainly, nothing stops you from writing an entire application code within a single file. But that would prove to be a nightmare to read and maintain.

Modern JS frameworks, like Express and others, provide powerful tools for dynamic html rendering, internationalisation, etc.

But what if you don’t have a framework? For instance, besides the main application there is one or more landing pages that should as lightweight as possible but also contain some important js logic and, probably, a little bit of jQuery for dynamic elements.

But even when developing a small site like single landing page it is likely that you would use modern tools like jade, css preprocessors, ES6, etc.

Let’s say there is a jade page or partial containing customer reviews:

h2 Reviews:
.review
.author John Doe
.text Just awesome!
.review
.author Jane Doe
.text Lorem ipsum dolor sit amet
// And so on...

I am big fan of DRY principle so I always try to prevent same piece of code from being repeated over and over again. That is why I’d prefer to write this code using jade capabilities like iteration and interpolation:

-
reviews = [
{
author: 'John Doe',
text: 'Just awesome!'
},
{
author: 'Jane Doe',
text: 'Lorem ipsum dolor sit amet'
}
// And so on...
];
h2 Reviews:
- each review in reviews
.review
.author #{author}
.text #{text}

If html code is not extracted to a separate file in the final build than it is possible to move reviews array to a json file and load it using json-loader:

// structure
- /views
- /data
- reviews.json
- /partials
- reviews.jade

// don’t forget to configure the “json” loader for /.json$/
- reviews = require(“../data/reviews.json”);

h2 Reviews:
- each review in reviews
.review
.author #{author}
.text #{text}

Internationalisation can be performed with the help of webpack.DefinePlugin.

// webpack.config.js
plugins: [
new webpack.DefinePlugin({
LOCALE: JSON.stringify('fr')
})
]

The LOCALE parameter passed to the define plugin will be available in a jade code during jade2html transformation. Then it will be possible to show reviews based on selected language:

- reviews = require("../data/reviews.json")[LOCALE]h2 Reviews:
- each review in reviews
.review
.author #{author}
.text #{text}

--

--

Slava K

Ruby on Rails consultant - web performance, security, scalability, architecture planning. skdev.info. Founder form2chat.io and vkdevlab.org