簡體   English   中英

如何在網頁中使用ECMAScript6模塊

[英]How to use ECMAScript6 modules within webpages

我很高興現在通過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到您的瀏覽器可以理解的代碼) )。 你可以用不同的生成系統,如這樣做一飲而盡的WebPackbrowserify ,等我將使用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

[ 注意 :我意識到我的答案很差,因為它沒有完全反映提問者在前端工作流程中通過babeljs使用ES6模塊的意圖。 為那些想要在網頁中使用ES6模塊的人保留答案]

嘗試使用jspm.io在瀏覽器中加載ES6模塊,而無需事先與babel進行轉換。 可以在這里找到一個plunker

JSPM作品上的頂部system.js它試圖對任何模塊格式(ES6,AMD,CommonJS的)加載器..

為了在我的瀏覽器中工作,我基於這個jspm ES6演示 剛剛在js / lib文件夾中復制了System.jses6-module-loader.js ,並將你的es6 js文件復制到了js文件夾中。 然后html看起來像這樣:

<html>
    <body>
        Test .. just open up the Chrome Devtools console to see the ES6 modules output using jspm
        <script src="js/lib/system.js"></script>
        <script>System.import("main");</script> </body>
</html>

可以在這里找到一個plunker

我從嘗試同樣的事情開始,但最終發現Gulp確實幫了很多忙。

要記住一件事: babel source.js > destination.js不會填充新的ES6語法 你的代碼現在沒有使用任何let語句,結構化賦值,生成器函數或類似的東西; 但如果你在稍后階段添加它,你將需要更復雜的轉換。

這是一個解釋如何設置gulp文件的答案: Javascript 6to5(現在Babel)導出模塊用法 (免責聲明:這是我的答案之一:P)

以下是針對您的案例的具體步驟:

  1. 在您的目錄中創建一個名為gulpfile.js的文件,其中包含以下內容:
var gulp = require('gulp');
var browserify = require('browserify');
var babelify= require('babelify');
var util = require('gulp-util');
var buffer = require('vinyl-buffer');
var source = require('vinyl-source-stream');
var uglify = require('gulp-uglify');
var sourcemaps = require('gulp-sourcemaps');

gulp.task('build', function() {
  browserify(['./lib.js', './main.js'], { debug: true })
  .add(require.resolve('babel/polyfill'))
  .transform(babelify)
  .bundle()
  .on('error', util.log.bind(util, 'Browserify Error'))
  .pipe(source('app.js'))
  .pipe(buffer())
  .pipe(sourcemaps.init({loadMaps: true}))
  .pipe(uglify({ mangle: false }))
  .pipe(sourcemaps.write('./'))
  .pipe(gulp.dest('./'));
});

gulp.task('default', ['build']);
  1. 運行npm install gulp browserify babel babelify gulp-util vinyl-buffer vinyl-source-stream gulp-uglify gulp-sourcemaps來安裝所需的依賴項。
  2. 運行gulp將所有內容捆綁在一起。
  3. 使用HTML中的捆綁腳本和此元素: <script src="app.js"></script>

除了添加polyfill之外,還有一個好處是代碼縮小了,你得到了源圖,這意味着即使在你的開發人員工具中,你也可以自己調試ES6代碼。


注意:雖然您使用的import語句根據ES6草案規范是正確的,但Babel不會喜歡它。 您需要添加./ ,以便它看起來像這樣:

import { square, diag } from './lib';

我懷疑這是因為轉換發生在Node.js中,這將文件與節點模塊區分開來。 作為一個側面,您可以使用import語句編寫ES6 for node do requires :)

其中一個--modules切換編譯成JS,可以直接包含在網頁中,就像--script標志將編譯到瀏覽器JS一樣( --script不能與模塊一起使用)? 請參閱https://github.com/google/traceur-compiler/wiki/Options-for-Compiling

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM