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

使用next.js参数化动态导入,next.js,globalize,next-i18next,Next.js,Globalize,Next I18next,我正在尝试将GlobalizeNPM包生成的格式化程序集成到基于next.js的应用程序中。格式化程序存储在特定于语言环境的文件中。其思想是基于当前区域设置动态导入特定于区域设置的格式化程序。当前区域设置信息可通过页面的getInitialProps方法中的next-i18next集成获得,但由于格式化程序包含在getInitialProps中导入格式化程序并将其与初始道具一起传递的函数,所以无法使用 实现所需行为的潜在解决方法是什么?我最终使用了带有动态导入的HOC: const format

我正在尝试将GlobalizeNPM包生成的格式化程序集成到基于next.js的应用程序中。格式化程序存储在特定于语言环境的文件中。其思想是基于当前区域设置动态导入特定于区域设置的格式化程序。当前区域设置信息可通过页面的getInitialProps方法中的next-i18next集成获得,但由于格式化程序包含在getInitialProps中导入格式化程序并将其与初始道具一起传递的函数,所以无法使用


实现所需行为的潜在解决方法是什么?

我最终使用了带有动态导入的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;
}
const格式化程序={};
LOCALES.forEach((locale)=>{
格式化程序[区域设置]=动态(()=>{
返回导入(`.././public/static/globalize/locales/${locale}/formatters-${locale}.js`);
});
});
使用格式化程序导出默认函数(第页){
const PageWithFormatter=(道具)=>{
const lang=i18n.language | | | props.currentLanguage | | | en |;
常量格式化程序=格式化程序[lang]('')。类型(lang);
返回(
);
};
PageWithFormatter.getInitialProps=async({req})=>{
const currentLanguage=req?req.language:“”;
返回{currentLanguage};
};
返回页面和格式化程序;
}

我最终使用了带有动态导入的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;
}
const格式化程序={};
LOCALES.forEach((locale)=>{
格式化程序[区域设置]=动态(()=>{
返回导入(`.././public/static/globalize/locales/${locale}/formatters-${locale}.js`);
});
});
使用格式化程序导出默认函数(第页){
const PageWithFormatter=(道具)=>{
const lang=i18n.language | | | props.currentLanguage | | | en |;
常量格式化程序=格式化程序[lang]('')。类型(lang);
返回(
);
};
PageWithFormatter.getInitialProps=async({req})=>{
const currentLanguage=req?req.language:“”;
返回{currentLanguage};
};
返回页面和格式化程序;
}