search
HomeWeb Front-endFront-end Q&AWhy does the mini program need to convert es6 to es5?

For browser compatibility. As a new specification for JS, ES6 adds a lot of new syntax and API. However, modern browsers do not have high support for the new features of ES6, so ES6 code needs to be converted to ES5 code. In the WeChat web developer tools, babel is used by default to convert the developer's ES6 syntax code into ES5 code that is well supported by all three terminals, helping developers solve development problems caused by different environments; you only need to configure the check box Just use the "ES6 to ES5" option.

Why does the mini program need to convert es6 to es5?

The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.

The reason why the applet converts es6 to es5

Reason: For browser compatibility, and for node. js environment can run the application smoothly .

As a new specification for JS, ES6 adds a lot of new syntax and API. However, modern browsers do not have high support for the new features of ES6, so if you want to use the new features of ES6 directly in the browser, Features must be implemented with the help of other tools. To convert ES6 code to ES5 code, just need to install and configure the Babel tool in the project.

In the node.js environment, node’s support for ES6 has been criticized. It was only after version 13 that the module mode was introduced (add a sentence to package.json: "type": "module"), but some libraries still do not support ES6 syntax. Therefore, if your node.js program does not recognize ES6 syntax, please use Babel to transcode it, which may solve the problem.

Convert es6 to es5 in the mini program

##In the development tools of 0.10.101000 and later versions, it will Babel is used by default to convert the developer's ES6 syntax code into ES5 code that is well supported by all three terminals, helping developers solve development problems caused by different environments.

In the project, just check the ES6 to ES5 option

Why does the mini program need to convert es6 to es5?

It should be noted that:

In order to improve code quality, when the ES6 conversion function is turned on, the javasctipt strict mode is enabled by default. Please refer to "use strict"

What is Babel?

Babel is an ES6 transcoder that can convert ES6 code into ES5 code, so that older browsers that do not originally support ES6 can execute ES6 code, Example: ES6 arrow function Code example:

// 转码前:使用了ES6箭头函数
items.map(item => item + 1);

// 转码后:转为了普通函数
items.map(function (item) {
  return item + 1;
});

How to convert es6 to es5?

Use babel to convert es6 to es5.

Below we write out the process of using Babel on the command line so that you can understand the entire translation process.

1. Install Babel’s command line tool in the project

$ npm install -D babel-cli

2. Prepare ES6 code

Usually we The source code is placed in the src directory. If you do not have ready-made ES6 code, create one in the src directory:

// src/example.js

class Hello {

  static world() {

    console.log('Hello, World!');

  }

}

Hello.world();

3. Configure Babel

Babel Yes Transpiles code via plugins and presets (so it can transpile more than just ES6). In order to translate ES6 to ES5, we only need to configure the env default value and install this plug-in:

$ npm install -D babel-preset-env
We also need a configuration file, create the file in the project root directory:

.babelrc. , the content is as follows: This file is used to set transcoding rules and plug-ins. The basic format is as follows.

// .babelrc

{

  "presets": [],

  "plugins": []

}

Why does the mini program need to convert es6 to es5?

Note that .babelrc. has a dot before and after it, so that it can be saved successfully

presets field

The presets field sets the transcoding rules. The following official rule sets are provided. You can install them as needed.

Latest transcoding rules
$ npm install --save-dev @babel/preset-env

react transcoding rules
$ npm install --save-dev @babel/preset-react

Then, add these rules. babelrc. Code example:

  {

    "presets": [

      "@babel/env",

      "@babel/preset-react"

    ],

    "plugins": []

  }

Note that before using all Babel tools and modules below, .babelrc must be written first.

Command line transcoding and transcoding rules

Babel provides the command line tool @babel/cli for command line transcoding.

Its installation command is as follows.

$ npm install --save-dev @babel/cli
The basic usage is as follows.

# 转码结果输出到标准输出
$ babel test.js
 
# 转码结果写入一个文件
# --out-file 或 -o 参数指定输出文件
$ babel a.js --out-file b.js
# 或者
$ babel a.js -o b.js
 
# 整个目录转码
# --out-dir 或 -d 参数指定输出目录
$ babel src --out-dir lib
# 或者
$ babel src -d lib
 
# -s 参数生成source map文件
$ babel src -d lib -s

Use the babel-node command to get the REPL environment transcoding

@babel/node module’s babel-node command provides a REPL environment that supports ES6 . It supports all the features of Node's REPL environment and can run ES6 code directly.

First, install this module.

$ npm install --save-dev @babel/node
Then, execute babel-node to enter the REPL environment.

@babel/register module
$ npx balel-node

@babel/register module rewrites the require command and adds a hook to it. From then on, whenever you use require to load files with .js, .jsx, .es and .es6 suffixes, they will be transcoded with Babel first.

$ npm install --save-dev @babel/register

使用时,必须首先加载@babel/register。

// index.js

require('@babel/register');

require('./es6.js');

然后,就不需要手动对index.js转码了。

$ node index.js

需要注意的是,@babel/register只会对require命令加载的文件转码,而不会对当前文件转码。另外,由于它是实时转码,所以只适合在开发环境使用。

浏览器环境

Babel 也可以用于浏览器环境,使用@babel/standalone模块提供的浏览器版本,将其插入网页。

<script></script>

<script>

// Your ES6 code

</script>

注意,网页实时将 ES6 代码转为 ES5,对性能会有影响。生产环境需要加载已经转码完成的脚本。

【推荐学习:javascript视频教程

The above is the detailed content of Why does the mini program need to convert es6 to es5?. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
CSS IDs vs Classes: which is better for accessibility?CSS IDs vs Classes: which is better for accessibility?May 10, 2025 am 12:02 AM

Classesarebetterforaccessibilityinwebdevelopment.1)Classescanbeappliedtomultipleelements,ensuringconsistentstylesandbehaviors,whichaidsuserswithdisabilities.2)TheyfacilitatetheuseofARIAattributesacrossgroupsofelements,enhancinguserexperience.3)Classe

CSS: Understanding the Difference Between Class and ID SelectorsCSS: Understanding the Difference Between Class and ID SelectorsMay 09, 2025 pm 06:13 PM

Classselectorsarereusableformultipleelements,whileIDselectorsareuniqueandusedonceperpage.1)Classes,denotedbyaperiod(.),areidealforstylingmultipleelementslikebuttons.2)IDs,denotedbyahash(#),areperfectforuniqueelementslikeanavigationmenu.3)IDshavehighe

CSS Styling: Choosing Between Class and ID SelectorsCSS Styling: Choosing Between Class and ID SelectorsMay 09, 2025 pm 06:09 PM

In CSS style, the class selector or ID selector should be selected according to the project requirements: 1) The class selector is suitable for reuse and is suitable for the same style of multiple elements; 2) The ID selector is suitable for unique elements and has higher priority, but should be used with caution to avoid maintenance difficulties.

HTML5: LimitationsHTML5: LimitationsMay 09, 2025 pm 05:57 PM

HTML5hasseverallimitationsincludinglackofsupportforadvancedgraphics,basicformvalidation,cross-browsercompatibilityissues,performanceimpacts,andsecurityconcerns.1)Forcomplexgraphics,HTML5'scanvasisinsufficient,requiringlibrarieslikeWebGLorThree.js.2)I

CSS: Is one style more priority than another?CSS: Is one style more priority than another?May 09, 2025 pm 05:33 PM

Yes,onestylecanhavemoreprioritythananotherinCSSduetospecificityandthecascade.1)Specificityactsasascoringsystemwheremorespecificselectorshavehigherpriority.2)Thecascadedeterminesstyleapplicationorder,withlaterrulesoverridingearlieronesofequalspecifici

What are the significant goals of the HTML5 specification?What are the significant goals of the HTML5 specification?May 09, 2025 pm 05:25 PM

ThesignificantgoalsofHTML5aretoenhancemultimediasupport,ensurehumanreadability,maintainconsistencyacrossdevices,andensurebackwardcompatibility.1)HTML5improvesmultimediawithnativeelementslikeand.2)ItusessemanticelementsforbetterreadabilityandSEO.3)Its

What are the limitations of React?What are the limitations of React?May 02, 2025 am 12:26 AM

React'slimitationsinclude:1)asteeplearningcurveduetoitsvastecosystem,2)SEOchallengeswithclient-siderendering,3)potentialperformanceissuesinlargeapplications,4)complexstatemanagementasappsgrow,and5)theneedtokeepupwithitsrapidevolution.Thesefactorsshou

React's Learning Curve: Challenges for New DevelopersReact's Learning Curve: Challenges for New DevelopersMay 02, 2025 am 12:24 AM

Reactischallengingforbeginnersduetoitssteeplearningcurveandparadigmshifttocomponent-basedarchitecture.1)Startwithofficialdocumentationforasolidfoundation.2)UnderstandJSXandhowtoembedJavaScriptwithinit.3)Learntousefunctionalcomponentswithhooksforstate

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use