在 ES6 转译器中导入/导出

import / export in ES6 Transpilers

This is not a duplicate of below questions which is dealing with browser specific questions. I'm expecting an answer whether import / export will work in Client side or not.

//lib.js

export const sqrt = Math.sqrt;
export function square(x) {
    return x * x;
}
export function diag(x, y) {
    return sqrt(square(x) + square(y));
}
  
//main.js
  
"use strict";

import { square, diag } from 'lib';
console.log(square(11)); // 121
console.log(diag(4, 3)); // 5
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Import Check</title>
</head>
<body>
<script type="text/javascript" src="main.js"></script>
</body>
</html>

Error that I'm getting in Chrome:

Tested Browser: Google Chrome Version 47.0.2526.106

  1. 是否可以使代码在任何浏览器中运行?
  2. 比方说,我们选择了一个转译器 (BabelJS) 并转译了代码。 import / export 文件代码片段将在客户端或服务器端工作(在节点服务器中作为 require 方法)?

MDN

Note: This feature is not implemented in any browsers natively at this time. It is implemented in many transpilers, such as the Traceur Compiler, Babel or Rollup.

例如,在您的代码片段上使用 babel 后,您将得到如下内容:

//lib.js

"use strict";

Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.square = square;
exports.diag = diag;
var sqrt = Math.sqrt;
exports.sqrt = sqrt;

function square(x) {
    return x * x;
}

function diag(x, y) {
    return sqrt(square(x) + square(y));
}
//------ main.js ------
'use strict';

var _lib = require('lib');

console.log((0, _lib.square)(11)); // 121
console.log((0, _lib.diag)(4, 3)); // 5

这段代码在NodeJs中足够用了。 但是要在浏览器中使用,您需要 require.js 或 browserify 之类的东西。 在这个plunker I used require1k

就像Manasov Daniel说的

MDN says

Note: This feature is not implemented in any browsers natively at this time. It is implemented in many transpilers, such as the Traceur Compiler, Babel or Rollup.

对于较新版本的 ECMAScript(在浏览器中实现之前),您通常必须将 ECMAScript 代码转译(编译)为 JavaScript。我选择的工具是 Babel,尽管还有很多其他工具。

您可以通过转到终端并输入以下内容来安装 Babel CLI:

$ npm install --save-dev babel-cli

每次对 ES 进行更改时,都应该重新编译为 JS。