【问题标题】:Run node module in browser在浏览器中运行节点模块
【发布时间】:2021-06-13 19:41:50
【问题描述】:

我正在尝试使用此节点模块上传和读取 excel 文件:read-excel-file 并根据 Browser 下的说明,我需要将此代码放入我的 .js 文件中:

import readXlsxFile from 'read-excel-file'

const input = document.getElementById('input')

input.addEventListener('change', () => {
  readXlsxFile(input.files[0]).then((rows) => {
    // `rows` is an array of rows
    // each row being an array of cells.
  })
})

但是浏览器不知道import readXlsxFile from 'read-excel-file' 是什么。需要注意的是我使用http-serverhttp://localhost:8080/查看我的项目

【问题讨论】:

    标签: javascript node.js npm node-modules httpserver


    【解决方案1】:

    TL;DR:您必须将 JS 代码实际编译成浏览器可用的代码。使用webpackother bundling tools 这样做。

    长话短说:浏览器不理解import(因为例如:资源在哪里?)。您可以使用 webpack 之类的工具创建 JavaScript 代码包,在编译时检测从 YY 导入 XX 意味着他们必须在 de node_modules 或 bower_modules 文件夹中查找该模块并将其包含在最终包中

    PS:请注意,并非所有 npm 模块都能够在浏览器中运行,因为它们是节点模块,反之亦然(它们提供不同的 API)。

    【讨论】:

    • 浏览器现在确实有native support for modules,但不支持为 Node.js 设计的模块(带有 Node.js 的模块解析系统)。
    【解决方案2】:

    一个不同的库可能是答案。浏览器中的作品之一是sheetjs

    这里有一个工作演示:https://sheetjs.com/demos/modify.html

    【讨论】:

      猜你喜欢
      • 2015-07-30
      • 2016-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-26
      • 1970-01-01
      • 1970-01-01
      • 2014-04-23
      相关资源
      最近更新 更多