xia的小窩

一起來coding和碼字吧

0%

js-撰寫及匯入JavaScript模組

先隨手建立專案

建立專案

1
npm init --yes

接著修改 json 檔,說明引用 module

1
2
3
4
5
6
7
8
9
10
11
12
13
{
"name": "js",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"type": "module"
}

然後新增一個 tax.js 的檔案

1
2
3
export default function(price){
return Number(price) * 1.2;
}
  • export 關鍵字 → 代表函式是要匯出給外部檔案引用的內容。( JS 預設是私有,所以必須宣告 )
  • default 關鍵字 → 只能用在模組中的一個函式,作為匯入時的預設功能,讓我們能用任意名稱呼叫它。

使用 Js 模組,在這裡新增了一個 index.js 的檔案

1
2
3
4
5
6
7
8
9
10
11
12
13
import calcTax from './tax.js';

class Product{
constructor(name, price){
this.id = Symbol();
this.name = name;
this.price = price;
}
}

let product = new Product("Hat", 1000);
let taxedPrice = calcTax(product.price);
console.log(`name : ${product.name}, taxprice : ${taxedPrice}`)

最後輸入 ↓,就可以看到答案了。

1
node index.js

從模組匯出有名稱的功能

函式作用不變

1
2
3
export function cal(price){
return Number(price) * 1.2;
}

我們將 default 關鍵字拿掉後改成自己設定的名字,而後再更改 index.js 的函式……

1
2
3
4
5
6
7
8
9
10
11
12
13
import { cal } from './tax.js';

class Product{
constructor(name, price){
this.id = Symbol();
this.name = name;
this.price = price;
}
}

let product = new Product("Hat", 1000);
let taxedPrice = cal(product.price);
console.log(`name : ${product.name}, taxprice : ${taxedPrice}`)

這樣也可以有相同的結果喔

不過要注意一個問題

1
import tax, { cal } from './tax.js';

這時候就要注意預設的值~~