javascript JavaScript模块ES6(ES2015)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript JavaScript模块ES6(ES2015)相关的知识,希望对你有一定的参考价值。

// lib/math.js
export function sum(x, y) {
  return x + y;
}
export var pi = 3.141593;

// app.js
import * as math from "lib/math";
console.log("2π = " + math.sum(math.pi, math.pi));

// otherApp.js
import {sum, pi} from "lib/math";
console.log("2π = " + sum(pi, pi));



// lib/mathplusplus.js
export * from "lib/math";
export var e = 2.71828182846;
export default function(x) {
    return Math.exp(x);
}

// app.js
import exp, {pi, e} from "lib/mathplusplus";
console.log("e^π = " + exp(pi));
// library.js

// import the book module
import {favoriteBook, Book} from 'book';

// create some books and get their descriptions
let booksILike = [  
    new Book("Under The Dome", "Steven King"),
    new Book("Julius Ceasar", "William Shakespeare")
];

console.log("My favorite book is " + favoriteBook + ".");  
console.log("I also like " + booksILike[0].describeBook() + " and " + booksILike[1].describeBook());  
// book.js
const favoriteBook = {  
    title: "The Guards",
    author: "Ken Bruen"
}

// a Book class using ES6 class syntax
class Book {  
    constructor(title, author) {
        this.title = title;
        this.author = author;
    }

    describeBook() {
        let description = this.title + " by " + this.author + ".";
        return description;
    }
}

// exporting looks different from Node.js but is almost as simple
export {favoriteBook, Book};  
module.exports = {
    name: 'Brad', 
    email:'email@gmail.com'
}



export const person = {
    name: 'John',
    age: 30
}

export function sayHello() {
    return `Hello ${person.name}`;
}

const greeting = 'Hello';
export default greeting; 








//CommonJS module synthax
/* const person = require('./mymodule1');
console.log(person.name); */


//ES2015 Module synthax
// import { person, sayHello } from "./mymodule2";
//import * as mod from './mymodule2';
//import greeting from './mymodule2';

console.log(mod.person.name);

console.log(mod.sayHello());

console.log(greeting);

以上是关于javascript JavaScript模块ES6(ES2015)的主要内容,如果未能解决你的问题,请参考以下文章

javascript ES6模块

javascript ES模块和用法

javascript ES6模块

markdown Javascript ES5模块设置

JavaScript模块(ES6 module)化总结(import())

JavaScript模块(ES6 module)化总结(import())