-
Notifications
You must be signed in to change notification settings - Fork 31
Closed
Description
Your Environment
- Prettier version: 3.6.0
- node version: 22.16.0
- package manager: [email protected]
- IDE: VScode
Describe the bug
When running pnpm format --write .
, I got an error with one MDX file. The error was:
[error] [prettier-plugin-sort-imports]: import sorting aborted due to babel parsing error.
It seems the plugin tried to parse an .mdx
file with Babel but failed. This error breaks the formatting process.
To Reproduce
- Create an MDX file (
js.mdx
) with the provided content. - Run
pnpm format --write .
using Prettier with@ianvs/prettier-plugin-sort-imports
enabled. - Observe the parsing error from the plugin.
Expected behavior
There should not be any error, formatting could be done successfully.
Screenshots, code sample, etc
MDX Code:
---
title: JavaScript Cheatsheet
description: JavaScript is a high-level, interpreted programming language that is widely used for web development. This cheatsheet covers essential JavaScript concepts, methods, and examples to help you write efficient code.
tags: [javascript, cheatsheet, programming, web-development, js-cheatsheet]
date: 25-09-2024
readTime: 7 min
updatedAt: 26-04-2025
---
JavaScript is a high-level, interpreted programming language that is widely used for web development. This cheatsheet covers essential JavaScript concepts, methods, and examples to help you write efficient code.
## JavaScript Basics
Set of JavaScript basic syntax to add, execute and write basic programming paradigms in Javascript
### On Page Script
Adding internal JavaScript to HTML
```html showLineNumbers
<script type="text/javascript">
//JS code goes here
</script>
```
### External JS File
Adding external JavaScript to HTML
```html
<script src="filename.js"></script>
```
### Functions
Creating a function in JavaScript
```js showLineNumbers
function functionName() {
// code to be executed
}
```
### DOM Element
Changing content of a DOM Element
```js
document.getElementById("elementID").innerHTML = "Hello World!";
```
### Output
This will print the value of a in JavaScript console
```js
console.log(a);
```
## Conditional Statements
Conditional statements are used to perform operations based on some conditions.
### If Statement
The block of code to be executed, when the condition specified is true.
```js
if (condition) {
// code to be executed
}
```
### If-Else Statement
If the condition for the if block is false, then the else block will be executed.
```js showLineNumbers
if (condition) {
// code to be executed if the condition is true
} else {
// code to be executed if the condition is false
}
```
### If-Else-If Statement
A basic if-else ladder
```js showLineNumbers
if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition2 is true
} else {
// code to be executed if neither condition is true
}
```
### Switch Statement
The switch statement is used to perform different actions based on different conditions.
```js showLineNumbers
switch (expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
```
## Loops
Loops are used to execute the same block of code again and again, as long as a certain condition is met.
### For Loop
For loop syntax in javascript
```js showLineNumbers
for (initialization; condition; increment / decrement) {
// code to be executed
}
```
Example:
```js showLineNumbers
for (let i = 0; i < 5; i++) {
text += "Iteration number: " + i + "<br />";
}
```
### While Loop
Runs the code till the specified condition is true
```js showLineNumbers
while (condition) {
// code to be executed
}
```
### Do-While Loop
The code block will be executed once before the condition is checked.
```js showLineNumbers
do {
// code to be executed
} while (condition);
```
## Strings
The string is a sequence of characters that is used for storing and managing text data.
### charAt method
Returns the character from the specified index.
```js
str.charAt(3);
```
### concat method
Joins two or more strings.
```js
str1.concat(str2);
```
### indexOf method
Returns the index within the calling String object of the first occurrence of the specified value.
```js
str.indexOf("world");
```
### replace method
Replaces the specified value with another value in a string.
```js
str.replace("hello", "world");
```
### match method
Used to match a regular expression against a string.
```js
str.match(/(chapter \d+(\.\d)*)/i;)
```
### search method
Searches a string for a specified value and returns the position of the match.
```js
str.search("world");
```
### split method
Splits a string into an array of substrings.
```js
str.split("\n");
```
### substring method
Returns the part of the string between the start and end indexes.
```js
str.substring(1, 4);
```
### toLowerCase method
Converts a string to lowercase letters.
```js
str.toLowerCase();
```
### toUpperCase method
Converts a string to uppercase letters.
```js
str.toUpperCase();
```
### trim method
Removes whitespace from both ends of a string.
```js
str.trim();
```
## Arrays
Arrays are used to store multiple values in a single variable.
### Creating an Array
Creating an array in JavaScript
```js
let fruits = ["Apple", "Banana", "Mango"];
```
### Accessing Array Elements
Accessing array elements in JavaScript
```js
let firstFruit = fruits[0];
```
### concat method
Joins two or more arrays together.
```js
let vegetables = ["Carrot", "Potato"];
let food = fruits.concat(vegetables);
```
### push method
Adds new elements to the end of an array.
```js
fruits.push("Orange");
```
### pop method
Removes the last element from an array.
```js
fruits.pop();
```
### shift method
Removes the first element from an array.
```js
fruits.shift();
```
### unshift method
Adds new elements to the beginning of an array.
```js
fruits.unshift("Grapes");
```
### splice method
Adds or removes elements from an array.
```js
fruits.splice(1, 0, "Pineapple", "Kiwi");
```
### slice method
Returns a new array from a specified index.
```js
let citrus = fruits.slice(1, 3);
```
### join method
Joins all elements of an array into a string.
```js
let fruitString = fruits.join(", ");
```
### sort method
Sorts the elements of an array.
```js
fruits.sort();
```
### toString method
Converts an array to a string.
```js
let fruitString = fruits.toString();
```
### valueOf method
Returns the primitive value of an array.
```js
let fruitValue = fruits.valueOf();
```
### indexOf method
Returns the index of the first occurrence of a specified element in an array.
```js
let index = fruits.indexOf("Banana");
```
### forEach method
Executes a provided function once for each array element.
```js showLineNumbers
fruits.forEach(function (fruit) {
console.log(fruit);
});
```
## Number Methods
JS math and number objects provide several constant and methods to perform mathematical operations.
### toExponential method
Converts a number to its exponential form.
```js
toExponential();
```
### toFixed method
Formats a number using fixed-point notation.
```js
toFixed();
```
### toPrecision method
Formats a number to a specified length.
```js
toPrecision();
```
### toString method
Converts a number to a string.
```js
toString();
```
### valueOf method
Returns the primitive value of a number.
```js
valueOf();
```
## Math Methods
Math object provides several constants and methods to perform mathematical operations.
### Math.PI
Returns the value of PI.
```js
Math.PI;
```
### ceil method
Rounds a number up to the nearest integer.
```js
Math.ceil(4.7);
```
### floor method
Rounds a number down to the nearest integer.
```js
Math.floor(4.7);
```
### round method
Rounds a number to the nearest integer.
```js
Math.round(4.7);
```
### max method
Returns the largest of zero or more numbers.
```js
Math.max(4, 7, 2);
```
### min method
Returns the smallest of zero or more numbers.
```js
Math.min(4, 7, 2);
```
### exp method
Returns the value of E raised to the power of a number.
```js
Math.exp(1);
```
### log method
Returns the natural logarithm of a number.
```js
Math.log(10);
```
### pow method
Returns the value of a number raised to a power.
```js
Math.pow(2, 3);
```
### random method
Returns a random number between 0 and 1.
```js
Math.random();
```
### sqrt method
Returns the square root of a number.
```js
Math.sqrt(16);
```
## Date Methods
Date object is used to get the year, month and day. It has methods to get and set day, month, year, hour, minute, and seconds.
```js
let date = new Date();
```
### Pulling Date from the Date object
Returns the date from the date object
```js
date.getDate();
```
### Pulling Day from the Date object
Returns the day from the date object
```js
date.getDay();
```
### Pulling Hours from the Date object
Returns the hours from the date object
```js
date.getHours();
```
### Pulling Minutes from the Date object
Returns the minutes from the date object
```js
date.getMinutes();
```
### Pulling Seconds from the Date object
Returns the seconds from the date object
```js
date.getSeconds();
```
### Pulling Time from the Date object
Returns the time from the date object
```js
date.getTime();
```
## Mouse Events
Any change in the state of an object is referred to as an Event. With the help of JS, you can handle events, i.e., how any specific HTML tag will work when the user does something.
```js
const element = document.getElementById("myBtn");
```
### onclick
The onclick event occurs when the user clicks on an element.
```js showLineNumbers
element.addEventListener("click", () => {
// Code to be executed when the event is fired
});
```
### oncontextmenu
The oncontextmenu event occurs when the user right-clicks on an element to open a context menu.
```js showLineNumbers
element.addEventListener("contextmenu", () => {
// Code to be executed when the event is fired
});
```
### dblclick
The ondblclick event occurs when the user double-clicks on an element.
```js showLineNumbers
element.addEventListener("dblclick", () => {
// Code to be executed when the event is fired
});
```
### mouseenter
The onmouseenter event occurs when the mouse pointer is moved onto an element.
```js showLineNumbers
element.addEventListener("mouseenter", () => {
// Code to be executed when the event is fired
});
```
### mouseleave
The onmouseleave event occurs when the mouse pointer is moved out of an element.
```js showLineNumbers
element.addEventListener("mouseleave", () => {
// Code to be executed when the event is fired
});
```
### mouseover
The onmouseover event occurs when the mouse pointer is moved over an element.
```js showLineNumbers
element.addEventListener("mouseover", () => {
// Code to be executed when the event is fired
});
```
### mouseout
The onmouseout event occurs when the mouse pointer is moved out of an element.
```js showLineNumbers
element.addEventListener("mouseout", () => {
// Code to be executed when the event is fired
});
```
### mousemove
The onmousemove event occurs when the mouse pointer is moving while it is over an element.
```js showLineNumbers
element.addEventListener("mousemove", () => {
// Code to be executed when the event is fired
});
```
## Keyboard Events
Keyboard events are used to handle the user's keyboard input.
```js
const element = document.getElementById("myInput");
```
### keydown
The keydown event occurs when the user is pressing a key.
```js showLineNumbers
element.addEventListener("keydown", () => {
// Code to be executed when the event is fired
});
```
### keypress
The keypress event occurs when the user presses a key.
```js showLineNumbers
element.addEventListener("keypress", () => {
// Code to be executed when the event is fired
});
```
### keyup
The keyup event occurs when the user releases a key.
```js showLineNumbers
element.addEventListener("keyup", () => {
// Code to be executed when the event is fired
});
```
## Errors
Errors are thrown by the compiler or interpreter whenever they find any fault in the code, and it can be of any type like syntax error, run-time error, logical error, etc. JS provides some functions to handle the errors.
### try-catch
The try statement allows you to define a block of code to be tested for errors while it is being executed.
```js showLineNumbers
try {
// code to be executed
} catch (error) {
// code to be executed if an error occurs
}
```
### throw
The throw statement allows you to create a custom error.
```js
throw new Error("An error occurred");
```
## Window Methods
Methods that are available from the window object
### alert
Displays an alert box with a message and an OK button.
```js
window.alert("Hello World!");
```
### confirm
Displays a dialog box with a message and an OK and Cancel button.
```js
window.confirm("Press a button!");
```
### prompt
Displays a dialog box that prompts the visitor for input.
```js
window.prompt("Please enter your name", "John Doe");
```
### blur method
Removes focus from the current window.
```js
window.blur();
```
### focus method
Sets focus to the current window.
```js
window.focus();
```
### setInterval
Calls a function or evaluates an expression at specified intervals (in milliseconds).
```js showLineNumbers
setInterval(() => {
// Code to be executed
}, 1000);
```
### setTimeout
Calls a function or evaluates an expression after a specified number of milliseconds.
```js showLineNumbers
setTimeout(() => {
// Code to be executed
}, 1000);
```
### open method
Opens a new browser window.
```js
window.open("https://www.example.com", "_blank");
```
### close method
Closes the current window.
```js
window.close();
```
### scrollBy
Scrolls the document by the specified number of pixels.
```js
window.scrollBy(0, 100); // Scroll down by 100 pixels
```
### scrollTo
Scrolls the document to the specified coordinates.
```js
window.scrollTo(0, 100); // Scroll to the top of the page
```
### clearInterval
Clears a timer set with setInterval().
```js
clearInterval(timer);
```
### clearTimeout
Clears a timer set with setTimeout().
```js
clearTimeout(timer);
```
### stop
Stops the further resource loading
```js
window.stop();
```
## Query/Get Elements
The browser creates a DOM (Document Object Model) whenever a web page is loaded, and with the help of HTML DOM, one can access and modify all the elements of the HTML document.
### querySelector
Returns the first element that matches a specified CSS selector(s) in the document.
```js
document.querySelector("p");
```
### querySelectorAll
Returns all elements that matches a specified CSS selector(s) in the document.
```js
document.querySelectorAll("p", ...);
```
### getElementsByTagName
Returns a collection of all elements in the document with the specified tag name.
```js
document.getElementsByTagName("p");
```
### getElementsByClassName
Returns a collection of all elements in the document with the specified class name.
```js
document.getElementsByClassName("example");
```
### getElementById
Returns the element that has the ID attribute with the specified value.
```js
document.getElementById("example");
```
## Creating Elements
Creating elements in the DOM
### createElement
Create a new element
```js
let p = document.createElement("p");
```
### createTextNode
Create a text node
```js
let text = document.createTextNode("Hello World!");
```
## Conclusion
This cheatsheet covers essential JavaScript concepts, methods, and examples to help you write efficient code. JavaScript is a high-level, interpreted programming language that is widely used for web development. It is a versatile language that can be used for both client-side and server-side development. By mastering JavaScript, you can build interactive web applications and create dynamic content on your website.
</>
Configuration File (cat .prettierrc, prettier.config.js, .prettier.js)
//prettier.config.mjs
/** @type {import('prettier').Config} */
const config = {
endOfLine: "lf",
semi: true,
singleQuote: false,
tabWidth: 2,
printWidth: 100,
trailingComma: "es5",
plugins: ["@ianvs/prettier-plugin-sort-imports", "prettier-plugin-tailwindcss"],
tailwindFunctions: ["clsx", "cn", "cva"],
tailwindAttributes: [
"activeClassName",
"navClassName",
"liClassName",
"ulClassName",
"className",
"class",
],
importOrder: [
"^(react|next?/?([a-zA-Z/]*))$",
"<THIRD_PARTY_MODULES>",
"^types$",
"^@/types/(.*)$",
"^@/actions/(.*)$",
"^@/lib/(.*)$",
"^@/hooks/(.*)$",
"^@/config/(.*)$",
"^@/components/ui/(.*)$",
"^@/components/(.*)$",
"^@/validations/(.*)$",
"^@/styles/(.*)$",
"^@/app/(.*)$",
"^[./]",
],
importOrderTypeScriptVersion: "5.8.3",
importOrderParserPlugins: ["typescript", "jsx", "decorators-legacy"],
};
export default config;
Error log
[error] [prettier-plugin-sort-imports]: import sorting aborted due to babel parsing error.
Contribute to @ianvs/prettier-plugin-sort-imports
- I'm willing to fix this bug 🥇
rebasecase
Metadata
Metadata
Assignees
Labels
No labels