Tôi đang học tiêu chuẩn ES6 vì vậy tôi bắt đầu từ một mã ví dụ rất cơ bản.Công việc xuất/nhập trong ES6 như thế nào?
file đầu tiên của tôi là Rectangle.js
class Rectangle {
perimeter(x, y) {
return (2 * (x + y));
}
area(x, y) {
return (x * y);
}
}
export default class { Rectangle };
Và trong một tập tin solve-1.js
, tôi có một số hàng nhập khẩu như thế này
import Rectangle from './Rectangle';
function solveRect(l, b) {
if (l < 0 || b < 0) {
console.log(`Rectangle dimensions should be greater than zero: l = ${l} and b = ${b}`);
} else {
console.log(Rectangle.area(l, b));
}
}
solveRect(2, 4);
Tôi đang sử dụng babel-nút để chạy chương trình này, tôi đã yêu cầu cài đặt trước, .babelrc
chứa
{
"presets": [
"es2015",
"react",
"stage-2"
],
"plugins": []
}
Các báo cáo thông tin lỗi là
/Users/Kulbear/Desktop/NodeBear/Basic/solve-1.js:13
console.log(_Rectangle2.default.area(l, b));
^
TypeError: _Rectangle2.default.area is not a function
at solveRect (solve-1.js:7:27)
at Object.<anonymous> (solve-1.js:12:1)
at Module._compile (module.js:541:32)
at loader (/usr/local/lib/node_modules/babel-cli/node_modules/babel-register/lib/node.js:148:5)
at Object.require.extensions.(anonymous function) [as .js] (/usr/local/lib/node_modules/babel-cli/node_modules/babel-register/lib/node.js:158:7)
at Module.load (module.js:458:32)
at tryModuleLoad (module.js:417:12)
at Function.Module._load (module.js:409:3)
at Function.Module.runMain (module.js:575:10)
at /usr/local/lib/node_modules/babel-cli/lib/_babel-node.js:160:24
Edit:
$ node --version
> v6.3.1
Might hữu ích khi đọc một số tài liệu về các tính năng mới của ES6, ví dụ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes. –