首页 > 解决方案 > 在浏览器中运行节点模块

问题描述

我正在尝试使用此节点模块上传和读取 excel 文件:read-excel-file并根据浏览器下的说明,我需要将此代码放入我的 .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-server用来查看我的项目http://localhost:8080/

标签: javascriptnode.jsnpmnode-moduleshttpserver

解决方案


TL;DR:您必须将 JS 代码实际编译成浏览器可用的代码。使用webpack其他捆绑工具来执行此操作。

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

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


推荐阅读