一、CommonJS
method.js
let sum = (a,b)=>a+b;
function myFun(a){
return a;
}
module.exports = {
sum,
myFun
};
hello.js
let method = require("./method.js");
console.log(method.myFun(1));
console.log(method.sum(1,2));
二、ES6
注:由于可能不支持ES6语法,所以需要事先
下载babel
npm install -g babel-cli
# .babelrc
{
"presets":["es2015"],
"plugins":[]
}
"dev":"babel src -d dist"
npm run dev
运行时运行dist目录下的对应文件
1.普通型
userApi.js
export function mul(a,b){
return a*b;
}
export function sayBye(){
console.log("ByeBye!");
}
use.js
import {mul,sayBye} from './userApi';
sayBye();
2.日用型
userApi.js
export default{
mul(a,b){
return a*b;
},
sayBye(){
console.log("ByeBye!");
}
}
use.js
import user from './userApi';
user.sayBye();