在需要模块之前,使用require.js运行公共代码 [英] Use require.js to run common code before module is required

查看:56
本文介绍了在需要模块之前,使用require.js运行公共代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在国际网站的几个不同页面上使用 Moment.js 。每个页面都使用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:


  1. 创建一个名为时刻配置的模块

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'
        }
    }
    


  • 此方法改编自 RequireJS'文档,关于如何使用 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运行公共代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆