0

I've tried different ways to search for this and I am coming up with nothing. When setting up an express app and importing a file of routes you often see documentation for this statement:

require('./app/routes/posts.routes.js')(app)

Which from the documentation in nodejs.org means to require the file './app/routes/posts.routes.js' and run everything in the app object.

What I have not come across is how to write this statement using "import".

My example:

Route File Contents

module.exports = (app) => {

    import posts from '../controllers/post.controller.js'

    app.post('/posts', posts.create);

    app.get('/posts', posts.findAll);

    app.get('/posts/:postId', posts.findOne);

    app.put('/posts/:postId', posts.update);

    app.delete('/posts/:postId', notes.delete);
}

Import Statement

//this does not work throws Error: Cannot find package 'app' imported from /Users/matt1/socialbulk/server/server.js

import posts from 'app/routes/post.routes.js' //what do you do with (app)?

app.use('/posts', posts) 

app.listen(3000, () => {
    console.log("Server is listening on port 3000");
});

Thank you so much in advance for your help!!!!

mrmonroe
  • 305
  • 1
  • 10
  • Try using `../`,`./` or `/` as first characters of the import path. – Kvothe Aug 06 '20 at 00:16
  • Your "*Route File Contents*" is an invalid mixture of `module.exports` and `import` syntax. What does the file actually look like? – Bergi Aug 06 '20 at 00:18
  • @Bergi the file has been shared and `import` is backward compatible with `module.exports` https://stackoverflow.com/questions/34278474/module-exports-and-es6-import – Maxime Helen Aug 06 '20 at 00:24
  • @MaximeHelen The shared code snippet is just a plain syntax error. And the backward compatibility depends on your module loader, it should not be assumed generally. – Bergi Aug 06 '20 at 00:27
  • @Bergi So it depends on the v8 engine version? Is there a compatibility table somewhere that confirms the flakiness on that side? – Maxime Helen Aug 06 '20 at 00:36
  • @MaximeHelen I said module loader (which often means transpiler/bundler), not js engine. (Notice that only ES6 modules are standardised, the rest is always platform-dependent). If you're talking about node.js specifically, see https://nodejs.org/api/esm.html#esm_interoperability_with_commonjs. – Bergi Aug 06 '20 at 00:46
  • @Bergi Ah I wasn't aware of the synonyms, thanks! – Maxime Helen Aug 06 '20 at 01:02

1 Answers1

0

module.exports = foo is equivalent to export default foo

Here foo is a function

import posts from 'app/routes/post.routes.js' //what do you do with (app)?

app.use('/posts', posts(app)) 

app.listen(3000, () => {
    console.log("Server is listening on port 3000");
});
Maxime Helen
  • 1,218
  • 6
  • 15