【问题标题】:Downloading Script Dependencies in Parallel RequireJS在 Parallel RequireJS 中下载脚本依赖
【发布时间】:2014-05-21 00:22:20
【问题描述】:

this RequireJS example 之后,我试图为所有供应商js 资产(如jquery 和foundation)创建一个文件,同时在其他模块中加载页面特定代码。

虽然我可以成功构建和复制 js(使用 grunt requirejs 优化器)到 build 文件夹中,但 require.config 中的 baseUrl 现在显然是错误的。

baseUrl: 'js' 指向public/js 而不是public/build/js,因此所有路径都不正确。

有没有办法在运行优化器时动态更新baseUrl?所以它指向public/build/js

这是我的繁重任务:

requirejs: {
    dist: {
        options: {
            baseUrl: '<%=pkg.paths.js%>',
            dir:'project/public/build/js',
            mainConfigFile: '<%=pkg.paths.js%>main.js',
            optimize: 'none',
            removeCombined: true,
            uglify2: {
                no_mangle: true,
                compress: {
                    drop_console: true
                }
            },
            modules: [
                {
                    name: 'vendorCommon'
                },
                {
                    name: 'dashboard',
                    exclude: ['vendorCommon']
                }
            ]
        }
    }
}

供应商通用

define(['jquery', 'foundation'],
function () {
    //Just an empty function, this is a place holder
    //module that will be optimized to include the
    //common depenendencies listed in this module's dependency array.
});

需要配置

require.config({

    baseUrl: '/js',

    priority: ['vendorCommon'],

    paths: {
        'vendorCommon':'vendor/vendor-common',
        'jquery':'../bower_components/jquery/dist/jquery.min',
        'foundation':'../bower_components/foundation/js/foundation/foundation',
        'dashboard':'views/dashboard'
    },

    shim: {
        'foundation': ['jquery']
    }

});

【问题讨论】:

    标签: javascript requirejs


    【解决方案1】:

    我使用优化器的onBuildWrite 设置在优化某些模块时对其进行了修改。如果您的配置包含在您的优化包中,那么您可以使用onBuildWrite 对其进行修补:

    onBuildWrite: function (moduleName, path, contents) {
        if (moduleName === '<%=pkg.paths.js%>main') {
            return contents.replace("baseUrl: '/js'", "baseUrl: '/build/js'");
        }
        return contents;
    }
    

    免责声明:我是在脑海中写下这个。谨防错别字。

    另一种可能性是在运行时覆盖baseUrl。 RequireJS 能够将多个配置组合成一个配置。稍后调用中的新值 baseUrl 将覆盖先前的值。因此,如果您有办法设置应用程序的优化版本(例如,通过服务器提供的不同 HTML)调用 require.config({baseUrl: '/build/js'}); 您在问题中显示的调用但 任何需要正确baseUrl的代码之前,这也是一个选项。

    【讨论】:

    • 我考虑过为生产创建一个单独的配置,但对我来说,您的 onBuildWrite 是一个更好的解决方案。谢谢!
    猜你喜欢
    • 2013-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-16
    • 2012-12-19
    • 1970-01-01
    • 2015-03-11
    相关资源
    最近更新 更多