简体   繁体   中英

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 broswer usable code. Use bower, 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 bower or 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 vise versa (they provide different API's).

There are two problems here:

  • read-excel-file package does not support the client, so you could not run it the browser. It only works only on nodejs(server)

  • Suppose it has supported in the client(browser) you can use JavaScript modules via script tag for modern browsers or use CDN link via unpkg .

A different library might be the answer. One the works in the browser is sheetjs .

Theres a working demo here: https://sheetjs.com/demos/modify.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM