2
votes

I user FilesaverJS for save JSON file on the client side.

I've an error when i load Filesaver JS with RequireJS:

Uncaught Error: Mismatched anonymous define() module: function () {
    return saveAs;
}

My requirejs optimizer config file :

require.config({
    paths: {
        ...
        blobjs                 : "../../libs/blobjs/Blob",
        ....
        filesaver              : "../../libs/filesaver/FileSaver",
    },
    shim : {
        ...
        blobjs: {
             exports: "Blob"
        },
        filesaver: {
             exports: "Filesaver"
        },
        ...
   },

   optimize: 'uglify2',
   uglify2: {
      output: { beautify: true },
      beautify: { semicolons: false }
   },
   baseUrl                 : '../assets/js/',
   mainConfigFile          : '../assets/js/config.js',
   name                    : 'formbuilder',
   out                     : 'formbuilder.min.js',
   output : { beautify: true },
   preserveLicenseComments : false,

   include : ['here i include some views template']
});

And in my code :

var blob = new Blob([jsonContent], {
     type: "application/json;charset=utf-8"
});

saveAs(blob, collectionAndFilename['filename'] + '.json');

Thanks for your help

3

3 Answers

1
votes

I had the same problem. after an investigation I realized that I was loading the FileSaver file in a script tag, and since inside the FileSaver the define() function is called - this was a problem.

This is what states in the reauire.js docs:

Be sure to load all scripts that call define() via the RequireJS API. Do not manually code script tags in HTML to load scripts that have define() calls in them.

I loaded the file with the requireJS API and everything works just fine...

0
votes

this worked for me :

requirejs(["lib/FileSaver"], function(){
    console.log("in FileSAver");

    var text = createString();
    var fileName = getFileName();

    var blob = new Blob([text], {type: "text/plain;charset=utf-8"});
    window.saveAs(blob, fileName);

});
0
votes

Since FileSaver.js is using named AMD module, you have to use it as package in require.config file, juts like moment library.

require.config({
    packages: [{
      name: 'moment',
      location: './js/resources/',
      main: 'moment'
    }, {
      name: 'FileSaver.js',
      location: './js/resources/',// path where you have placed FileSaver.js file
      main: 'FileSaver.js'
    }]
  });

and then just require package FileSaver.js

  requirejs(["FileSaver.js"], function(FileSaver) {
    //FileSaver is now available as function
    console.log(FileSaver);
  });