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,你可以隨意更改主入口文件

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM