如何在EJS文件[WEBPACK]中获取JSON内容 [英] How to get JSON content in EJS file [WEBPACK]
问题描述
我想从外部 JSON 文件中获取值,并在我的EJS文件中使用这些值 ,该文件由Webpack编译为HTML.
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.
我的JSON& EJS正常工作.
我在EJS中尝试类似的事情:
I trying things like that in my EJS :
<%=
require('./components/products.json')
%>
但是我在渲染器上获得的唯一输出(在HTML文件中)是:
But the only output (in a HTML file) i get at the render is :
"components/products.json"
我尝试使用Fetch,但是在打包时Webpack无法识别它.并且还尝试将其传递给变量但结果相同.
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.
目标是在JSON中显示图像的 URL ,要求将其作为图像的 src . EJS文件.
The objective is to display images's URL contained in the JSON to require them as image's src in the EJS file.
推荐答案
最后,我找到了合适的解决方案.对于将来会来这里的人们:
Finally, i've find a proper solution. For future people who will come here :
一切都在webpack.config.js
1)第一次我需要JSON文件:
1) In a first time i require my JSON file :
const productsJson = require('.src/components/products.json')
2)然后,我在插件数组中添加以下代码:
2) Then i add the following code in my plugins array :
new HtmlWebpackPlugin({
template: './src/index.ejs',
templateParameters: {
'myJSON': productsJSON
}
})
3)最后,在index.ejs
中不需要文件,它已经由webpack.config.js
加载.要显示JSON内容,您只需要执行以下行:
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 %>
这篇关于如何在EJS文件[WEBPACK]中获取JSON内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!