简体   繁体   English

使用 next.js 的参数化动态导入

[英]Parametrized dynamic imports with next.js

I'm trying to integrate formatters generated with globalize npm package into next.js based application.我正在尝试将使用 globalize npm package 生成的格式化程序集成到基于 next.js 的应用程序中。 Formatters are stored in locale specific files.格式化程序存储在特定于语言环境的文件中。 Idea is to import locale specific formatters dynamically based on current locale.想法是根据当前语言环境动态导入特定于语言环境的格式化程序。 Current locale information is available via next-i18next integration in getInitialProps method of the page but since formatters contain functions importing formatters in getInitialProps and passing them along with initial props doesn't work.当前的语言环境信息可通过页面的 getInitialProps 方法中的 next-i18next 集成获得,但由于格式化程序包含在 getInitialProps 中导入格式化程序并将它们与初始道具一起传递的函数不起作用。

What would be any potential workaround to achieve desired behaviour?实现所需行为的任何潜在解决方法是什么?

I ended up using HOC with dynamic imports:我最终将 HOC 与动态导入一起使用:

const formatters = {};
LOCALES.forEach((locale) => {
  formatters[locale] = dynamic(() => {
    return import(`../../public/static/globalize/locales/${locale}/formatters-${locale}.js`);
  });
});

export default function withFormatter(Page) {
  const PageWithFormatter = (props) => {
    const lang = i18n.language || props.currentLanguage || 'en';

    const formatter = formatters[lang]('').type(lang);

    return (
      <GlobalizeContext.Provider value={{ formatter }}>
        <Page {...props} />
      </GlobalizeContext.Provider>
    );
  };

  PageWithFormatter.getInitialProps = async ({ req }) => {
    const currentLanguage = req ? req.language : '';

    return { currentLanguage };
  };

  return PageWithFormatter;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM