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
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
I'm trying to upgrade to use import instead of requires for modules:
My old code looked like so:
const { NETWORK } = require(`${basePath}/constants/network.js`);
The network.js File:
export const NETWORK = {
eth: "eth",
sol: "sol",
};
module.exports = {
NETWORK,
};
When ever I try to import i've tried a few syntaxes):
import { NETWORK } from '../constants/network.js';
import NETWORK from '../constants/network.js';
import * as NETWORK from '../constants/network.js';
I get an error:
This file is being treated as an ES module because it has a '.js' file extension and '..\package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
at file:///../constants/network.js:6:1
at ModuleJob.run (node:internal/modules/esm/module_job:193:25)
at async Promise.all (index 0)
at async ESMLoader.import (node:internal/modules/esm/loader:526:24)
at async loadESM (node:internal/process/esm_loader:91:5)
at async handleMainPromise (node:internal/modules/run_main:65:12)
When I try to rename the file to be network.cjs I get an error:
SyntaxError: Unexpected token 'export'
how can I import variables from js files using import?
You need to remove the unnecessary "module.exports" part from your network.js, because that is the way to export stuff in commonjs. Your first line of import will work after that import { NETWORK } from '../constants/network.js'; so remove the other ones
I'm using ES6 style and want to be consistent of using import from ES6.
Here is my jest test file I'm setting up:
import Get from './Get'
test('Some test', async () => {
expect(true).toBe(true)
})
And here is my Get file:
import cli from "commander";
import get from "./myHandler.js"
const GET = () => {
// Doing some stuff here...
}
export default GET
I keep getting:
C:\...\GET\get.test.js:2
import Get from './Get';
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1773:14)
And I have already added "type": "module", in my package.json as suggested by this and others. What am I doing wrong here?
I've just been following a tutorial about Axios and I noticed that in it, they import it as axios but when they import React it's as React.
Why are some imports capitalised? is there a technical reason?
is there a technical reason?
Yes and no.
Both of the ones you've listed are the default export of their relevant modules, which means the name you use for them in your code is largely up to you (with a frequent exception in the case of React, more below). (It's different if they're named exports, more below on that as well). I've seen people use Axios instead of axios, for instance.
// Valid:
// ESM
import axios from "axios";
// CommonJS
const axios = require("axios");
// Also valid:
// ESM
import Axios from "axios";
// CommonJS
const Axios = require("axios");
With React, is used to be (and may well still be in some environments) that you needed to call it React if you were using JSX, because JSX is compiled to calls to React.createElement, and if you've used the name react instead, it won't match. (With some modern bundlers and configurations, you don't have to import React at all anymore.)
Named exports have to be imported with the name that they're exported with (so the names are defined by the module author), like this:
// ESM
import { memo } from "react";
// CommonJS
const { memo } = require("react");
although you could rename your local binding if you wanted to with as (perhaps to avoid conflicts with something else you're importing):
// ESM
import { memo as reactMemo } from "react";
// CommonJS
const { memo: reactMemo } = require("react");
With ESM it's an import of a named export using import renaming syntax. With CommonJS, it's destructuring with destructuring renaming syntax.
I have a problem with the module not being found in React import. Here is my API from the file:
[
{
"poolNumber": "1",
"sender": "Damir",
"notRoutedReason": "NumberDoesntExist",
"sentDateTime": "2019-08-13T08:01:48.1535075Z",
"requestedDeliveryReportMaskText": "Submitted",
"deliveryReportReceivedDateTime": "2019-08-13T08:01:48.1535075Z",
"isUnicode": "FALSE",
"messageUUID": "4889e632-a314-45e2-89fd-35b07b4f9ff2"
},
{
"poolNumber": "1",
"sender": "Damir",
"notRoutedReason": "NumberDoesntExist",
"sentDateTime": "2019-08-13T08:01:46.3254032Z",
"requestedDeliveryReportMaskText": "Submitted",
"deliveryReportReceivedDateTime": "2019-08-13T08:01:46.3254032Z",
"isUnicode": "FALSE",
"messageUUID": "7f48626f-7dfe-4772-99e6-3a4c1df15e0e"
}
]
And then I'm trying to call it under imports so I can log(data)..
import React from 'react'
import dataJSON from './data.json'
const getData = async () => {
const response = await fetch(dataJSON)
const data = await response;
return getData
}
But I can't fetch data coz it isn't getting module I need.
How can I fix this?
If you're using Create React App this should work fine :
import dataJSON from './data.json'
console.log(dataJSON )
You could use axios / Promise based HTTP client for the browser and node.js to handle the request in the React componentDidMount life-cycle method.
https://github.com/axios/axios
But I agree that in CreatReactApp is easier to just:
import info from './data.json';
If you are using create-react-app, just import
import dataJson from './dataJson.json';
Please see my sandbox import json in react app
Tnx all for trying to help me, but my solution was putting .json file in public folder, and importing it in App.js... that Way engine didn't trow error and I resolved it with async/await.
For use import and export statements, you have to use es6, and for this, babal is required.
Maybe you have to add babel-plugin-import to your project: read if you have and how to install and configure here here)
I installed axios using the npm install axios command this is my package.json dependencies
"dependencies": {
"axios": "^0.18.0",
"bootstrap-vue": "^2.0.0-rc.11",
"vue": "^2.5.2",
"vue-router": "^3.0.1"
},
I registered the axios in my main.js file.
import Vue from 'vue'
import VueRouter from 'vue-router'
import BootstrapVue from 'bootstrap-vue'
import axios from 'axios'
import App from './App'
import routerList from './routes'
Vue.use(axios)
Vue.use(BootstrapVue)
Vue.use(VueRouter)
When I tried to use axios in one of my components I get this error:
Uncaught ReferenceError: axios is not defined
How to fix this?
Vue.use means adding plugins. However, axios is not a plugin for Vue, so you can not add it globally via use.
My recommendation is importing axios only when you need it. But if you really need to access it globally, you may like to add it to prototype.
Vue.prototype.$axios = axios
Then you can access axios in vue using this.$axios
Solution 1 (Not recommended):
In main.js, add this line instead of import axios from 'axios'
window.axios = require('axios');
And remove
Vue.use(axios)
Solution 2 (Recommended Approach):
Using window is generally considered a bad practice, so you better use axios the following way:
Create a folder named plugins inside of your src directory.
Then, create axios.js file inside that directory. We will put all our axios logic here and use axios as a Vue plugin.
Add the following:
import ax from 'axios'
// insert all your axios logic here
export const axios = ax
export default {
install (Vue, options) {
Vue.prototype.$axios = ax
}
}
In src/main.js, add the following:
import Vue from 'vue' // You can skip this line
import VueAxios from './plugins/axios'
Vue.use(VueAxios)
Now, you can use axios as this.$axios in your components. So something like this.$axios.get().
Therefore, you can import axios with the following line:
import { axios } from '#/plugins/axios'
Now, you can use axios directly in your store.
Or you can also use it as Vuex plugin:
import { axios } from '#/plugins/axios'
const axiosPlugin = store => {
store.$axios = axios
}
new Vuex.Store({
...,
plugins: [axiosPlugin]
})
Now, you can use it as this.$axios in Vuex.
Use following command to install axios
npm install axios --save
After executing above command import like mentioned below:
import axios from 'axios'
Also install vue-axios and import in main.js
import VueAxios from 'vue-axios'
Then in main.js:
Vue.use(VueAxios, axios)
Now if I am not mistaken in your methods you can use for example:
let uri = 'http://localhost:4000/tickets/add';
this.axios.post(uri, this.ticket).then((response) => {
console.log(response);
});
import Vue from 'vue'
import axios from 'axios'
Vue.prototype.$http = axios;
then inside your component you can start using axios like this:
{
methods: {
someMethod() {
this.$http.get('/users').then(() => {
// do something
})
}
}
}
Include this line:
import {AxiosInstance as axios} from "axios";
To use in Vue Components, install both Vue Axios and Axios packages
npm install --save axios vue-axios
In your main.js file, add the following:
import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)
With the above solution, I never had an issue using axios in my Vue components with this keyword till now.
Custom Javascript File
However, I had faced issues using Axios in a custom JS file with axios not defined error.
Following worked for me in a custom JS file:
const axios = require("axios");
Usage example:
export default {
fetchProducts() {
return axios.get(`${ROOT_URL}/products`);
},
};
Try this codes:
import axios from 'axios'
Vue.use(axios)