【问题标题】:r.js not compiling shimmed scripts properlyr.js 没有正确编译填充脚本
【发布时间】:2013-05-23 21:32:05
【问题描述】:

我能够通过 Grunt 的 requirejs 任务成功编译我的 JS 模块,但是我在使用任何 shim 脚本时都无法定义。这是我的配置

requirejs.config({
    "baseUrl": "../../../components/",
    "paths": {
        "less": "less.js/dist/less-1.3.3",
        "datepicker": "jquery-ui/ui/jquery.ui.datepicker",
        "jquery": "jquery/jquery",
        "jqueryui": "jquery-ui/ui/jquery-ui",
        "spectrum": "spectrum/spectrum",
        "class": "class/class",
        "underscore": "underscore-amd/underscore",
        "d3": "d3/d3",
        "nv": "nvd3/nv.d3",
        "dataTables": "datatables/dataTables"

    },
    shim: {
        less: {
            exports: "less"
        },
        jqueryui: {
            exports: "jqueryui"
        },
        spectrum: {
            exports: "spectrum"
        },
        class:{
            deps: [ 'jquery'],
            exports: "class"
        }
    }   
})

这是我的 Gruntfile 中的 requirejs 配置:

requirejs: {
    dist: {
        options: {
            mainConfigFile: 'src/scripts/main.js',
            out: '<%= yeoman.dist %>/scripts/main.js',
            paths:{
                "main" : "../final/src/scripts/main"
            },
            include:['main'],
            preserveLicenseComments: false,
            useStrict: true,
            wrap: true
        }
    }
}

现在,当我运行 grunt requirejs:dist 时,它编译得很好,并且确实包含了我的填充文件。但是每当我尝试运行编译后的 JS 时,对我的任何已填充脚本的访问都是未定义的。

【问题讨论】:

    标签: javascript requirejs gruntjs r.js


    【解决方案1】:

    不确定您所说的“未定义对我的任何已填充脚本的访问”是什么意思。您需要确保以正确的顺序包含已填充的脚本。您也可以尝试为该脚本定义假模块。在你构建 JS 配置中添加:

    onBuildRead: function (moduleName, path, contents) {
        if (moduleNam === 'spectrum'){
            contents += '; define(' + moduleName + ', function(){ return window.spectrum; });';
        }
        return contents;
    }
    

    您需要了解 export 的作用。加载脚本后,它将在全局命名空间中查找该变量。我认为没有“jqueryui”命名空间。所以它总是未定义的,因为它必须在 jQuery 之后加载,它只是扩展 jQuery,所以模块不能返回任何有用的东西。

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-20
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-18
      • 1970-01-01
      相关资源
      最近更新 更多