59

So i have been trying to run this web app and at first it showed

(node:12960) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
C:\Users\J\react-messenger\stream-chat-boilerplate-api\src\index.js:1
import dotenv from 'dotenv'; ^^^^^^

SyntaxError: Cannot use import statement outside a module

And then i went to put set the type: module in the package.json but it gave me this error

ReferenceError: module is not defined

at file:///C:/Users/J/react-messenger/stream-chat-boilerplate-api/src/index.js:38:1

Here is my code:

import dotenv from 'dotenv';
dotenv.config();

import fs from 'fs';
import path from 'path';
import express from 'express';
import bodyParser from 'body-parser';
import cors from 'cors';
import helmet from 'helmet';
import compression from 'compression';

const api = express();

api.use(cors());
api.use(compression());
api.use(helmet());
api.use(bodyParser.urlencoded({ extended: true }));
api.use(bodyParser.json());

api.listen(process.env.PORT, error => {
    if (error) {
        console.warn(error);
        process.exit(1);
    }

    // eslint-disable-next-line array-callback-return
    fs.readdirSync(path.join(__dirname, 'routes')).map(file => {
        require('./routes/' + file)(api);
    });

    console.info(
        `Running on port ${process.env.PORT} in ${
            process.env.NODE_ENV
        } mode. 🚀`
    );
});

module.exports = api;

I dont know what am doing wrong

1
  • As it says: Set "type": "module" in the package.json or use the .mjs extension. Commented Oct 2, 2020 at 0:10

1 Answer 1

103

You are mixing ES imports with CommonJS - at bottom of file you have module.exports = api; which is CJS terminology. The ES module equivalent is:

export default api
Sign up to request clarification or add additional context in comments.

3 Comments

Can I use a require cjs module in .mjs file using an import statement
@Gary yes you can.
This is the straight forward answer I needed!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.