admin管理员组

文章数量:1402274

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

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

Share Improve this question asked Jul 18, 2021 at 16:56 Mohammad Yaseen AfridiMohammad Yaseen Afridi 351 silver badge6 bronze badges 0
Add a ment  | 

4 Answers 4

Reset to default 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": "monjs", to use explicitly CommonJS)

You're using the es6 syntax instead of the monJS. 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

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"
    }
};

本文标签: javascriptIt give me error while importing axios from node moduleStack Overflow