JSファイルを別のJSファイルに含めるJavaScriptプログラム

Javascript

例:インポート/エクスポートの使用

という名前のファイルを作成しましょう module.js (ファイル名は何でもかまいません)次の内容で:

// program to include JS file into another JS file

const message = 'hello world';

const number = 10;

function multiplyNumbers(a, b) {
    return a * b;
}

// exporting variables and function
export { message, number, multiplyNumbers };

これらの変数と関数を別のファイルに含めるには、次のように言います。 main.js、あなたは使用することができます import キーワードとして:

// import the variables and function from module.js
import { message, number, multiplyNumbers } from './modules.js';

console.log(message); // hello world

console.log(number); // 10

console.log(multiplyNumbers(3, 4)); // 12
console.log(multiplyNumbers(5, 8)); // 40

別のファイルを含めるには、使用するコードを別のファイルでエクスポートする必要があります。 export ステートメント。 例えば、

export { message, number, multiplyNumbers };

個別にエクスポートすることもできます。 例えば、

export const message = 'hello world';

export const number = 10;

別のファイルのコードを含めるには、を使用する必要があります import ステートメントを作成し、ファイルパスを使用してインポートします。 例えば、

// importing codes from module file
import { message, number, multiplyNumbers } from './modules.js';

次に、これらのコードは同じファイルの一部であるため、使用できます。

これは、よりクリーンで保守が容易なモジュラーコードの記述に役立ちます。



Hope this helps!

Source link

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です