Webpack:无需捆绑即可加载外部 JSON [英] Webpack: Loading external JSON without bundling

查看:29
本文介绍了Webpack:无需捆绑即可加载外部 JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 redux + deku 构建我的第一个单页网站,我需要将它国际化.我想要一个包含所有文本的 json 文件,如下所示:

I'm building my first one-page site using redux + deku and I need to internationalize it. I want to have a json file with all the texts, something like this:

# http://mysite.me/assets/i18n.json
{
  "en": {
    "greeting": "Hello"
  },
  "es": {
    "greeting": "Hola"
  }
}

理想情况下,我可以在我的启动文件中要求它:

Ideally I can require it in my boot file:

const T = require('/assets/i18n.json')
setTranslation(T)

但它不能捆绑在同一个文件中,它应该保留一个外部依赖项并且应该在运行时加载,这样我就可以编辑它而无需重新编译整个应用程序!

But it mustn't be bundled in the same file, it should remain an external dependencies and it should load at runtime, so that I can edit it without needing to recompile the entire app!

webpack 可以吗?将它直接包含在 HTML 中是我唯一的选择吗?

Is it possible with webpack? Is my only option to include it directly in the HTML?

<script type="text/javascript" src="i18n.js"></script>
<script type="text/javascript" src="app.js"></script>

现在最后一个解决方案还可以,但我正在考虑将翻译拆分为每个主要组件,因此能够直接通过 js 包含它会很好.

For now this last solution is ok, but I was thinking on splitting the translations per main components, therefore the ability to include it directly through js would be nice.

感谢任何愿意提供帮助的人:)

Thanks to anyone who will help :)

推荐答案

一种选择是不require文件而是fetch(或其他一些请求方法),然后从 webpack 中排除 JSON.

One option would either to not require the file but instead fetch (or some other request method) and then exclude JSON from webpack.

另一种方法是使用 webpack 的通用块插件拆分代码.你的 webpack 配置看起来像这样:

The other way would be to split the code using the common chunks plugin for webpack. Your webpack config would look something like this:

entry: {
    app: './index.jsx',
    i18n: [
        'en',
        'fr',
        '...others'
    ]
},
output: {
    path: '/path/to/dist/',
    filename: '[name].js'
}

查看官方文档了解更多信息

这篇关于Webpack:无需捆绑即可加载外部 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆