javascript - 如何在网页中使用 ECMAScript6 模块

标签 javascript ecmascript-6 babeljs

我对现在通过 Babeljs 使用 ECMAScript 6 功能感到非常兴奋 - 特别是,我很乐意开始使用新的模块功能使我的 JavaScript 代码更加模块化。

这是我到目前为止所写的内容:

// ECMAScript 6 code - 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));
}

// ECMAScript 6 code - main.js
import { square, diag } from 'lib';
console.log(square(11));
console.log(diag(4, 3));

我知道我可以在命令行上通过 babel 将此代码从 ES6 转换为 ES5:

babel lib.js > lib6to5.js
babel main.js > main6to5.js

但是我需要做什么才能在 HTML 中使用此代码?

例如,这个index.html 文件是什么样的:

<!-- index.html -->
<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>ECMAScript 6</title>

    <!-- What goes here? 
     How do I include main6to5.js and lib6to5.js to make this work in the browser? -->
    <script src="?????"></script>

  </head>
  <body>

  </body>
</html>

谢谢

最佳答案

不使用模块: 如果您不使用模块(导入/导出),那么您可以简单地将代码转换为 ES5 并将这些 ES5 文件包含在 html 中。 示例:

// ES6 - index.js
// arrow function
var result = [1, 2, 3].map(n => n * 2);
console.log(result);

// enhanced object literal
var project = "helloWorld";
var obj = {
    // Shorthand for ‘project: project’
    project,
    // Methods
    printProject() {
     console.log(this.project);
    },
    [ "prop_" + (() => 42)() ]: 42
};
console.log(obj.printProject());
console.log(obj);

转换为 es5: babel index.js > es5.js

index.html ,包括<script src="es5.js"></script> 将在控制台中打印出以下内容:

[2,4,6]
helloWorld
{"project":"helloWorld","prop_42":42}

使用模块:现在,如果您正在使用模块(即 lib.jsmain.js 的情况),在将代码转换为 ES5 后,您还必须捆绑它们(来自 AMD/CommonJS/Modules 来编写您的浏览器可以理解的代码)。您可以使用各种构建系统来完成此操作,例如 gulp , webpack , browserify等等。我将在这里使用 browserify 作为示例。

假设我的文件夹结构如下所示:

es6
|- src
  |- lib.js
  |- main.js
|- compiled
|- index.html

我运行 babel 来转译我的文件 /src/compiled文件夹:babel src --out-dir compiled .

现在我的 ES5 代码位于已编译的文件夹中。我在 cmd 行中安装 browserify,然后将 main.js (入口点)捆绑到我的编译文件夹中

~/es6 » npm install --global browserify
~/es6 » browserify ./compiled/main.js -o ./bundle.js

现在我有bundle.js看起来像这样:

(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
"use strict";

exports.square = square;
exports.diag = diag;
var sqrt = exports.sqrt = Math.sqrt;

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

function diag(x, y) {
    return sqrt(square(x) + square(y));
}

Object.defineProperty(exports, "__esModule", {
    value: true
});
},{}],2:[function(require,module,exports){
"use strict";

var _lib = require("./lib");

var square = _lib.square;
var diag = _lib.diag;

console.log(square(11)); // 121
console.log(diag(4, 3)); // 5
},{"./lib":1}]},{},[2]);

然后在你的index.html中:

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>ECMAScript 6</title>

    <script src="./bundle.js"></script>

  </head>
  <body>

  </body>
</html>

然后只需打开您的 index.html ,您的控制台应该会显示以下内容:

 121           bundle.js:27
 5             bundle.js:28

关于javascript - 如何在网页中使用 ECMAScript6 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28761120/

相关文章:

javascript - JQuery - 用 FontAwesome 图像替换表格文本值

javascript - 如何将 thymeleaf 字符串变量传递给 javascript 参数?

嵌套箭头函数的Javascript内存含义

javascript - 使用 ES6 访问参数对象

javascript - 带赋值的箭头函数语法 ES6

javascript - react 路由器 : TypeError Cannot read properties of undefined (reading 'originalPositionFor' )

javascript - twbsPagination totalPage 值总是在变化?

javascript - 无法设置对象属性以存储到对象数组(JavaScript)

javascript - React、webpack 热重载的“导入”问题

javascript - three.js ES6 如何只导入特定模块