This TypeError is thrown when import is combined with module.exports in a specific JavaScript file (module) and you are using Webpack 2.
[topads][/topads]
I was creating an API interface to interact with the GitHub API in my React app like so
import "whatwg-fetch"; const ROOT_API_URL = "https://api.github.com/"; const ACCESS_TOKEN = "access_token=9d...c0"; const fetchUser = async () => { const url = `${ROOT_API_URL}user?${ACCESS_TOKEN}`; const response = await fetch(url); const body = await response.json(); if (response.status !== 200) throw Error(body.message); return body; }; module.exports = { fetchUser, };
And upon running my app (yarn start) this error was being thrown
Uncaught TypeError: Cannot assign to read only property 'exports' of object '#<object width="300" height="150">'
Solution 1
To fix just replace import with require.
require("whatwg-fetch"); const ROOT_API_URL = "https://api.github.com/"; const ACCESS_TOKEN = "access_token=9d...c0"; const fetchUser = async () => { const url = `${ROOT_API_URL}user?${ACCESS_TOKEN}`; const response = await fetch(url); const body = await response.json(); if (response.status !== 200) throw Error(body.message); return body; }; module.exports = { fetchUser, };
Solution 2
My preferred solution 🙂
Switch the require to import, then add export before all of your function literals that you want to make public, then create an object with your function literals as properties and export default that object like so
const GitHubAPI = { fetchUser, updateProfile, }; export default GitHubAPI;
Full code
import "whatwg-fetch"; const ROOT_API_URL = "https://api.github.com/"; const ACCESS_TOKEN = "access_token=9d...c0"; export const fetchUser = async () => { const url = `${ROOT_API_URL}user?${ACCESS_TOKEN}`; const response = await fetch(url); const body = await response.json(); if (response.status !== 200) throw Error(body.message); return body; }; const GitHubAPI = { fetchUser, }; export default GitHubAPI;
Then in the module you want to use this GitHub interface you can use ES6 destructuring or the dot notation
// ES6 destructuring import { fetchUser } from "./github"; fetchUser(); // Dot notation import github_api from "./github"; github_api.fetchUser();
[bottomads][/bottomads]