首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用vite动态导入json文件

如何使用vite动态导入json文件
EN

Stack Overflow用户
提问于 2021-06-03 13:18:23
回答 2查看 8.4K关注 0票数 6

我在一个vue-i18n项目中使用努克茨,我想动态地导入我的地区文件。

当我使用webpack时,这些代码运行良好。

plugins/i18n.js

代码语言:javascript
复制
import Vue from 'vue';
import VueI18n from 'vue-i18n';
import config from '@/config';

Vue.use(VueI18n);

let messages = Object;

config.locale.available.forEach(locale => {
    messages[locale] = require(`~/locales/${locale}.json`);
});

export default ({ app, store }) => {
    app.i18n = new VueI18n({
        locale: store.state.locale.locale,
        messages: messages
    });
}

我知道在vitejs中没有require(),这也是vitejs的全球进口特性

  1. 所以我先尝试了如下:
代码语言:javascript
复制
let messages = Object,
    languages = import.meta.glob('../locales/*.json'); // => languages = {} (languages only get {} value)

config.locale.available.forEach(locale => {
    messages[locale] = languages[`../locales/${locale}.json`];
});

但是languages只得到了{}值。

  1. 然后我尝试使用import()
代码语言:javascript
复制
let messages = Object,
    translate = lang => () => import(`@/locales/${lang}.json`).then(i => i.default || i);

config.locale.available.forEach(locale => {
    messages[locale] = translate(locale);
});

终端和控制台都没有错误,但没有正确加载区域设置文件。

只有当我一个一个地import()时,这个问题才会消失:

代码语言:javascript
复制
import en from '@/locales/en.json';
import fr from '@/locales/fr.json';
import ja from '@/locales/ja.json';

let messages = Object;

messages['en'] = en;
messages['fr'] = fr;
messages['ja'] = ja;

CodeSandbox

但是,如何动态地进口呢?

我在谷歌上搜索过,但帮不上什么忙。感谢任何人的帮助!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-11-21 18:26:14

所以,我想我想出了一些基于@刘启轩在GitHub上的回答的东西。

代码语言:javascript
复制
//Importing your data 
const data = import.meta.glob('../locales/*.json')

//Ref helps with promises I think. I'm sure there are more elegant ways.
const imp = ref([{}])

// From https://github.com/vitejs/vite/issues/77
// by LiuQixuan commented on Jun 20

for (const path in data) {
    data[path]().then((mod) => { 
        imp.value.push(mod)
    })
}

在那里,我遍历了imp.values,然后我可以在一个循环中调用每个文件,用以下方法获取数据:

代码语言:javascript
复制
JSON.parse(JSON.stringify(**Your data**))

我的示例Vue HTML是这样的:

代码语言:javascript
复制
    <div v-for="(module,i) in imp" :key="i">
          <div v-for="(data,j) in module" :key="j">

            //at this point you can read it fully with {{ data }}

            <div v-for="(jsonText, k) in JSON.parse(JSON.stringify(data))" :key=k">
              {{ jsonText.text }}
              <div v-for="insideJson in jsonText" :key="insideJson">
                {{ insideJson.yourtext }}
              </div>
            </div>
          </div>
     </div>

这样,我就可以访问文件中的每个对象。我认为您还有其他需要,但这证明您可以在没有独立导入的情况下访问每个文件。

我知道这有点难。我使用Stringify解析,因为数据总是以“从不”的形式返回,因此无法直接访问。我相信有一个更优雅的解决方案,但这就是我想出来的。

我最初试图动态导入图像,在计算出之后,我将该方法应用于您的问题。

对于任何想要从文件夹中动态导入多映像的人,请使用:

代码语言:javascript
复制
new URL(*, import.meta.url)

和以前一样,但是加上了:

代码语言:javascript
复制
    for (const path in modules) {
      modules[path]().then(() => {
        //*************
        const imgURL = new URL(path, import.meta.url)
        //*************
        gallery.value.push(imgURL)
      })
    }
    //Then reference that gallery.value in your :src
票数 3
EN

Stack Overflow用户

发布于 2022-04-06 09:26:27

基于@Lucas Dawson的回答

对于那些必须在vite和webpack上运行代码的人来说

plugins/i18n.js

代码语言:javascript
复制
import Vue from 'vue';
import VueI18n from 'vue-i18n';

Vue.use(VueI18n);

/***
make sure your public config has `VITE_` prefix or it can't be seen in the client side
https://vitejs.dev/guide/env-and-mode.html#env-files
***/
let messages = Object,
    locales = process.env.VITE_AVAILABLE_LOCALES.split(',');

// check is using vite or webpack
if (typeof __webpack_require__ !== 'function') {
    // for vite

    /***
    glob and globEager are both work for this
    https://vitejs.dev/guide/features.html#glob-import

    the differences is
    `glob` will return a dynamic import function (lazy load)
    `globEager` will return the data of the file from the path directly

    if you use `glob`, don't forget `JSON.parse(JSON.stringify(**Your data**))`
    if you have trouble with this, use `globEager` may save your day
    ***/

    let modules = import.meta.globEager('/lang/*.json');
    locales.forEach(locale => {
        messages[locale] = modules[`/lang/${locale}.json`];
    });
}
else {
    // for webpack (storybook)
    locales.forEach(locale => {
        messages[locale] = require(`~/lang/${locale}.json`);
    });
}

export default ({ app, store }) => {
    app.i18n = new VueI18n({
        locale: store.getters['locale/locale'],
        messages
    });
}

再次感谢@Lucas Dawson的回答!

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67822238

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档