Search code examples
javascriptnode.jspassport.js

ES import passport


Can anyone help me use ES import version of the: require('./config/passport')(passport);. I cant get this to work. I don't think you can use both ES import and require at the same time. I get and error that require is undefined.

import express from 'express';
import bodyParser from 'body-parser';
import mongoose from 'mongoose';
import cors from 'cors';
import dotenv from 'dotenv';
import { createRequire } from 'module';
const URL = createRequire(import.meta.url);
import passport from 'passport'


import postRoutes from './routes/posts.js'
import userRoutes from './routes/user.js'
import loginRoutes from './routes/login.js'

const app = express();
dotenv.config();
require('./config/passport')(passport);

app.use(passport.initialize());
app.use(passport.session());

Solution

  • Yes, we can not use require which is commonjs modules with import which is ES6 modules. Though the solution is really simple. Basically, you have to pass passport as an argument to the function exported from ./config/passport. All you have to do is just import the function as is and pass passport as an argument.

    So here's what you need to do:-


    config/passport.js

    export default = (passport) => {
     /* use passport here */
    }
    

    index.js

    import passport from "passport";
    import passportConfig from "./config/passport";
    
    passportConfig(passport);