如何在网页内使用ECMAScript6模块 [英] How to use ECMAScript6 modules within webpages

查看:120
本文介绍了如何在网页内使用ECMAScript6模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很高兴通过Babeljs来使用ECMAScript 6功能 - 特别是,我很乐意使用新的模块功能开始使我的JavaScript代码更加模块化。



这是我到目前为止写的:

  // ECMAScript 6代码 -  lib.js 
导出const sqrt = Math.sqrt;
导出函数square(x){
return x * x;
}

导出函数diag(x,y){
返回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: p>

  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>

<! - 这里有什么?
如何在浏览器中添加main6to5.js和lib6to5.js? - >
< script src =?????>< / script>

< / head>
< body>

< / body>
< / html>

谢谢

解决方案

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

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

//增强对象文字
var project =helloWorld;
var obj = {
//项目:项目
项目,
//方法
printProject(){
console.log这个项目);
},
[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。在将代码转换成ES5之后,您也必须将它们(从AMD / CommonJS / Modules转换为代码,将您的浏览器可以理解)。您可以使用各种构建系统,如 gulp webpack browserify 等。我将在此使用browserify作为示例。



说出我的文件夹结构如下:

  es6 
| - src
| - lib .js
| - main.js
| - 编译
| - index.html

我运行babel将我的文件 / src 转载到 / compile 文件夹: babel src --out-dir编译



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

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

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

 (函数e(t,n,r){function s(o,u){if(!n [o]){if(!t [o]){var a = typeof require = =function&& require; if(!u&&& a)返回一个(o,!0); if(i)返回i(o,!0); var f = new Error(Can not find模块'+ o +'); throw f.code =MODULE_NOT_FOUND,f} var l = n [o] = {exports:{}}; t [o] [0] .call(l.exports,函数(e){var n = t [o] [1] [e]; return s(n?n:e)},l,lexports,e,t,n,r)} return n [ .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;

functio n square(x){
return x * x;
}

函数diag(x,y){
返回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


I'm pretty excited about using ECMAScript 6 features now via Babeljs - in particular, I'd love to start making my JavaScript code more modular using the new modules feature.

Here's what I've written so far:

// 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));

I understand that I can transpile this code from ES6 to ES5 via babel on the command line:

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

But what do I need to do to use this code within my HTML?

For example, what would this index.html file look like:

<!-- 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>

Thank you

解决方案

Without using Modules: If you are not using modules (imports/exports), then you can simply transpile your code into ES5 and include those ES5 files in your html. Example:

// 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);

Transpile to es5: babel index.js > es5.js

In index.html, include <script src="es5.js"></script> Will print out the following in console:

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

Using Modules: Now if you are using modules (which is your case with lib.js and main.js), after converting your code into ES5 you also have to bundle them (from AMD/CommonJS/Modules to code that your browser can understand). You can do this with various build systems like gulp, webpack, browserify, etc. I'm going to use browserify as an example here.

Say my folder structure looks like this:

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

I run babel to transpile my files /src to /compiled folder: babel src --out-dir compiled.

Now I have my ES5 code in the compiled folder. I install browserify in the cmd line and then bundle my main.js (entry point) in my compiled folder

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

Now I have bundle.js which is look like this:

(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]);

Then in your index.html:

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

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

  </head>
  <body>

  </body>
</html>

Then simply open up your index.html, and your console should give you the following:

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

这篇关于如何在网页内使用ECMAScript6模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆