- main.js
javascript
import { bar } from "./module1";
import module2 from "./module2";
bar()
module2()
- module1.js
javascript
// 多变量导出,导入变量需要变量名一对一映射
export const module1='module1'
export function bar(params) {
console.log(module1)
}
- module2.js
javascript
// 默认导出任何数据类型,导入变量名可随机取名
export default function bar(){
console.log('bar module2');
}
- package.json 和babel.config.json
javascript
{
"name": "es6",
"version": "1.0.0",
"description": "",
"main": "main.js",
"scripts": {
"compile": "babel js --out-dir lib && browserify -e ./lib/main.js -o ./dist/boundle.js"
},
"author": "",
"license": "ISC",
"devDependencies": {
"@babel/cli": "^7.22.15",
"@babel/core": "^7.22.15",
"@babel/preset-env": "^7.22.15"
}
}
{
"presets": [
[
"@babel/preset-env",
{
"targets": {
"edge": "17",
"firefox": "60",
"chrome": "67",
"safari": "11.1"
},
"useBuiltIns": "usage",
"corejs": "3.6.5"
}
]
]
}
- index.html中使用编译之后的js
javascript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>es6</title>
</head>
<body>
</body>
<script src="./dist/boundle.js"></script>
</html>
note:
babel js --out-dir lib && browserify -e ./lib/main.js -o
./dist/boundle.js script中的compile命令,使用管道符&&串联命令。
先使用babel转换es6语法(名为env的preset),再使用browserify编译代码