我已经构建了一个js库,希望使用grunt将其打包为AMD模块。还有其他连接库文件的任务,因此我将以非AMD模块作为开始。

Gruntfile的外观如下:

module.exports = function(grunt) {
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    concat: {
      all: {
        options: {
          separator: '\n\n',
          stripBanners: true,
          banner: '/*! <%= pkg.name %> - v<%= pkg.version %> - ' +
            '<%= grunt.template.today("yyyy-mm-dd") %> */\n\n'
        },
        files: {
          'dist/<%= pkg.name %>.js': ['src/file1.js', 'src/file2.js'], // this works
          'dist/<%= pkg.name %>.amd.js': ['src/file1.js', 'src/file2.js'] // this is meant to create the AMD version of the library
        }
      }
    }
 });
 grunt.registerTask('default', ['concat']);
};


结果文件(针对目标library.amd.js)旨在包含library.js的内容,包括define(..., ..., ...)require.js部分:

define('library', ['dependency1', 'dependency2'], function(dep1, dep2) {
  // content of library.js here
});


我该怎么做呢?我曾考虑过将header.js(用于define('library...)和footer.js(用于});)添加到AMD目标的构建源中,但是希望有一个更优雅的解决方案。我还查看了grunt模板,但找不到将完整文件包含到模板中的方法。

最佳答案

您可以使用grunt-umd将文件包装在通用模块定义中

正如您所描述的,许多库在构建中合并了一个页眉和页脚文件。一个示例是snap.svg(请参阅amd-banner.jsamd-footer.js及其gruntfile.js

关于javascript - 如何使用grunt创建require.js包,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19885539/

10-10 21:47