Skip to content

Run node module in browser

I’m trying to upload and read excel file using this node module: read-excel-file and according to the instructions under Browser I need to put this code in my .js file:

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.

But the browser doesn’t know what is import readXlsxFile from 'read-excel-file'. It should be noted that I’m using http-server to see my project at http://localhost:8080/



TL;DR: You have to actually compile your JS code into browser-usable code. Use webpack or other bundling tools to do so.

Long story: The browser does not understand import (because for example: where is the resource?). You can use tools like webpack to create bundles of JavaScript code that detect on compile time that import XX from YY means that they have to look in de node_modules or bower_modules folder for that module and include it in the final bundle

PS: Be aware that not all npm modules are able to run in the browser since thy are node modules or vice versa (they provide different APIs).

3 People found this is helpful