1576761449
Almost every language has a concept of modules — a way to include functionality declared in one file within another. Typically, a developer creates an encapsulated library of code responsible for handling related tasks. That library can be referenced by applications or other modules.
The benefits:
x()
in module1 cannot clash with function x()
in module2. Options such as namespacing are employed so calls become module1.x()
and module2.x()
.Anyone starting web development a few years ago would have been shocked to discover there was no concept of modules in JavaScript. It was impossible to directly reference or include one JavaScript file in another. Developers therefore resorted to alternative options.
<script>
TagsHTML can load any number JavaScript files using multiple <script>
tags:
<script src="lib1.js"></script>
<script src="lib2.js"></script>
<script src="core.js"></script>
<script>
console.log('inline code');
</script>
The average web page in 2018 uses 25 separate scripts, yet it’s not a practical solution:
lib1.js
referenced code in lib2.js
, the code would fail because it had not been loaded. That could break further JavaScript processing.One solution to problems of multiple <script>
tags is to concatenate all JavaScript files into a single, large file. This solves some performance and dependency management issues, but it could incur a manual build and testing step.
Systems such as RequireJS and SystemJS provide a library for loading and namespacing other JavaScript libraries at runtime. Modules are loaded using Ajax methods when required. The systems help, but could become complicated for larger code bases or sites adding standard <script>
tags into the mix.
Bundlers introduce a compile step so JavaScript code is generated at build time. Code is processed to include dependencies and produce a single ES5 cross-browser compatible concatenated file. Popular options include Babel, Browserify, webpack and more general task runners such as Grunt and Gulp.
A JavaScript build process requires some effort, but there are benefits:
The options above introduced a variety of competing module definition formats. Widely-adopted syntaxes included:
module.exports
and require
syntax used in Node.jsA single, native module standard was therefore proposed in ES6 (ES2015).
Everything inside an ES6 module is private by default, and runs in strict mode (there’s no need for 'use strict'
). Public variables, functions and classes are exposed using export
. For example:
// lib.js
export const PI = 3.1415926;
export function sum(...args) {
log('sum', args);
return args.reduce((num, tot) => tot + num);
}
export function mult(...args) {
log('mult', args);
return args.reduce((num, tot) => tot * num);
}
// private function
function log(...msg) {
console.log(...msg);
}
Alternatively, a single export
statement can be used. For example:
// lib.js
const PI = 3.1415926;
function sum(...args) {
log('sum', args);
return args.reduce((num, tot) => tot + num);
}
function mult(...args) {
log('mult', args);
return args.reduce((num, tot) => tot * num);
}
// private function
function log(...msg) {
console.log(...msg);
}
export { PI, sum, mult };
import
is then used to pull items from a module into another script or module:
// main.js
import { sum } from './lib.js';
console.log( sum(1,2,3,4) ); // 10
In this case, lib.js
is in the same folder as main.js
. Absolute file references (starting with /
), relative file references (starting ./
or ../
) or full URLs can be used.
Multiple items can be imported at one time:
import { sum, mult } from './lib.js';
console.log( sum(1,2,3,4) ); // 10
console.log( mult(1,2,3,4) ); // 24
and imports can be aliased to resolve naming collisions:
import { sum as addAll, mult as multiplyAll } from './lib.js';
console.log( addAll(1,2,3,4) ); // 10
console.log( multiplyAll(1,2,3,4) ); // 24
Finally, all public items can be imported by providing a namespace:
import * as lib from './lib.js';
console.log( lib.PI ); // 3.1415926
console.log( lib.add(1,2,3,4) ); // 10
console.log( lib.mult(1,2,3,4) ); // 24
At the time of writing, ES6 modules are supported in Chromium-based browsers (v63+), Safari 11+, and Edge 16+. Firefox support will arrive in version 60 (it’s behind an about:config
flag in v58+).
Scripts which use modules must be loaded by setting a type="module"
attribute in the <script>
tag. For example:
<script type="module" src="./main.js"></script>
or inline:
<script type="module">
import { something } from './somewhere.js';
// ...
</script>
Modules are parsed once, regardless of how many times they’re referenced in the page or other modules.
Modules must be served with the MIME type application/javascript
. Most servers will do this automatically, but be wary of dynamically generated scripts or .mjs
files (see the Node.js section below).
Regular <script>
tags can fetch scripts on other domains but modules are fetched using cross-origin resource sharing (CORS). Modules on different domains must therefore set an appropriate HTTP header, such as Access-Control-Allow-Origin: *
.
Finally, modules won’t send cookies or other header credentials unless a crossorigin="use-credentials"
attribute is added to the <script>
tag and the response contains the header Access-Control-Allow-Credentials: true
.
The <script defer>
attribute delays script execution until the document has loaded and parsed. Modules — including inline scripts — defer by default. Example:
<!-- runs SECOND -->
<script type="module">
// do something...
</script>
<!-- runs THIRD -->
<script defer src="c.js"></script>
<!-- runs FIRST -->
<script src="a.js"></script>
<!-- runs FOURTH -->
<script type="module" src="b.js"></script>
Browsers without module support won’t run type="module"
scripts. A fallback script can be provided with a nomodule
attribute which module-compatible browsers ignore. For example:
<script type="module" src="runs-if-module-supported.js"></script>
<script nomodule src="runs-if-module-not-supported.js"></script>
Browser support is growing, but it’s possibly a little premature to switch to ES6 modules. For the moment, it’s probably better to use a module bundler to create a script that works everywhere.
When Node.js was released in 2009, it would have been inconceivable for any runtime not to provide modules. CommonJS was adopted, which meant the Node package manager, npm, could be developed. Usage grew exponentially from that point.
A CommonJS module can be coded in a similar way to an ES2015 module. module.exports
is used rather than export
:
// lib.js
const PI = 3.1415926;
function sum(...args) {
log('sum', args);
return args.reduce((num, tot) => tot + num);
}
function mult(...args) {
log('mult', args);
return args.reduce((num, tot) => tot * num);
}
// private function
function log(...msg) {
console.log(...msg);
}
module.exports = { PI, sum, mult };
require
(rather than import
) is used to pull this module into another script or module:
const { sum, mult } = require('./lib.js');
console.log( sum(1,2,3,4) ); // 10
console.log( mult(1,2,3,4) ); // 24
require
can also import all items:
const lib = require('./lib.js');
console.log( lib.PI ); // 3.1415926
console.log( lib.add(1,2,3,4) ); // 10
console.log( lib.mult(1,2,3,4) ); // 24
So ES6 modules were easy to implement in Node.js, right? Er, no.
ES6 modules are behind a flag in Node.js 9.8.0+ and will not be fully implemented until at least version 10. While CommonJS and ES6 modules share similar syntax, they work in fundamentally different ways:
It would make no difference in the example above, but consider the following ES2015 module code:
// ES2015 modules
// ---------------------------------
// one.js
console.log('running one.js');
import { hello } from './two.js';
console.log(hello);
// ---------------------------------
// two.js
console.log('running two.js');
export const hello = 'Hello from two.js';
The output for ES2015:
running two.js
running one.js
hello from two.js
Similar code written using CommonJS:
// CommonJS modules
// ---------------------------------
// one.js
console.log('running one.js');
const hello = require('./two.js');
console.log(hello);
// ---------------------------------
// two.js
console.log('running two.js');
module.exports = 'Hello from two.js';
The output for CommonJS:
running one.js
running two.js
hello from two.js
Execution order could be critical in some applications, and what would happen if ES2015 and CommonJS modules were mixed in the same file? To resolve this problem, Node.js will only permit ES6 modules in files with the extension .mjs
. Files with a .js
extension will default to CommonJS. It’s a simple option which removes much of the complexity and should aid code editors and linters.
ES6 modules are only practical from Node.js v10 onwards (released in April 2018). Converting an existing project is unlikely to result in any benefit, and would render an application incompatible with earlier versions of Node.js.
For new projects, ES6 modules provide an alternative to CommonJS. The syntax is identical to client-side coding, and may offer an easier route to isomorphic JavaScript, which can run in the either the browser or on a server.
A standardized JavaScript module system took many years to arrive, and even longer to implement, but the problems have been rectified. All mainstream browsers and Node.js from mid 2018 support ES6 modules, although a switch-over lag should be expected while everyone upgrades.
Learn ES6 modules today to benefit your JavaScript development tomorrow.
#es6 #javascript #webdev
1619571780
March 25, 2021 Deepak@321 0 Comments
Welcome to my blog, In this article, we will learn the top 20 most useful python modules or packages and these modules every Python developer should know.
Hello everybody and welcome back so in this article I’m going to be sharing with you 20 Python modules you need to know. Now I’ve split these python modules into four different categories to make little bit easier for us and the categories are:
Near the end of the article, I also share my personal favorite Python module so make sure you stay tuned to see what that is also make sure to share with me in the comments down below your favorite Python module.
#python #packages or libraries #python 20 modules #python 20 most usefull modules #python intersting modules #top 20 python libraries #top 20 python modules #top 20 python packages
1576761449
Almost every language has a concept of modules — a way to include functionality declared in one file within another. Typically, a developer creates an encapsulated library of code responsible for handling related tasks. That library can be referenced by applications or other modules.
The benefits:
x()
in module1 cannot clash with function x()
in module2. Options such as namespacing are employed so calls become module1.x()
and module2.x()
.Anyone starting web development a few years ago would have been shocked to discover there was no concept of modules in JavaScript. It was impossible to directly reference or include one JavaScript file in another. Developers therefore resorted to alternative options.
<script>
TagsHTML can load any number JavaScript files using multiple <script>
tags:
<script src="lib1.js"></script>
<script src="lib2.js"></script>
<script src="core.js"></script>
<script>
console.log('inline code');
</script>
The average web page in 2018 uses 25 separate scripts, yet it’s not a practical solution:
lib1.js
referenced code in lib2.js
, the code would fail because it had not been loaded. That could break further JavaScript processing.One solution to problems of multiple <script>
tags is to concatenate all JavaScript files into a single, large file. This solves some performance and dependency management issues, but it could incur a manual build and testing step.
Systems such as RequireJS and SystemJS provide a library for loading and namespacing other JavaScript libraries at runtime. Modules are loaded using Ajax methods when required. The systems help, but could become complicated for larger code bases or sites adding standard <script>
tags into the mix.
Bundlers introduce a compile step so JavaScript code is generated at build time. Code is processed to include dependencies and produce a single ES5 cross-browser compatible concatenated file. Popular options include Babel, Browserify, webpack and more general task runners such as Grunt and Gulp.
A JavaScript build process requires some effort, but there are benefits:
The options above introduced a variety of competing module definition formats. Widely-adopted syntaxes included:
module.exports
and require
syntax used in Node.jsA single, native module standard was therefore proposed in ES6 (ES2015).
Everything inside an ES6 module is private by default, and runs in strict mode (there’s no need for 'use strict'
). Public variables, functions and classes are exposed using export
. For example:
// lib.js
export const PI = 3.1415926;
export function sum(...args) {
log('sum', args);
return args.reduce((num, tot) => tot + num);
}
export function mult(...args) {
log('mult', args);
return args.reduce((num, tot) => tot * num);
}
// private function
function log(...msg) {
console.log(...msg);
}
Alternatively, a single export
statement can be used. For example:
// lib.js
const PI = 3.1415926;
function sum(...args) {
log('sum', args);
return args.reduce((num, tot) => tot + num);
}
function mult(...args) {
log('mult', args);
return args.reduce((num, tot) => tot * num);
}
// private function
function log(...msg) {
console.log(...msg);
}
export { PI, sum, mult };
import
is then used to pull items from a module into another script or module:
// main.js
import { sum } from './lib.js';
console.log( sum(1,2,3,4) ); // 10
In this case, lib.js
is in the same folder as main.js
. Absolute file references (starting with /
), relative file references (starting ./
or ../
) or full URLs can be used.
Multiple items can be imported at one time:
import { sum, mult } from './lib.js';
console.log( sum(1,2,3,4) ); // 10
console.log( mult(1,2,3,4) ); // 24
and imports can be aliased to resolve naming collisions:
import { sum as addAll, mult as multiplyAll } from './lib.js';
console.log( addAll(1,2,3,4) ); // 10
console.log( multiplyAll(1,2,3,4) ); // 24
Finally, all public items can be imported by providing a namespace:
import * as lib from './lib.js';
console.log( lib.PI ); // 3.1415926
console.log( lib.add(1,2,3,4) ); // 10
console.log( lib.mult(1,2,3,4) ); // 24
At the time of writing, ES6 modules are supported in Chromium-based browsers (v63+), Safari 11+, and Edge 16+. Firefox support will arrive in version 60 (it’s behind an about:config
flag in v58+).
Scripts which use modules must be loaded by setting a type="module"
attribute in the <script>
tag. For example:
<script type="module" src="./main.js"></script>
or inline:
<script type="module">
import { something } from './somewhere.js';
// ...
</script>
Modules are parsed once, regardless of how many times they’re referenced in the page or other modules.
Modules must be served with the MIME type application/javascript
. Most servers will do this automatically, but be wary of dynamically generated scripts or .mjs
files (see the Node.js section below).
Regular <script>
tags can fetch scripts on other domains but modules are fetched using cross-origin resource sharing (CORS). Modules on different domains must therefore set an appropriate HTTP header, such as Access-Control-Allow-Origin: *
.
Finally, modules won’t send cookies or other header credentials unless a crossorigin="use-credentials"
attribute is added to the <script>
tag and the response contains the header Access-Control-Allow-Credentials: true
.
The <script defer>
attribute delays script execution until the document has loaded and parsed. Modules — including inline scripts — defer by default. Example:
<!-- runs SECOND -->
<script type="module">
// do something...
</script>
<!-- runs THIRD -->
<script defer src="c.js"></script>
<!-- runs FIRST -->
<script src="a.js"></script>
<!-- runs FOURTH -->
<script type="module" src="b.js"></script>
Browsers without module support won’t run type="module"
scripts. A fallback script can be provided with a nomodule
attribute which module-compatible browsers ignore. For example:
<script type="module" src="runs-if-module-supported.js"></script>
<script nomodule src="runs-if-module-not-supported.js"></script>
Browser support is growing, but it’s possibly a little premature to switch to ES6 modules. For the moment, it’s probably better to use a module bundler to create a script that works everywhere.
When Node.js was released in 2009, it would have been inconceivable for any runtime not to provide modules. CommonJS was adopted, which meant the Node package manager, npm, could be developed. Usage grew exponentially from that point.
A CommonJS module can be coded in a similar way to an ES2015 module. module.exports
is used rather than export
:
// lib.js
const PI = 3.1415926;
function sum(...args) {
log('sum', args);
return args.reduce((num, tot) => tot + num);
}
function mult(...args) {
log('mult', args);
return args.reduce((num, tot) => tot * num);
}
// private function
function log(...msg) {
console.log(...msg);
}
module.exports = { PI, sum, mult };
require
(rather than import
) is used to pull this module into another script or module:
const { sum, mult } = require('./lib.js');
console.log( sum(1,2,3,4) ); // 10
console.log( mult(1,2,3,4) ); // 24
require
can also import all items:
const lib = require('./lib.js');
console.log( lib.PI ); // 3.1415926
console.log( lib.add(1,2,3,4) ); // 10
console.log( lib.mult(1,2,3,4) ); // 24
So ES6 modules were easy to implement in Node.js, right? Er, no.
ES6 modules are behind a flag in Node.js 9.8.0+ and will not be fully implemented until at least version 10. While CommonJS and ES6 modules share similar syntax, they work in fundamentally different ways:
It would make no difference in the example above, but consider the following ES2015 module code:
// ES2015 modules
// ---------------------------------
// one.js
console.log('running one.js');
import { hello } from './two.js';
console.log(hello);
// ---------------------------------
// two.js
console.log('running two.js');
export const hello = 'Hello from two.js';
The output for ES2015:
running two.js
running one.js
hello from two.js
Similar code written using CommonJS:
// CommonJS modules
// ---------------------------------
// one.js
console.log('running one.js');
const hello = require('./two.js');
console.log(hello);
// ---------------------------------
// two.js
console.log('running two.js');
module.exports = 'Hello from two.js';
The output for CommonJS:
running one.js
running two.js
hello from two.js
Execution order could be critical in some applications, and what would happen if ES2015 and CommonJS modules were mixed in the same file? To resolve this problem, Node.js will only permit ES6 modules in files with the extension .mjs
. Files with a .js
extension will default to CommonJS. It’s a simple option which removes much of the complexity and should aid code editors and linters.
ES6 modules are only practical from Node.js v10 onwards (released in April 2018). Converting an existing project is unlikely to result in any benefit, and would render an application incompatible with earlier versions of Node.js.
For new projects, ES6 modules provide an alternative to CommonJS. The syntax is identical to client-side coding, and may offer an easier route to isomorphic JavaScript, which can run in the either the browser or on a server.
A standardized JavaScript module system took many years to arrive, and even longer to implement, but the problems have been rectified. All mainstream browsers and Node.js from mid 2018 support ES6 modules, although a switch-over lag should be expected while everyone upgrades.
Learn ES6 modules today to benefit your JavaScript development tomorrow.
#es6 #javascript #webdev
1649418120
grunt-es6-module-transpiler
A Grunt task for processing ES6 module import/export syntax into one of AMD, CommonJS, YUI or globals using the es6-module-transpiler. Also allows you to temporarily enable ES6 modules for other tasks.
This plugin requires Grunt ~0.4.1
If you haven't used Grunt before, be sure to check out the Getting Started guide, as it explains how to create a Gruntfile as well as install and use Grunt plugins. Once you're familiar with that process, you may install this plugin with this command:
npm install grunt-es6-module-transpiler --save-dev
To use add the transpile
task to your Grunt configuration.
grunt.loadNpmTasks('grunt-es6-module-transpiler');
grunt.initConfig({
transpile: {
main: {
type: "cjs", // or "amd" or "yui"
files: [{
expand: true,
cwd: 'lib/',
src: ['**/*.js'],
dest: 'tmp/'
}]
}
}
});
grunt.loadNpmTasks('grunt-es6-module-transpiler');
grunt.initConfig({
transpile: {
main: {
type: "globals",
imports: { bar: "Bar" },
files: {
'tmp/globals.js': ['test/fixtures/input.js'],
'tmp/globals-bar.js': ['test/fixtures/bar.js']
}
}
}
});
Manually run the task with grunt transpile
or include it as part of your build task:
grunt.registerTask('build', ['clean', 'transpile', '...']);
The module transpiler forces strict mode; there is no option to turn this off. If, like me, you typically use Mocha with Chai, this can cause a problem because Chai attempts to access arguments.callee
, which violates strict mode. I switched to using expect.js and it works great.
In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using Grunt.
10/07/2013 v0.5.0 - Support for v0.3.0 of es6-module-transpiler; removes transpile:enable task as the feature no longer exists 07/09/2013 v0.4.1 - Improved windows support when using amd 07/09/2013 v0.4.0 - Update to v0.2.0 of es6-module-transpiler for new syntax support 05/28/2013 v0.3.0 - Add callback for dynamically specifying AMD modulename 05/02/2013 v0.2.0 - Fixes for globals, CoffeeScript, transpile:enable task for node scripts 04/17/2013 v0.1.0 - Initial release, supports basic transpile task
Author: joefiorini
Source Code: https://github.com/joefiorini/grunt-es6-module-transpiler
License: MIT License
1649347152
es6-module-transpiler-brunch
Adds ES6 module syntax to Brunch based on Square's es6-module-transpiler.
ES6 Module Transpiler is an experimental compiler that allows you to write your JavaScript using a subset of the current ES6 module syntax, and compile it into AMD or CommonJS modules.
Install the plugin via npm with npm install --save es6-module-transpiler-brunch
.
Or, do manual install:
"es6-module-transpiler-brunch": "x.y.z"
to package.json
of your brunch app."es6-module-transpiler-brunch": "git+ssh://git@github.com:gcollazo/es6-module-transpiler-brunch.git"
.Again, this syntax is in flux and is closely tracking the module work being done by TC39.
There are two types of exports. Named exports like the following:
// foobar.js
var foo = "foo", bar = "bar";
export { foo, bar };
This module has two named exports, foo
and bar
.
You can also write this form as:
// foobar.js
export var foo = "foo";
export var bar = "bar";
Either way, another module can then import your exports like so:"
import { foo, bar } from "foobar";
console.log(foo); // "foo"
You can also export a default export. For example, an ES6ified jQuery might look like this:
// jquery.js
var jQuery = function() {};
jQuery.prototype = {
// ...
};
export default = jQuery;
Then, an app that uses jQuery could import it with:
import $ from "jquery";
The default export of the "jquery" module is now aliased to $
.
A default export makes the most sense as a module's "main" export, like the jQuery
object in jQuery. You can use default and named exports in parallel.
module
Whereas the import
keyword imports specific identifiers from a module, the module
keyword creates an object that contains all of a module's exports:
module foobar from "foobar";
console.log(foobar.foo); // "foo"
In ES6, this created object is read-only, so don't treat it like a mutable namespace!
import "foo";
A "bare import" that doesn't import any identifiers is useful for executing side effects in a module. For example:
// alerter.js
alert("alert! alert!");
// alertee.js
import "alerter"; // will pop up alert box
The plugin will take all files ending in *.js
under the app
directory and pass them through the es6-module-transpiler
and compiled as CommonJS modules.
The plugin has two configuration options you can add to your project's config.coffee
: match
which is a regex used to decide what files to compile and debug
which will console.log
debugging info when the plugin runs.
exports.config =
es6ModuleTranspiler:
match: /^app/
debug: yes
Author: Gcollazo
Source Code: https://github.com/gcollazo/es6-module-transpiler-brunch
License: MIT License
1649365860
gulp-es6-module-transpiler
Gulp plugin for the ES6 Module Transpiler
npm install gulp-es6-module-transpiler
var transpile = require('gulp-es6-module-transpiler');
gulp.task('build', function() {
return gulp.src('src/**/*.js')
.pipe(transpile({
formatter: 'bundle'
}))
.pipe(gulp.dest('lib'));
})
var sourcemaps = require('gulp-sourcemaps');
var transpile = require('gulp-es6-module-transpiler');
gulp.task('build', function() {
return gulp.src('src/**/*.js')
.pipe(sourcemaps.init())
.pipe(transpile({
formatter: 'bundle'
}))
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('lib'));
})
formatter
String|Formatter|Formatter constructor
[optional]
Name of built-in formatter, formatter instance of formatter constructor function. Controls the output format of transpiler scripts. All built-in formatters are available as formatters
property of required module require('gulp-es6-module-transpiler').formatters
.
Defaults to es6-module-transpiler default formatter.
Important es6-module-transpiler version 0.9.x supports bundle
and commonjs
formatters only. To support AMD format, please use es6-module-transpiler-amd-formatter.
basePath
String
[optional]
All module names will be resolved and named relatively to this path.
Defaults to process.cwd()
.
importPaths
Array<String>
[optional]
Array of path that will be used to resolve modules.
Defaults to [ options.basePath ]
.
sourceMaps
Boolean
[optional]
If set to false
, sourceMappingURL is not appended to transpiled files and source maps are not applied. Defaults to true
.
Author: Ryanseddon
Source Code: https://github.com/ryanseddon/gulp-es6-module-transpiler
License: MIT License