es6 - 导入导出

今天用node纠结了半天,明明是正确的语法,一直报错,原来node和chrome并不支持es6语法....

 

1. npm install

package.json

 1 {
 2     "name": "ES6",
 3     "version": "1.0.0",
 4     "description": "",
 5     "main": "export.js",
 6     "dependencies": {
 7         "babel": "^6.23.0",
 8         "babel-cli": "^6.26.0",
 9         "babel-preset-es2015": "^6.24.1"
10     },
11     "devDependencies": {
12         "babel-core": "^6.26.3",
13         "babel-register": "^6.26.0"
14     },
15     "scripts": {
16         "test": "echo \"Error: no test specified\" && exit 1"
17     },
18     "keywords": [],
19     "author": "",
20     "license": "ISC"
21 }
View Code

 

2.创建index.js

index.js

1 require('babel-register');
2 require('./import.js');

 

3.创建import.js 也就相当于 import 导入

import.js

// 1.导入函数和变量
import { calc, name } from './export';

// 2. 可以使用别名 (多个之间可以用逗号隔开)
import { calc as calcs, name } from './export';

console.log(calcs(1, 2), name);

 

4.创建export.js 导出函数、变量、等...

export.js

1 // 1.name  - 第一种导出方式
2 export var name = 'bat';
3 
4 // 2.function - 第二种导出方式
5 function calc(x, y) {
6     return x * y;
7 }
8 
9 export { calc };

 

5.创建.babelrc文件

.babelrc

1 {
2     "presets": [
3         "es2015"
4     ],
5     "plugins": [
6 
7     ]
8 }

 

 

文件目录结构 除了.babelrc必须放在根目录,其它随意

 

 

默认主入口文件是index.js,你可以随意更改主入口文件

 

 

 

posted @ 2018-07-21 10:53  Sunsin  阅读(2344)  评论(0编辑  收藏  举报