docs.sheetjs.com/docz/docs/03-demos/01-frontend/19-bundler/11-requirejs.md
2023-10-19 14:45:29 -04:00

5.7 KiB

title sidebar_label pagination_prev pagination_next sidebar_position
Bundling Sheets with RequireJS RequireJS demos/index demos/grid/index 11

import current from '/version.js'; import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; import CodeBlock from '@theme/CodeBlock';

RequireJS is a JavaScript file and module loader. It includes an in-browser loader as well as a static optimizer.

SheetJS is a JavaScript library for reading and writing data from spreadsheets.

This demo uses RequireJS and SheetJS to export data. We'll explore how to load SheetJS in a site using RequireJS and how to use the r.js optimizer to create a bundled site.

The Live demo loads RequireJS from the CDN, uses it to load the standalone script from the SheetJS CDN, and uses the XLSX variable to create a button click handler that creates a workbook.

:::note

This demo was last tested on 2023 October 18 against RequireJS 2.3.6

:::

Integration Details

The SheetJS Standalone scripts comply with AMD define semantics. They support RequireJS and the r.js optimizer out of the box.

Config

The RequireJS config should set the xlsx alias in the paths property.

SheetJS CDN

The SheetJS CDN URL can be directly referenced in a path alias:

{\ require.config({ baseUrl: ".", name: "app", paths: { // highlight-next-line xlsx: "https://cdn.sheetjs.com/xlsx-${current}/package/dist/xlsx.full.min" } });}

Vendoring

After downloading the SheetJS standalone script, a relative path can be used in the path alias. For example, if the standalone script was downloaded in the same directory as the HTML page, the path should be ./xlsx.full.min:

require.config({
  baseUrl: ".",
  name: "app",
  paths: {
    // highlight-next-line
    xlsx: "./xlsx.full.min"
  }
});

Usage

Once the alias is set, "xlsx" can be required from app scripts:

// highlight-next-line
require(["xlsx"], function(XLSX) {
  /* use XLSX here */
  console.log(XLSX.version);
});

Within the callback, the XLSX variable exposes the functions listed in the "API Reference" section of the documentation.

Complete Example

This demo will explore the standalone RequireJS script and the r.js optimizer.

Standalone RequireJS

  1. Download the SheetJS Standalone script and move to the project directory:
  • xlsx.full.min.js

{\ curl -LO https://cdn.sheetjs.com/xlsx-${current}/package/dist/xlsx.full.min.js}

  1. Save the following to index.html:
<!DOCTYPE html>
<html lang="en">
  <head></head>
  <body>
    <h1>SheetJS Presidents Demo</h1>
    <button id="xport">Click here to export</button>
    <script src="http://requirejs.org/docs/release/2.3.6/comments/require.js"></script>
    <script>
/* Wire up RequireJS */
require.config({
  baseUrl: ".",
  name: "SheetJSRequire",
  paths: {
    xlsx: "./xlsx.full.min"
  }
});
    </script>
    <script src="SheetJSRequire.js"></script>
  </body>
</html>
  1. Save the following to SheetJSRequire.js:
require(["xlsx"], function(XLSX) {
  document.getElementById("xport").addEventListener("click", function() {
    /* fetch JSON data and parse */
    var url = "https://sheetjs.com/data/executive.json";
    fetch(url).then(function(res) { return res.json(); }).then(function(raw_data) {

    /* filter for the Presidents */
    var prez = raw_data.filter(function(row) { return row.terms.some(function(term) { return term.type === "prez"; }); });

    /* flatten objects */
    var rows = prez.map(function(row) { return {
      name: row.name.first + " " + row.name.last,
      birthday: row.bio.birthday
    }; });

    /* generate worksheet and workbook */
    var worksheet = XLSX.utils.json_to_sheet(rows);
    var workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, "Dates");

    /* fix headers */
    XLSX.utils.sheet_add_aoa(worksheet, [["Name", "Birthday"]], { origin: "A1" });

    /* calculate column width */
    var max_width = rows.reduce(function(w, r) { return Math.max(w, r.name.length); }, 10);
    worksheet["!cols"] = [ { wch: max_width } ];

    /* create an XLSX file and try to save to Presidents.xlsx */
    XLSX.writeFileXLSX(workbook, "Presidents.xlsx");
    });
  });
});

:::info pass

The r.js optimizer does not handle async functions or ES6 arrow functions.

To demonstrate compatibility with older versions of Webpack, SheetJSRequire.js uses normal functions and traditional Promise chains.

:::

  1. Start a local HTTP server, then go to http://localhost:8080/
npx http-server .

Click on "Click here to export" to generate a file.

r.js Optimizer

  1. Create build.js configuration for the optimizer:
({
  baseUrl: ".",
  name: "SheetJSRequire",
  paths: {
    xlsx: "./xlsx.full.min"
  },
  out: "SheetJSRequire.min.js"
});
  1. Run the r.js optimizer to create SheetJSRequire.min.js:
npx -p requirejs@2.3.6 r.js -o build.js
  1. Save the following to optimized.html:
<!DOCTYPE html>
<html lang="en">
  <head></head>
  <body>
    <h1>SheetJS Presidents Demo</h1>
    <button id="xport">Click here to export</button>
    <script src="http://requirejs.org/docs/release/2.3.3/comments/require.js"></script>
    <script src="SheetJSRequire.min.js"></script>
  </body>
</html>
  1. Open http://localhost:8080/optimized.html

Click on "Click here to export" to generate a file.