1

Can someone maybe explain me, how this build-time require works?

https://github.com/kriasoft/react-starter-kit/blob/feature/redux/src/server.js#L89

They are requiring a jade template, which package or configuration allows this, I seem unable to find it myself.

const template = require('./views/index.jade')

I think is much more elegant then:

import jade from 'jade'
const template = jade.compile('./views/index.jade')
Pepijn
  • 1,204
  • 1
  • 11
  • 25
  • Possible duplicate of [What is this Javascript "require"?](http://stackoverflow.com/questions/9901082/what-is-this-javascript-require) – KWeiss May 23 '16 at 09:49
  • "`require()` is not part of your standard JavaScript. In context to your question and tags, `require()` is built into Node.js to load *modules*." http://stackoverflow.com/a/9901097/5742681 – KWeiss May 23 '16 at 09:50
  • 2
    In addition to the links above, that project is using [Webpack](https://github.com/kriasoft/react-starter-kit/blob/feature/redux/tools/webpack.config.js) which means that this transformation happens at *build-time*, rather than at *runtime* like `jade.compile` – CodingIntrigue May 23 '16 at 12:03

2 Answers2

2

As RGraham mentioned in his comment, the require call is being "intercepted" during webpack's compilation of the application bundle. This is done using "loaders" that define particular behaviour for imports of a particular type:

Loaders allow you to preprocess files as you require() or “load” them.

In this particular case, the loader that does this modification could be one of these (or another that I didn't find in my search):

Edit: looking at the project's own webpack configuration we can see it is the second link above:

{
  test: /\.jade$/,
  loader: 'jade-loader',
}
sdgluck
  • 24,894
  • 8
  • 75
  • 90
0

jade-loader reads the content of the specified file, which make look something like this (Jade string):

h1 Hello, #{author}!

..and replaces that with a CommonJS JavaScript code similar to this (at compile time):

module.exports = function(data) {
  return `<h1>Hello, ${data.name}</h1>`;
};
Konstantin Tarkus
  • 37,618
  • 14
  • 135
  • 121