Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Gabotronix's avatar

Why can't I use import/export in node.js enviroment?

Hi everybody, I'm working in my first node.js app coming from a vue/laravel background where I alsways used import/exports, now I'm trying to use it in my node.js but I get the following error:

(node:13072) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
C:\xampp\htdocs\myapp\app.js:7
import MapsService from '../services/MapsService';
^^^^^^

SyntaxError: Cannot use import statement outside a module

I thought node.js was pretty common, how can I not use import/exports? This is what I have in my app.js

var express = require('express');
var app = express();
//process.env.DB_HOST
require('dotenv').config()


import MapsService from '../services/MapsService';

app.get('/', async (req, res) => {

    MapsService.scrapeAddress();

    res.send('Hello World!');
});


app.listen(3000, function () {
  console.log('Example app listening on port 3000!');
});

And in my MapsService file I use imports/exports too, does that mean I will have to use this require thing I see? How can I transform my MapsService file to be require friendly?

//import { Client } from '@googlemaps/google-maps-services-js';
import * as geometry from 'spherical-geometry-js';
import axios from "axios";
//const axios = require('axios').default ??;
import VenuesService from '../services/VenuesService';


export class MapsService {

   



}
0 likes
1 reply
ni31593's avatar

Node js uses commonjs module formatting system so you can't use import, export inside nodejs.

still u want to use import, export inside nodejs then you need to use .mjs file extenstion instead of .js

In latest version of node 14.11.X you can use import export you can find more info at https://nodejs.org/api/esm.html

otherwise solution will be as below

in app.js


const MapsService  = require('../services/MapsService');

and MapsService.js


const geometry = require('spherical-geometry-js');
const axios = require('axios');

const VenuesService = require('../services/VenuesService');


class MapsService {

}

module.exports = { MapsService }

Please or to participate in this conversation.