javascript - import or require js file in another js file - Stack Overflow

I'm not sure if this has been answered before. I am trying to build a node express API, where I no

I'm not sure if this has been answered before. I am trying to build a node express API, where I now need to include another js file so I can spread up my code.

Basically, I have a server.js file where I want to call a function in a router.js file. Is this possible?

Have tried using import, because i read that ES6 now supports that. Code:

import routers from '/router.js';

Have also tried with the 'required' keyword, but that does not help either. The router.js file is also just placed in the root as the server.js.

Package.json:

 {
    "name": "nodeexpresapi",
    "main": "server.js",
    "dependencies": {
      "body-parser": "~1.0.1",
      "express": "~4.0.0",
      "mongoose": "~3.6.13",
      "nodemon": "^1.9.2",
    },
    "scripts": {
      "start": "nodemon server.js"
    }
 }

I have read that you can import them in the html file, but this is a server with no html, so that is not possible for me.

I'm not sure if this has been answered before. I am trying to build a node express API, where I now need to include another js file so I can spread up my code.

Basically, I have a server.js file where I want to call a function in a router.js file. Is this possible?

Have tried using import, because i read that ES6 now supports that. Code:

import routers from '/router.js';

Have also tried with the 'required' keyword, but that does not help either. The router.js file is also just placed in the root as the server.js.

Package.json:

 {
    "name": "nodeexpresapi",
    "main": "server.js",
    "dependencies": {
      "body-parser": "~1.0.1",
      "express": "~4.0.0",
      "mongoose": "~3.6.13",
      "nodemon": "^1.9.2",
    },
    "scripts": {
      "start": "nodemon server.js"
    }
 }

I have read that you can import them in the html file, but this is a server with no html, so that is not possible for me.

Share Improve this question asked Jun 24, 2016 at 11:27 MikkelMikkel 1,81111 gold badges37 silver badges62 bronze badges 1
  • '/router.js' will search for router.js in the root of the filesystem not root of your server, if the file is in the same directory then you need to use import routers from './router.js'; if it's one directory up in file tree then you to use '../routers.js' – jcubic Commented Jun 24, 2016 at 11:33
Add a ment  | 

1 Answer 1

Reset to default 3

In router.js file , you can try

module.exports = functionYouWantToImport();

and in the server.js you can try

var routerFunction = require('./router.js');

also when you require some local file as a module you should take care the path you are directing

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744399668a4572322.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信