首页 > 代码库 > JavaScript import/export

JavaScript import/export

定义模块

ES6之后,使用模块语法(import/export)时,每个文件都会成为它自己的模块,带有一个私有全名空间。顶层的函数和变量不会污染全局全名空间。要为其他模块暴露函数,类,和变量以便import的话,可以用export关键字。

// not exported
function somethingPrivate() {
    console.log(‘TOP SECRET‘)
}


export const PI = 3.14;

export function doSomething() {
    console.log(‘Hello from a module!‘)
}

function doSomethingElse(){ 
    console.log("Something else")
}

export {doSomethingElse}

export class MyClass {
    test() {}
}

import整个模块

import * as test from ‘./test‘

test.doSomething()

./test表示test.js的路径。

import命名成员

import {doSomething, MyClass, PI} from ‘./test‘

doSomething()

const mine = new MyClass()
mine.test()

console.log(PI)

语法


import defaultMember from ‘module‘;


import { memberA, memberB, ... } from ‘module‘;


import * as module from ‘module‘;


import { memberA as a, memberB, ... } from ‘module‘;


import defaultMember, * as module from ‘module‘;


import defaultMember, { moduleA, ... } from ‘module‘;


import ‘module‘;
<script type="text/javascript"> $(function () { $(‘pre.prettyprint code‘).each(function () { var lines = $(this).text().split(‘\n‘).length; var $numbering = $(‘
    ‘).addClass(‘pre-numbering‘).hide(); $(this).addClass(‘has-numbering‘).parent().append($numbering); for (i = 1; i <= lines; i++) { $numbering.append($(‘
  • ‘).text(i)); }; $numbering.fadeIn(1700); }); }); </script>

    JavaScript import/export