In the world of web development, transpiling is a key process that allows you to write modern code while maintaining compatibility with a variety of environments and browsers. In simple terms, transpiling converts code written in a newer or more advanced version of a language into an older or more compatible version with older browsers and environments.
Difference between Transpiling and Compiling
Although they are often confused, transpiling and compiling are distinct concepts:
- Compiling: Translates source code from a high-level language (such as C or Java) to executable machine code.
- Transpiling: Translates code from one version of a language to another version or from a similar language to an equivalent one, while maintaining readability and compatibility (for example, from ES6 to ES5 in JavaScript or from TypeScript to JavaScript).
🔗 Do you like Techelopment? Check out the site for all the details!
What is Transpiling Used For?
Transpiling is particularly useful in these contexts:
- JavaScript: It is used to convert modern code (ES6 or higher) into JavaScript compatible with older browsers. With the introduction of new ECMAScript specifications (ES6, ES7, etc.), many features are not supported by all browsers, so transpiling solves compatibility issues.
- TypeScript and JSX: In the case of TypeScript, a superset of JavaScript that adds support for static types, it is transpiled into standard JavaScript. Similarly, JSX, a syntax used in React to write components, is transpiled into JavaScript.
- CSS: For stylesheets, transpiling converts code written in pre-processors like Sass or Less into standard CSS that all browsers can interpret.
Transpiling in JavaScript, TypeScript and JSX
ECMAScript and New Features
With each ECMAScript release (ES6, ES7, ES8…), new features are introduced that make the work of developers easier:
- Classes, modules, arrow functions
- Template literals (to handle multi-line strings)
- Async/Await for asynchronous code management
Not all browsers support these features out of the box, so transpiling from ES6 to ES5 is often necessary to ensure that the code works everywhere.
TypeScript and JSX
Transpiling is essential for:
- TypeScript: Adds static types to JavaScript, improving maintainability and reducing bugs. TypeScript is transpiled to JavaScript (usually ES5 or ES6) because browsers cannot run TypeScript directly.
- JSX: Used in React, JSX is an HTML-like syntax for writing React components. It is transpiled to regular JavaScript.
TypeScript example:
let message: string = "Hello, TypeScript!";
console.log(message);
After transpiling it becomes JavaScript:
var message = "Hello, TypeScript!";
console.log(message);
JSX Example:
const element = <h1>Hello, JSX!</h1>;
After transpiling, it becomes JavaScript:
const element = React.createElement("h1", null, "Hello, JSX!");
Most Used JavaScript Transpiling Tools
Babel is one of the most popular and versatile JavaScript transpilers. Babel converts modern JavaScript (ES6+) code into a version compatible with older environments. It is configurable via plugins to handle advanced and specific features.
Let's see now how to integrate Babel into Gulp in order to have an integrated environment in case we need to perform, in addition to transpiling, other tasks such as minification.
Gulp as a Transpiling Tool
Gulp is one of the most popular and flexible task runners to automate the build process in web projects. You can use it to handle transpiling of JavaScript, TypeScript, JSX and CSS, among other things. Unlike Webpack, which is a bundler, Gulp focuses on automating tasks such as transpiling, minification, concatenation and much more.
How to Configure Gulp for JavaScript, TypeScript and JSX Transpiling
Here is an example of configuring Gulp for JavaScript (ES6), TypeScript and JSX transpiling:
Install Gulp and the necessary dependencies:
npm install --save-dev gulp gulp-babel @babel/core @babel/preset-env gulp-typescript gulp-sourcemaps
Create a gulpfile.js
file:
const gulp = require('gulp');
const babel = require('gulp-babel');
const sourcemaps = require('gulp-sourcemaps');
const ts = require('gulp-typescript');
// Task for transpiling modern JavaScript (ES6+) to ES5
gulp.task('transpile-js', () =>
gulp.src('src/**/*.js') // Source code path
.pipe(sourcemaps.init())
.pipe(babel({
presets: ['@babel/preset-env'] // Set the ECMAScript versions to use
}))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('dist')) // Destination of transpiled code
);
// Task for transpiling TypeScript to JavaScript
gulp.task('transpile-ts', () => {
return gulp.src('src/**/*.ts')
.pipe(sourcemaps.init())
.pipe(ts({
noImplicitAny: true,
target: 'ES5' // Transpiling engine target
}))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('dist'));
});
// JSX transpiling task
gulp.task('transpile-jsx', () => {
return gulp.src('src/**/*.jsx')
.pipe(sourcemaps.init())
.pipe(babel({
presets: ['@babel/preset-react', '@babel/preset-env']
}))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('dist'));
});
// Default task to perform all transpiling
gulp.task('default', gulp.parallel('transpile-js', 'transpile-ts', 'transpile-jsx'));
Before going further, let's look at some steps in detail::
.pipe(sourcemaps.init()): This step starts the creation of:
sourcemaps for the processed files.
- Sourcemaps: When you transpile JavaScript code, the source code is transformed (for example, from ES6 to ES5), which makes debugging more difficult. Sourcemaps connect the original source code (ES6) with the transformed code (ES5), allowing browser development tools to show you the original source while debugging.
- The
.init()
method tells Gulp to start tracking changes to connect the modified code to the original code.
.pipe(babel(…)): This step runs Babel, the JavaScript transpiler, which converts ES6 (or higher) code to a compatible version, such as ES5:
- babel(): Runs the Babel function to process the code.
- presets: Specifies a set of default settings for Babel, which tell Babel how to transcribe the code.
-
'@babel/preset-env'
: This preset tells Babel to automatically use the ECMAScript version that best suits the context. For example, it can transcribe ES6, ES7, etc., to ES5 if necessary.preset-env
evaluates the code features based on the target browser support (which can be defined in the configurations, for example withbrowserslist
).
.pipe(sourcemaps.write('.')): This step writes the generated source map to the same directory as the output file (. indicates the current directory).
- This allows you to associate the transpiled JavaScript file with its original version during debugging.
- If the JavaScript file is
dist/main.js
, Gulp will also generate amain.js.map
file, which contains the information needed for debugging.
Finally, run the transpiling: To perform the transpiling, just use the command:
gulp
This command will transpile JavaScript (ES6), TypeScript, and JSX files into their compatible versions (ES5 for JavaScript and standard JavaScript for TypeScript and JSX).
CSS Transpiling
For CSS, tools like Sass or Less add advanced features that improve standard CSS. However, to make your code usable in browsers, you need to transpile it into standard CSS.
Sass Transpiling Example
Here's how to set up a transpiling process for Sass files into CSS with Gulp:
Install the necessary dependencies:
npm install --save-dev gulp-sass sass gulp-sourcemaps
Aggiungi il task per Sass a gulpfile.js
:
const sass = require('gulp-sass')(require('sass'));
gulp.task('transpile-sass', () => {
return gulp.src('src/**/*.scss')
.pipe(sourcemaps.init())
.pipe(sass().on('error', sass.logError))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('dist'));
});
To perform Sass transpilation:
gulp transpile-sass
Transpiling Tools and Workflow
In addition to Gulp, there are several tools that make transpiling easy:
- Webpack: Although primarily a bundler, Webpack can be configured for transpiling using loaders such as babel-loader for JavaScript and sass-loader for CSS.
- Parcel: Another modern bundler that includes automatic transpiling and support for many technologies.
Did you know about transpiling?
In this article, we learned what transpiling is and how it is a fundamental technique to ensure that code written in modern JavaScript, TypeScript, JSX or advanced CSS is compatible with different environments, especially older browsers.
Furthermore, using tools such as Gulp, you can automate the transpiling process, making it easier to manage advanced code, without sacrificing compatibility.
Whether you are working with ES6, TypeScript, JSX or Sass, transpiling allows you to use all the modern features while ensuring that your code is compatible with potentially obsolete or outdated systems used by your users.
Follow me #techelopment
Official site: www.techelopment.it
Medium: @techelopment
Dev.to: Techelopment
facebook: Techelopment
instagram: @techelopment
X: techelopment
telegram: @techelopment_channel
youtube: @techelopment
whatsapp: Techelopment
References
URL