简体   繁体   English

如何在 javascript 文件中使用 require

[英]how to use require in javascript files

in my app.js that is located in the root folder, I mean Mywebsite/app.js i can access require variable在位于根文件夹中的 app.js 中,我的意思是Mywebsite/app.js我可以访问 require 变量

const express = require("express");
const admin = require("firebase-admin");

but in all other folders like public or static or views folders, I can not use require and also I can't import any library like this one但在所有其他文件夹中,如publicstaticviews文件夹,我不能使用 require 也不能导入任何像这样的库

import admin from "firebase-admin"

and im getting this error for import我收到此错误以进行导入

SyntaxError: Unexpected identifier 'admin'. SyntaxError:意外的标识符“管理员”。 import call expects exactly one argument. import call 只需要一个参数。

or this for require或者这个要求

ReferenceError: Can't find variable: require ReferenceError:找不到变量:需要

I'm new to web development especially when it comes to using an express app now all my problem is with require or importing a library in javascript files, is there any other ways to include or call models in nodejs rather than require我是 web 开发的新手,尤其是在使用 express 应用程序时,现在我的所有问题都在于 require 或在 javascript 文件中导入库,有没有其他方法可以在 nodejs 中包含或调用模型而不是 require

here is my dependencies这是我的依赖项

"dependencies": {
    "body-parser": "^1.19.0",
    "cookie-parser": "^1.4.5",
    "csurf": "^1.11.0",
    "ejs": "^3.1.6",
    "express": "^4.17.1",
    "firebase": "^8.6.3",
    "firebase-admin": "^9.9.0",
    "firebase-functions": "^3.14.1",
    "nodemon": "^2.0.7",
    "popups": "^1.1.3",
    "requirejs": "^2.3.6"
  },

have you tried using const { admin } = require("firebase-admin");您是否尝试过使用const { admin } = require("firebase-admin"); ? ?

const { admin } = require("firebase-admin"); should solve your issue but if it doesn't应该可以解决您的问题,但如果没有

Do check the following请检查以下内容

  • Node Version节点版本
  • Add a key to package.josn , "main": "app.js"package.josn添加密钥, "main": "app.js"
  • run npm i运行npm i
  • run node app.js in the root folder在根文件夹中运行node app.js

import admin from "firebase-admin" won't work as you're not using ES6. import admin from "firebase-admin"将不起作用,因为您没有使用 ES6。

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

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