quiz/js: polyfills and commonjs vs es modules in javascript (#464)
This commit is contained in:
parent
e040771d9b
commit
9a6beb4b8e
|
|
@ -0,0 +1,117 @@
|
|||
---
|
||||
title: Explain the differences between commonjs modules-and-es-modules ?
|
||||
---
|
||||
|
||||
## TL;DR
|
||||
|
||||
In JavaScript, `modules` are reusable pieces of code that encapsulate functionality, making it easier to manage, maintain, and structure your applications. Modules allow you to break down your code into smaller, manageable parts, each with its own scope.
|
||||
|
||||
**CommonJS**:
|
||||
|
||||
CommonJS is an older module system that was initially designed for server-side JavaScript development with Node.js. It uses the require function to load modules and the module.exports or exports object to define the exports of a module.
|
||||
|
||||
```js
|
||||
// my-module.js
|
||||
const value = 42;
|
||||
module.exports = { value };
|
||||
|
||||
// main.js
|
||||
const myModule = require('./my-module.js');
|
||||
console.log(myModule.value); // 42
|
||||
```
|
||||
|
||||
**ES Modules**:
|
||||
|
||||
ES Modules (ECMAScript Modules) are the standardized module system introduced in ES6 (ECMAScript 2015). They use the import and export statements to handle module dependencies.
|
||||
|
||||
```js
|
||||
// my-module.js
|
||||
export const value = 42;
|
||||
|
||||
// main.js
|
||||
import { value } from './my-module.js';
|
||||
console.log(value); // 42
|
||||
```
|
||||
|
||||
**CommonJs vs ES Modules**
|
||||
|
||||
| Feature | CommonJS | ES Modules |
|
||||
| --- | --- | --- |
|
||||
| Module Syntax | `require()` for importing `module.exports` for exporting | `import` for importing `export` for exporting |
|
||||
| Environment | Primarily used in `Node.js` for server-side development | Designed for both browser and server-side JavaScript (Node.js) |
|
||||
| Loading | Synchronous loading of modules | Asynchronous loading of modules |
|
||||
| Structure | Dynamic imports, can be conditionally called | Static imports/exports at the top level |
|
||||
| File Extensions | `.js` (default) | `.mjs` or `.js` (with `type`: `module` in `package.json`) |
|
||||
| Browser Support | Not natively supported in browsers | Natively supported in modern browsers |
|
||||
| Optimization | Limited optimization due to dynamic nature | Allows for optimizations like tree-shaking due to static structure |
|
||||
| Compatibility | Widely used in existing Node.js codebases and libraries | Newer standard, but gaining adoption in modern projects |
|
||||
|
||||
---
|
||||
|
||||
## Modules in Javascript
|
||||
|
||||
`Modules` in JavaScript are a way to organize and encapsulate code into reusable and maintainable units. They allow developers to break down their codebase into smaller, self-contained pieces, promoting code reuse, separation of concerns, and better organization. There are two main module systems in JavaScript: `CommonJS` and `ES Modules`.
|
||||
|
||||
### CommonJS
|
||||
|
||||
CommonJS is an older module system that was initially designed for server-side JavaScript development with Node.js. It uses the require function to load modules and the module.exports or exports object to define the exports of a module.
|
||||
|
||||
- **Syntax**: Modules are included using `require()` and exported using `module.exports`.
|
||||
- **Environment**: Primarily used in `Node.js`.
|
||||
- **Execution**: Modules are loaded `synchronously`.
|
||||
|
||||
```js
|
||||
// my-module.js
|
||||
const value = 42;
|
||||
module.exports = { value };
|
||||
|
||||
// main.js
|
||||
const myModule = require('./my-module.js');
|
||||
console.log(myModule.value); // 42
|
||||
```
|
||||
|
||||
#### Key points about CommonJS:
|
||||
|
||||
- `Synchronous` loading of modules
|
||||
- `Designed for server-side` environments (`Node.js`)
|
||||
- Uses `require` for importing and `module.exports` for exporting
|
||||
- Modules are `loaded dynamically at runtime`
|
||||
|
||||
### ES Modules
|
||||
|
||||
ES Modules (ECMAScript Modules) are the standardized module system introduced in ES6 (ECMAScript 2015). They use the import and export statements to handle module dependencies.
|
||||
|
||||
- **Syntax**: Modules are imported using `import` and exported using `export`.
|
||||
- **Environment**: Can be used in both `browser` environments and `Node.js` (with certain configurations).
|
||||
- **Execution**: Modules are loaded `asynchronously`.
|
||||
- **Support**: Introduced in `ES6 (2015)`, now widely supported in modern browsers and `Node.js`.
|
||||
|
||||
```js
|
||||
// my-module.js
|
||||
export const value = 42;
|
||||
|
||||
// main.js
|
||||
import { value } from './my-module.js';
|
||||
console.log(value); // 42
|
||||
```
|
||||
|
||||
#### Key points about `ES Modules`:
|
||||
|
||||
- `Asynchronous loading` of modules
|
||||
- Designed for both `client-side` (browsers) and `server-side` (`Node.js`)
|
||||
- Uses `import` for importing and `export` for exporting
|
||||
- Modules are loaded statically at `compile-time`
|
||||
- Better performance due to `static analysis` and `tree-shaking`
|
||||
|
||||
## Summary
|
||||
|
||||
While `CommonJS` was the default module system in `Node.js` initially,`ES Modules` are now the recommended approach for new projects, as they provide better tooling, performance, and ecosystem compatibility. However, `CommonJS` modules are still widely used in existing code bases and libraries.
|
||||
|
||||
## Further reading
|
||||
|
||||
- [JavaScript modules - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules)
|
||||
- [CommonJS vs ES Modules: the shift from require to import](https://nikolasbarwicki.com/articles/commonjs-vs-es-modules-the-shift-from-require-to-import/)
|
||||
- [Modules, introduction - javascript.info](https://javascript.info/modules-intro)
|
||||
- [Modules - Eloquent Javascript](https://eloquentjavascript.net/10_modules.html)
|
||||
- [CommonJS vs. ES modules in Node.js](https://blog.logrocket.com/commonjs-vs-es-modules-node-js/)
|
||||
- [Understanding CommonJS vs. ES Modules in JavaScript](https://www.syncfusion.com/blogs/post/js-commonjs-vs-es-modules)
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
{
|
||||
"slug": "explain-the-differences-between-commonjs-modules-and-es-modules",
|
||||
"languages": [],
|
||||
"companies": [],
|
||||
"premium": false,
|
||||
"duration": 5,
|
||||
"published": true,
|
||||
"topics": ["javascript"],
|
||||
"importance": "mid",
|
||||
"difficulty": "hard"
|
||||
}
|
||||
|
|
@ -0,0 +1,103 @@
|
|||
---
|
||||
title: What are polyfills for ?
|
||||
---
|
||||
|
||||
## TL;DR
|
||||
|
||||
Polyfills in JavaScript are pieces of code that provide modern functionality to older browsers that lack native support for those features. They bridge the gap between the JavaScript language features and APIs available in modern browsers and the limited capabilities of older browser versions.
|
||||
|
||||
**Key Points about Polyfills**
|
||||
|
||||
- **Purpose**: To bridge the gap between modern JavaScript features and older browsers.
|
||||
- **Implementation**: They can be implemented manually or included through libraries.
|
||||
- **Usage**: They are often used in conjunction with feature detection.
|
||||
|
||||
**Common Use Cases for Polyfills**:
|
||||
|
||||
- **New JavaScript Methods**: For example, `Array.prototype.includes()`, `Object.assign()`, etc.
|
||||
- **New APIs**: Such as Fetch API, `Promise`, `IntersectionObserver`, etc.
|
||||
- **ES6 Features**: Such as `let`, `const`, `arrow functions`, etc.
|
||||
|
||||
**Libraries and services for Polyfills**
|
||||
|
||||
- `Core-js`: A modular standard library for JavaScript which includes polyfills for a wide range of ECMAScript features.
|
||||
|
||||
```js
|
||||
import 'core-js/stable';
|
||||
import 'regenerator-runtime/runtime';
|
||||
```
|
||||
|
||||
- `Polyfill.io`: A service that provides polyfills based on the features and user agents specified in the request.
|
||||
|
||||
```js
|
||||
<script src="https://polyfill.io/v3/polyfill.min.js"></script>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Polyfills in JavaScript:
|
||||
|
||||
Polyfills in JavaScript are pieces of code (usually JavaScript) that provide modern functionality on older browsers that do not natively support it. They enable developers to use newer features of the language and APIs while maintaining compatibility with older environments.
|
||||
|
||||
### How Polyfills Work
|
||||
|
||||
Polyfills detect if a feature or API is missing in a browser and provide a custom implementation of that feature using existing JavaScript capabilities. This allows developers to write code using the latest JavaScript features and APIs without worrying about browser compatibility issues.
|
||||
|
||||
For example, let's consider the `Array.prototype.includes()` method, which determines if an array includes a specific element. This method is not supported in older browsers like `Internet Explorer 11`. To address this, we can use a polyfill:
|
||||
|
||||
```js
|
||||
// Polyfill for Array.prototype.includes()
|
||||
if (!Array.prototype.includes) {
|
||||
Array.prototype.includes = function (searchElement) {
|
||||
for (var i = 0; i < this.length; i++) {
|
||||
if (this[i] === searchElement) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
By including this polyfill, we can safely use Array.prototype.includes() even in browsers that don't support it natively.
|
||||
|
||||
### Implementing Polyfills
|
||||
|
||||
- **Identify the missing feature**: Determine if the feature is compatible with the target browsers or detect its presence using feature detection methods like `typeof`, `in`, or `window`.
|
||||
- **Write the fallback implementation**: Develop the fallback implementation that provides similar functionality, either using a pre-existing polyfill library or pure JavaScript code.
|
||||
- **Test the polyfill**: Thoroughly test the polyfill to ensure it functions as intended across different contexts and browsers.
|
||||
- **Implement the polyfill**: Enclose the code that uses the missing feature in an if statement that checks for feature support. If not supported, run the polyfill code instead.
|
||||
|
||||
### Considerations
|
||||
|
||||
- **Selective Loading**: Polyfills should only be loaded for browsers that need them to optimize performance.
|
||||
- **Feature Detection**: Perform feature detection before applying a polyfill to avoid overwriting native implementations or applying unnecessary polyfills.
|
||||
- **Size and Performance**: Polyfills can increase the JavaScript bundle size, so minification and compression techniques should be used to mitigate this impact.
|
||||
- **Existing Libraries**: Consider using existing libraries and tools that offer comprehensive polyfill solutions for multiple features, handling feature detection, conditional loading, and fallbacks efficiently
|
||||
|
||||
### Libraries and services for Polyfills
|
||||
|
||||
- `Core-js`: A modular standard library for JavaScript which includes polyfills for a wide range of ECMAScript features.
|
||||
|
||||
```js
|
||||
import 'core-js/stable';
|
||||
import 'regenerator-runtime/runtime';
|
||||
```
|
||||
|
||||
- `Polyfill.io`: A service that provides polyfills based on the features and user agents specified in the request.
|
||||
|
||||
```js
|
||||
<script src="https://polyfill.io/v3/polyfill.min.js"></script>
|
||||
```
|
||||
|
||||
## Summary
|
||||
|
||||
Polyfills are essential for ensuring cross-browser compatibility and enabling the use of modern JavaScript features in older browsers. By understanding how polyfills work and implementing them carefully, developers can write more robust and consistent code across different browser versions.
|
||||
|
||||
## Further reading
|
||||
|
||||
- [Polyfill - MDN](https://developer.mozilla.org/en-US/docs/Glossary/Polyfill)
|
||||
- [Polyfills and transpilers](https://javascript.info/polyfills)
|
||||
- [Polyfills: How do they work?](https://medium.com/alienbrains/polyfills-how-do-they-work-ea6a12b792b)
|
||||
- [Polyfill in Javascript](https://www.linkedin.com/pulse/polyfill-javascript-divyansh-singh)
|
||||
- [Shubham Dutta](https://dev.to/shubhamdutta2000/polyfills-for-javascript-a-full-overview-3f7m)
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
{
|
||||
"slug": "what-are-polyfills-for",
|
||||
"languages": [],
|
||||
"companies": [],
|
||||
"premium": false,
|
||||
"duration": 5,
|
||||
"published": true,
|
||||
"topics": ["javascript"],
|
||||
"importance": "mid",
|
||||
"difficulty": "medium"
|
||||
}
|
||||
Loading…
Reference in New Issue