Skip to main content

使用 SWC 打包表

SWC[^1] 是一个 JS 工具链。SWC 提供 spack(正式称为 "swcpack")用于打包脚本。

¥SWC[^1] is a JS toolchain. SWC provides spack (formally called "swcpack") for bundling scripts.

SheetJS 是一个用于从电子表格读取和写入数据的 JavaScript 库。

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

本演示使用 spack 和 SheetJS 导出数据。我们将探讨如何使用 spack 在站点中打包 SheetJS 以及如何将数据导出到电子表格。

¥This demo uses spack and SheetJS to export data. We'll explore how to bundle SheetJS in a site using spack and how to export data to spreadsheets.

该演示重点介绍与 spack 打包程序的集成细节。

¥This demo focuses on integration details with the spack bundler.

这些演示遵循 "导出教程",其中更详细地介绍了 SheetJS 库的用法。

¥The demos follow the "Export Tutorial", which covers SheetJS library usage in more detail.

测试部署

本 demo 在以下环境下进行了测试:

¥This demo was tested in the following environments:

版本日期
1.2.2462024-04-27

集成详情

¥Integration Details

"构架" 章节 涵盖了 Yarn 和其他包管理器的安装。

¥The "Frameworks" section covers installation with Yarn and other package managers.

在 SWC spack 项目中安装 SheetJS 模块后,import 语句可以加载库的相关部分。

¥After installing the SheetJS module in a SWC spack project, import statements can load relevant parts of the library.

导入数据的项目将使用 read[^2] 等方法解析工作簿,使用 sheet_to_json[^3] 从文件生成可用数据。由于 sheet_to_jsonutils 对象的一部分,因此所需的导入为:

¥Projects that import data will use methods such as read[^2] to parse workbooks and sheet_to_json[^3] to generate usable data from files. As sheet_to_json is part of the utils object, the required import is:

import { read, utils } from 'xlsx';

导出数据的项目会使用 json_to_sheet[^4] 等方法生成工作表,使用 writeFile[^5] 导出文件。由于 json_to_sheetutils 对象的一部分,因此所需的导入为:

¥Projects that export data will use methods such as json_to_sheet[^4] to generate worksheets and writeFile[^5] to export files. As json_to_sheet is part of the utils object, the required import is:

import { utils, writeFile } from 'xlsx';

当这个演示针对最新版本的 @swc/core 进行测试时,spack 崩溃了:

¥When this demo was tested against recent versions of @swc/core, spack crashed:

thread '<unnamed>' panicked at 'cannot access a scoped thread local variable without calling `set` first',

这是 SWC 中的一个错误

¥This is a bug in SWC

已知此错误会影响版本 1.3.1001.4.17

¥This bug is known to affect versions 1.3.100 and 1.4.17.

在 bug 修复之前,强烈建议使用 @swc/core@1.2.246

¥Until the bug is fixed, it is strongly recommended to use @swc/core@1.2.246.

完整示例

¥Complete Example

  1. 初始化一个新项目:

    ¥Initialize a new project:

mkdir sheetjs-spack
cd sheetjs-spack
npm init -y
  1. 使用包管理器安装依赖:

    ¥Install the dependencies using a package manager:

yarn add https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz regenerator-runtime @swc/cli @swc/core@1.2.246

regenerator-runtime 依赖用于转译 fetch,如果接口代码不使用 fetch 或 Promises,则不需要。

¥The regenerator-runtime dependency is used for transpiling fetch and is not required if the interface code does not use fetch or Promises.

  1. 将以下内容保存到 index.js

    ¥Save the following to index.js:

index.js
import { utils, version, writeFileXLSX } from 'xlsx';

document.getElementById("xport").addEventListener("click", async() => {
/* fetch JSON data and parse */
const url = "https://xlsx.nodejs.cn/executive.json";
const raw_data = await (await fetch(url)).json();

/* filter for the Presidents */
const prez = raw_data.filter(row => row.terms.some(term => term.type === "prez"));

/* sort by first presidential term */
prez.forEach(row => row.start = row.terms.find(term => term.type === "prez").start);
prez.sort((l,r) => l.start.localeCompare(r.start));

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

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

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

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

/* create an XLSX file and try to save to Presidents.xlsx */
writeFileXLSX(workbook, "Presidents.xlsx");
});
  1. 创建 spack.config.js 配置文件:

    ¥Create an spack.config.js config file:

spack.config.js
module.exports = ({
entry: {
'web': __dirname + '/index.js',
},
output: {
path: __dirname + '/lib'
},
module: {},
});
  1. 为生产而构建:

    ¥Build for production:

npx spack

该命令将创建脚本 lib/web.js

¥This command will create the script lib/web.js

  1. 创建一个小的 HTML 页面来加载生成的脚本:

    ¥Create a small HTML page that loads the generated script:

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="lib/web.js"></script>
</body>
</html>
  1. 启动本地 HTTP 服务器,然后转到 http://localhost:8080/

    ¥Start a local HTTP server, then go to http://localhost:8080/

npx http-server .

点击 "点击此处导出" 生成文件。

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

[^1]: 有关更多详细信息,请参阅 SWC 文档中的 "打包配置"

¥See "Bundling Configuration" in the SWC documentation for more details.

[^2]: 见 read 于 "读取文件"

¥See read in "Reading Files"

[^3]: 见 sheet_to_json 于 "实用工具"

¥See sheet_to_json in "Utilities"

[^4]: 见 json_to_sheet 于 "实用工具"

¥See json_to_sheet in "Utilities"

[^5]: 见 writeFile 于 "写入文件"

¥See writeFile in "Writing Files"