How to use ECMAScript6 modules within webpages

后端 未结 4 913
臣服心动
臣服心动 2020-12-08 07:11

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 featur

4条回答
  •  感情败类
    2020-12-08 07:53

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

    Then in your index.html:

    
    
      
        
        ECMAScript 6
    
        
    
      
      
    
      
    
    

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

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

提交回复
热议问题