2

I have installed axios via npm and try to import axios to my front end script file.

The error which i am facing is

Uncaught SyntaxError: Cannot use import statement outside a module

This is my app.js file

import axios from 'axios';

function updateRecipt(items) {
    axios.post('/update-reciept',items).then(res=>{
        console.log(res);
    })
}

Note:I also change "type":"tag" to "type":"module" in axios package.json and import statement to const axios = require("../../node_module/axios"). but it doesnot work for me

4 Answers4

3

You are using CommonJS. To import axios you could do

const axios = require("axios");

Instead if you want to use ES Modules, you need to go to package.jsonand add "type": "module", (you could also add "type": "commonjs", to use explicitly CommonJS)

BelMat
  • 93
  • 8
1

You're using the es6 syntax instead of the commonJS. Try using this

const axios = require('axios');

If you want to use es6, you'll need something like Babel

DogEatDog
  • 2,899
  • 2
  • 36
  • 65
0

Try putting that in another file, then do this:

const axios = require('your_file.js');

then go back to your file, and add:

import axios from 'axios';
module.exports = axios
Jake
  • 97
  • 1
  • 9
0

Ive solved this problem by using babel.

create a .babelrc file with

{
  "presets": ["@babel/preset-env"]
}

add this to devDependancies in package.json

 "@babel/core": "^7.22.10",
 "@babel/preset-env": "^7.22.10",

add this to jest.config.cjs

module.exports = {
    transform: {
        "^.+\\.jsx?$": "babel-jest"
    }
};