User Tools

Site Tools


java-script:babel

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
java-script:babel [2023/08/03 02:43] odeftajava-script:babel [2023/08/03 03:09] (current) odefta
Line 15: Line 15:
  
 ===== Install babel packages for a project ===== ===== Install babel packages for a project =====
 +
 +This will create a **node-modules** folder containing a lot of modules:
  
 <code> <code>
Line 20: Line 22:
 </code> </code>
  
 +Output:
 +<code>
 +added 248 packages, and audited 249 packages in 40s
  
 +58 packages are looking for funding
 +  run `npm fund` for details
  
 +found 0 vulnerabilities
 +</code>
 +
 +==== Create .babelrc ====
 +
 +Inside your project in the main directory create a file called **.babelrc**. \\
 +This will indicate babel which presets to use to transpile the ES6 code in ES5 code:
 +
 +<code javascript .babelrc>
 +{
 +    "presets": ["@babel/preset-env"]
 +}
 +</code>
 +
 +===== Run our transpiled code (from ES6 to ES5) =====
 +
 +This command will transpile and run the code on the fly:
 +
 +<code>
 +npx babel-node ./src/index.js
 +</code>
 +
 +If the program has some arguments:
 +
 +<code>
 +npx babel-node ./src/index.js 5 5
 +</code>
 +
 +===== View transpiled code =====
 +
 +If we want to examine the transpiled code, we'll need to install the babel command line:
 +
 +<code>
 +npm install @babel/cli
 +</code>
 +
 +Output:
 +<code>
 +added 29 packages, and audited 278 packages in 5s
 +
 +61 packages are looking for funding
 +  run `npm fund` for details
 +
 +found 0 vulnerabilities
 +</code>
 +
 +Next, add a script entry in the package.json file:
 +
 +<code javascript>
 +{
 +  "scripts": {
 +    "build": "babel src -d dist"
 +  }
 +}
 +</code>
 +
 +Next, we can run:
 +<code>
 +npm run build
 +</code>
 +
 +Transpiled code are now in the dist folder:
 +<code>
 +
 +> build
 +> babel src -d dist
 +
 +Successfully compiled 2 files with Babel (423ms).
 +</code>
java-script/babel.1691019826.txt.gz · Last modified: 2023/08/03 02:43 by odefta