function log(o) {
console.log(o);
}
module.exports = log;
es6_const_let_node_demo.js
// 在 Node 中使用模块的正确姿势:
const log = require("./lib/util_for_node");
// ES5
var a = 1;
a = a + 1;
log(a); // 2
// ES6
const b = 1;
// b = b + 1; // error : TypeError: Assignment to constant variable.
log(b);
// ES6
let c = 1;
c = c + 1;
log(c);
运行测试:
$ node es6_const_let_node_demo.js
2
1
2
方法2 使用万能变换器:babel
util_for_babel.js
function log(o) {
console.log(o);
}
export {log}
es6_const_let_babel_demo.js
import {log} from "./lib/util_for_babel";
/**
node: module.exports和require
es6:export和import
nodejs仍未支持import/export语法,需要安装必要的npm包–babel,使用babel将js文件编译成node.js支持的commonjs格式的代码。
因为一些历史原因,虽然 Node.js 已经实现了 99% 的 ES6 新特性,不过截止 2018.8.10,How To Enable ES6 Imports in Node.JS 仍然是老大难问题
借助 Babel
1.下载必须的包
npm install babel-register babel-preset-env --D
命令行执行:
babel-node es6_const_let_babel_demo.js
*
* @type {number}
*/
// ES5
var a = 1;
a = a + 1;
log(a); // 2
// ES6
const b = 1;
// b = b + 1; // error : TypeError: Assignment to constant variable.
log(b);
// ES6
let c = 1;
c = c + 1;
log(c);
上面的代码,直接 node 命令行运行是要报错的:
$ node es6_const_let_babel_demo.js
/Users/jack/WebstormProject/node-tutorials/hello-node/es6_const_let_babel_demo.js:1
(function (exports, require, module, __filename, __dirname) { import {log} from "./lib/util_for_babel";
^
SyntaxError: Unexpected token {
at new Script (vm.js:79:7)
at createScript (vm.js:251:10)
at Object.runInThisContext (vm.js:303:10)
at Module._compile (internal/modules/cjs/loader.js:656:28)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:699:10)
at Module.load (internal/modules/cjs/loader.js:598:32)
at tryModuleLoad (internal/modules/cjs/loader.js:537:12)
at Function.Module._load (internal/modules/cjs/loader.js:529:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:741:12)
at startup (internal/bootstrap/node.js:285:19)
/**
* 注意到这里的源码文件的后缀 .mjs
* @param o
*/
function log(o) {
console.log(o);
}
export {log};
es6_const_let_node_exp_demo.mjs
import {log} from "./lib/util_for_node_exp";
// ES5
var a = 1;
a = a + 1;
log(a); // 2
// ES6
const b = 1;
// b = b + 1; // error : TypeError: Assignment to constant variable.
log(b);
// ES6
let c = 1;
c = c + 1;
log(c);
/**
* 源码后缀 .mjs
*/
import Koa from 'koa';
import { render } from './lib/render.js';
import data from './lib/data.json';
let app = new Koa();
app.use((ctx, next) => {
let view = ctx.url.substr(1);
let content;
if ( view === 'data' ) {
content = data;
} else {
content = render(view);
}
ctx.body = content;
})
app.listen(3000, ()=>{
console.log('the modules test server is starting');
});