Javascript Naming Conventions for Importing modules
In JavaScript, naming conventions for imports and aliases can differ depending on the team's style guide, but there are some general best practices that are widely accepted.
Library Imports
These are usually named exactly as the library intended, in PascalCase or camelCase as per the library's documentation.
import React from 'react'
import Axios from 'axios'
Default Imports:
If the module exports a default value, you should stick to a name that represents what it does, usually in PascalCase or camelCase.
import MyComponent from './MyComponent'
Named Imports:
When you import named exports, the names should match the original names, and be destructured directly.
import { useState, useEffect } from 'react'
Renaming Imports:
If you absolutely have to rename an import due to naming conflicts or for clarity, use as to alias it.
import { useState as useMyState } from 'my-custom-hooks'
Wildcard Imports:
These should be avoided if possible for the sake of readability and understanding which pieces are being used from a module. If you must use it, it's commonly done with a PascalCase name.
import * as Utils from './Utils'
Best Practices:
- Grouping: Group your imports in a sensible manner. Libraries first, then absolute paths, and lastly relative paths.
- Sorting: Sort imports alphabetically to find dependencies faster.
- Spacing: Add a blank line between each group of imports.
// Libraries
import Axios from 'axios'
import React, { useState, useEffect } from 'react'
// Absolute paths
import MyDefaultComponent from 'MyDefaultComponent'
import { SomeComponent, AnotherComponent } from 'MyComponents'
// Relative paths
import Helper from './Helper'
import { something } from '../something'
Allowed Characters
In JavaScript and, by extension, React,
variable names and aliases must adhere to certain rules and conventions.
Specifically, they must start with a letter, underscore _
, or dollar sign $
subsequent characters can also be digits 0-9
.
This means that using a dash -
in a variable name or import alias
is not allowed and will result in a syntax error.
What Doesn't Work:
Trying to use a dash in an import alias like this will throw an error.
// This will result in a syntax error
import { useState as use-State } from 'react';
What Works:
However, you can use camelCase, PascalCase, or underscores if you need to rename an import for some reason.
// Valid
import { useState as useStateCustom } from 'react'
// Also valid
import { useState as UseState } from 'react'
// Valid as well
import { useState as use_state } from 'react'
Hence, So, if you are importing a package or file with a dash in its name, you will need to assign it to a valid JavaScript identifier using the as keyword.
For example: If you have a file named my-utils.js
and you're importing a function.
import { myFunction as myFunctionFromUtils } from 'my-utils'