简体   繁体   English

Node.js错误:客户端js文件中未定义require

[英]Node.js Error: require is not defined in clientside js file

I have a Javascript file in which I have data that needs to be saved into a Mongoose schema and subsequently inserted into a MongoDB table. 我有一个Javascript文件,其中有一些数据需要保存到Mongoose模式中,然后再插入到MongoDB表中。 The schema is defined in a file in a separate directory so I tried to essentially import it by including the following line at the top of the file: 该架构是在单独目录中的文件中定义的,因此我试图通过在文件顶部包括以下行来实质上导入该架构:

//import schema for sketches
var SketchSchema = require('../schemas/sketch_objs');

I then got the error "Uncaught ReferenceError: require is not defined" which I found out here was due to the fact that require() doesn't exist on the client-side. 然后我收到错误“未捕获的ReferenceError:未定义”, 是由于在客户端不存在require()导致的。 As suggested in the answer for that post, I installed Browserify in order to be able to require the schema javascript file. 如该帖子答案中所建议,我安装了Browserify以便能够要求架构javascript文件。

I couldn't really ascertain the specific usage of Browserify's functionality to achieve this but it seemed from the github readme that something like the following has to be done: 我无法确切确定Browserify功能的具体用法来实现此目的,但是从github自述文件中看来,必须执行以下操作:

$ browserify main.js > bundle.js

where the required files in main.js will be included inside of bundles.js. 其中main.js中所需的文件将包含在bundles.js中。 I tried to doing this for the file that needed to include the schema and successfully generated the new file; 我尝试对需要包含架构的文件执行此操作,并成功生成了新文件; however, for some reason when I run the project, I still get the error about require not being defined. 但是,由于某些原因,当我运行项目时,我仍然收到关于未定义require的错误。 Is it supposed to be that the new file generated by Browserify is supposed to be used instead of the old file? 是否应该使用Browserify生成的新文件代替旧文件? If this isn't the case, what is the correct way to require another js file inside a file on the client side? 如果不是这种情况,在客户端的文件中要求另一个js文件的正确方法是什么?

So 所以

  • you need browserify to require the JS file CommonJs way. 您需要使用browserify来要求JS文件CommonJs方式。
  • I do not think mongoDB is compatible with browserify, FYI, https://jira.mongodb.org/browse/NODE-698 我认为mongoDB与browserify,FYI, https: //jira.mongodb.org/browse/NODE-698不兼容

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

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