0

I want to get values from an external JSON file and use these values in my EJS file which is compiled as HTML by webpack.

My JSON & EJS working properly.

I trying things like that in my EJS :

<%=
require('./components/products.json')
%>

But the only output (in a HTML file) i get at the render is :

"components/products.json"

I've tried to use Fetch but at bundle time Webpack don't recognize it. And also tried to pass it in a variable but same result.

The objective is to display images's URL contained in the JSON to require them as image's src in the EJS file.

PedroZorus
  • 661
  • 1
  • 6
  • 21

1 Answers1

1

Finally, i've find a proper solution. For future people who will come here :

Everything happens in webpack.config.js


Setting-Up :

1) In a first time i require my JSON file :

const productsJson = require('.src/components/products.json')

2) Then i add the following code in my plugins array :

new HtmlWebpackPlugin({
    template: './src/index.ejs',
    templateParameters: {
        'myJSON': productsJSON
    }
})

3) Finally, In the index.ejs isn't needed to require the file, it's already loaded by the webpack.config.js. To display the JSON content, you simply need to do the following line :

<%= myJson.anything_In_My_Json %>

PedroZorus
  • 661
  • 1
  • 6
  • 21