简体   繁体   中英

How can a page call a function from a javascript file that uses Require()?

Newbie coder here. By cobbling together tutorials, I created a .js module that uses Google's API to return the value of a cell in my Google Sheet.

The module, sheetsReader.js includes these two require lines at the top:

const {google} = require('googleapis');
let privatekey = require('../../config/privatekey.json');

And it defines a function, getCell() , that returns the value of whatever cell is passed to it as the argument—eg getCell('A6')

It works perfectly when I run it in node terminal. But I want to access this function in my index.html , so I can display a cell value on the page. (I'm aware there may be better ways to accomplish this, but I'm trying to plug this spreadsheet data into an existing page.)

To export the function, in sheetsReader.js , I have:

module.exports.getCell = getCell;

And to import in index.html I put in the header:

<script> 
import * as getCell from './js/sheetsReader.js' 
</script>

However, when I open the page, it fails to load properly because:

Uncaught ReferenceError: require is not defined at sheetsReader.js:1

I know now that require() does not work browser-side. I've tried to solve by using browserify, requirejs, and all sorts of other fixes, but none seem to work for an html page.

I feel like I'm probably missing something very fundamental here—so I apologize! I learned to set up a server just so I could use the Google API to read a spreadsheet... but no matter how I try I just can't seem to find a way to call the function I built!

您错误地导入了 google api 值,您需要将其格式化为

       const google = require('googleapis.js');

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