It give me error while importing axios from node module

Viewed 1637

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

3 Answers

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)

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

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
Related