Home > OS >  Why are some imports capitalised but some aren't?
Why are some imports capitalised but some aren't?

Time:11-01

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?

CodePudding user response:

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.

  • Related