使用带有动态的 webpack 需要加载子模块

using webpack with dynamic requires to load sub-modules

根据 webpack documentation and the date-fns module structure,我尝试动态加载 date-fns 的语言环境模块。

没有 webpack,语言环境模块使用 var fr = require('date-fns/locale/fr')

加载

使用 webpack,我试了一下没有成功:

var locale = 'fr';
var date = new Date();
var format = 'dddd DD MMMM YYYY';
var req = require.context('date-fns/locale', true, /^\.\//);
return df.format(date, format, { locale: req('./' + locale) });

结果是: "Error: Cannot find module './fr'."

谁能帮帮我?

正确的形式是:

...
var req = require.context('date-fns/locale', true, /\.js$/);
return df.format(date, format, { locale: req('./'+locale+'/index.js') });

...或者只是

require('date-fns/locale/'+locale+'/index.js');