0

In my node.js (express.js) project, I try to wrap axios to create a HttpClient like this:

import axios from 'axios';

const httpClient = axios.create({ baseURL: 'http://locahost:3003' });

...

export const httpClient = {
       ...
  };

When I run it, I get error SyntaxError: Cannot use import statement outside a module which complains the line import axios from 'axios'. How can I get rid of this error? (I come from React-native world, I used the same thing in React-Native, it is fine)

user842225
  • 5,445
  • 15
  • 69
  • 119
  • How did you use this module? More information needed. And one thing. You can not define `httpClient` constant and after do `export const httpClient = .....` – CyberEternal Jun 02 '21 at 08:36
  • 1
    I found the answer I am looking for: https://stackoverflow.com/questions/38296667/getting-unexpected-token-export – user842225 Jun 02 '21 at 18:43

1 Answers1

1

The issue is by default express uses CJS format of importing as you might have seen const axios = require("axios").

What you are trying to do is an ESM format of import which is not understood by the JS as natively. To work import statements you can either add the following property to your package.json file - "type": "module" or you can use ".mjs" extension instead of default ".js" extension.

Hope this link helps further.

Karan Gaur
  • 809
  • 7
  • 20
  • Thanks but I wonder Is there anyway resolve the issue by modifying my code? I mean I am looking for a suggestion to just modify my current code to eliminate the error instead of either changing extension or adding the `"type":"module"` – user842225 Jun 02 '21 at 18:04
  • There is no other method of doing it that I know of – Karan Gaur Jun 02 '21 at 20:14