jsはrequireとimportの違いを使いますか?

1284 ワード

requireもimportもjsモジュール化のために使用されています.
一、require
requireはcommonjsの仕様であり、nodeアプリケーションはモジュールからなり、commonjsの仕様に従う.
a.js
function test (args) {
  // body...
  console.log(args);	
}
 
module.exports = {
  test
};

b.js
let { test } = require('./a.js');
test('this is a test.');

requireのコアコンセプト:エクスポートされたファイルにmoduleを定義します.exportsでは、エクスポートされるオブジェクトのタイプは限定されません(任意のタイプで使用できます).インポートされたファイルにrequire()を使用してインポートすれば使用できます.本質的には、エクスポートするオブジェクトをmoduleというオブジェクトのexportsプロパティに割り当て、他のファイルでrequireという方法でexportsというプロパティにアクセスします.上のb.jsでは、require(./a.js)=exportsというオブジェクトを使用し、es 6を使用してexportsオブジェクトからtestの値を取り出します. 
二、impoort
importはes 6がjsモジュール化のために提案した新しい構文であり、import(インポート)はexport(エクスポート)と組み合わせて使用される.
a.js
export function test (args) {
  // body...
  console.log(args);	
}
 
//       ,           
export default function() {...};
 
export const name = "lyn";

b.js
// _     export default   
import _, { test, name } from './a.js';
 
test(`my name is ${name}`);

三、commonjsモジュールとES 6モジュールの違い
    1.commonjsが出力するのは、値のコピーであり、es 6が出力するのは値の参照である.
    2.commonjsは実行時ロードであり、es 6はコンパイル時出力インタフェースである.