简体   繁体   中英

How to include jszip with requirejs : jszip is not defined

I am using the js-xlsx library to create an Excel file in JavaScript.

This library use jszip . I tried to define the jszip library in my JavaScript file before loading jszip but jszip is never defined:

Uncaught TypeError: jszip is not a function

Config requirejs:

<script type="text/javascript">
  requirejs.config({
    paths : {
      jszip : '../tools/jszip'
    }
  });
</script>

Here is how I use it in my JS file:

define(['jszip', '../tools/xlsx'], function(jszip, xlsx) {
  ...
}

JSZip (and ODS to support ods extension) must be loaded and attached to the window before XLSX is loaded. I'm getting it working using shim with a custom "xlsx-loader":

main.js

requirejs.config({
    paths: {
        ods: '...path to ods',
        jszip: '...path to jszip',
        xlsxloader: '...path to xlsx-loader',
        xlsx: '...path to xlsx'
    },
    shim: {
        xlsx: {
            exports: 'XLSX',
            deps: ['xlsxloader']
        }
    }
});

xlsx-loader.js

define(['jszip', 'ods'], function (jszip, ods) {
    "use strict";

    window.JSZip = jszip;
    window.ODS = ods;
});

your JS file

define(['xlsx'], function () {
    // Do what you want with XLSX
    ...

Option 2) You can also achieve this chaining requires, it doesn't need any shim but doesn't work with optimizer

require(['jszip', 'ods'], function (jszip, ods) {
    window.JSZip = jszip;
    window.ODS = ods;
    require(['xlsx'], function () {
        // Do what you want with XLSX
        ...
    });
});

if you open xlsx.js, you would see there is a global variable named JSZip is used and that actually populates value of jszip. So if you change your function definition like this

define(['jszip', '../tools/xlsx'], function(JSZip , xlsx) { 

it should work , I think

Your must define the lib var as the constructor's name.

For my case i had the same issue:

define("Statistics", ["jquery", "underscore", "Datatable", "moment", "jszip"], function($, _, Datatable, moment, jszip) {

and i changed jszip to JSZip like this:

define("Statistics", ["jquery", "underscore", "Datatable", "moment", "jszip"], function($, _, Datatable, moment, JSZip) {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM