美文网首页
ES6的开发环境搭建

ES6的开发环境搭建

作者: 莫言_jc | 来源:发表于2018-06-23 14:01 被阅读0次

由于有些低版本的浏览器还不支持ES6的语法,所以在不使用框架的情况下,需要将ES6语法转换为ES5语法
下面我在VS Code操作的所有命令
项目目录

项目目录

一,先创建一个项目,项目中有两个文件夹,src和dist,一个html文件

  • src:将编写的ES6的js文件放到此文件夹中(这里是index.js文件)
  • dist:将通过Babel编译成的ES5的js文件放到此文件中(这里是index.js文件)
  • html:注意:将dist中编译好的文件引入到HTML文件中,而不是src中的js文件
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title></title>
</head>
<script src="./dist/index.js"></script>
<body>
    EXMA Script 6
</body>
</html>

二,搭建环境

1, 在项目的根目录初始化项目并生成package.json文件(可以根据自己的需求进行修改)

cnpm init -y

{
  "name": "es6",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

2,安装Babel插件(将ES6语法转换为ES5)

cnpm install -g babel-cli

3, 当然现在还不能正常转换,还需要安装ES5所需的一个包

cnpm install --save-dev babel-preset-es2015 babel-cli
安装完成后,package.json会有所变化

{
  "name": "es6",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-preset-es2015": "^6.24.1"
  }
}

4, 在项目的根目录添加一个 .babelrc 文件,并添加内容

{
    "presets":[
        "es2015"
    ],
    "plugins": []
}

5,安装完成后我们可以通过命令进行转换

babel src/index.js -o dist/index.js

6,当然我们可以将命令进行简化(package.json进行配置)

"scripts": {
"test": "echo "Error: no test specified" && exit 1"
},

{
  "name": "es6",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "babel src/index.js -o dist/index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-preset-es2015": "^6.24.1"
  }
}

然后我们可以通过 npm run test 转义代码

声明:本文摘抄于别的文献,只用于自己的一个快速搭建

相关文章

网友评论

      本文标题:ES6的开发环境搭建

      本文链接:https://www.haomeiwen.com/subject/vaqlyftx.html