问题描述
我在国际网站的几个不同页面上使用。每个页面都使用require.js在Moment中要求。
I'm using Moment.js on a few different pages in an international site. Each page uses require.js to require in Moment.
Moment允许你以该区域设置格式显示日期。但是,此代码必须在每个页面上运行Moment加载(因为我从不确定用户首先加载哪个页面)。
Moment allows you to set the locale to display dates in that locales format. However, this code has to be run on every page Moment is loaded (since I'm never sure which page the user loads first).
var Moment = require('moment');
// configure locale
我想要做的是移动代码来配置语言环境类似于预先需要的步骤,这样我就不必记住在每个页面上配置语言环境(并且它变得更加干燥)。所以我所要做的就是
What I want to do is move the code to configure the locale to something like a pre-require step so that I don't have to remember to configure the locale on every page (and it becomes more DRY). So all I would have to do is
var Moment = require('moment');
并且预先要求步骤已经配置了区域设置。
and the pre-require step would already have configured the locale.
这可能吗?
推荐答案
是的,有可能,像这样:
Yes, it is possible, like this:
-
创建一个名为
时刻配置的模块
:
define(['moment'], function (moment) {
// Call what you need to call to configure moment...
return moment;
});
使用地图
配置每个加载时刻的人都会加载你的时刻配置的
模块,而时刻配置
加载真正的时刻
:
Use a map
configuration so that everybody who loads moment really loads your moment-configured
module whereas moment-configured
loads the real moment
:
map: {
'*': {
moment: 'moment-configured'
},
'moment-configured': {
moment: 'moment'
}
}
此方法改编自,关于如何使用 noConflict
自动加载jQuery。使用此映射配置,所有需要时刻
的模块将获得时刻配置
,但除外时刻配置的
,它将获得真正的时刻
。
This method is adapted from the example in RequireJS' documentation about how to have jQuery be automatically loaded with noConflict
. With this map configuration, all modules that require moment
will get moment-configured
, except for moment-configured
which will get the real moment
.
这篇关于在需要模块之前,使用require.js运行公共代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!