简体   繁体   English

页面如何从使用 Require() 的 javascript 文件调用函数?

[英]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.通过拼凑教程,我创建了一个 .js 模块,该模块使用 Google 的 API 返回 Google 表格中单元格的值。

The module, sheetsReader.js includes these two require lines at the top:模块sheetsReader.js在顶部包含这两条需要的行:

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')并且它定义了一个函数getCell() ,它返回作为参数传递给它的任何单元格的值——例如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.但是我想在我的index.html访问这个函数,所以我可以在页面上显示一个单元格值。 (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:要导出函数,在sheetsReader.js ,我有:

module.exports.getCell = getCell;

And to import in index.html I put in the header:并在index.html导入我放入标题:

<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未捕获的 ReferenceError:在 sheetReader.js:1 中未定义要求

I know now that require() does not work browser-side.我现在知道 require() 在浏览器端不起作用。 I've tried to solve by using browserify, requirejs, and all sorts of other fixes, but none seem to work for an html page.我试图通过使用 browserify、requirejs 和各种其他修复来解决,但似乎没有一个适用于 html 页面。

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 读取电子表格……但无论我如何尝试,我似乎都找不到调用我构建的函数的方法!

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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