NPM – Webpack – 使用 import 的絕對路徑方法
預設的時候通常使用相對路徑,可是會很不容易管理,例如
1 2 3 4 |
import '../compoments/tabs' import '../../template/helloWorld' |
這時我們只要在 webpack.config.js 使用模塊的解析方式 “resolve” 來設定別名,就能在 import 的時候簡寫來能省去計算相對位置的麻煩,例如
1 2 3 4 5 6 7 8 9 10 11 12 13 |
module.exports = { //... resolve: { alias: { '@compoments': path.resolve(__dirname, 'assets/src/javascript/compoments'), '@template': path.resolve(__dirname, 'assets/src/javascript/template'), '@scss': path.resolve(__dirname, 'assets/src/scss'), } } } |
修改成
1 2 3 4 5 |
import '@compoments/tabs' import '@template/helloWorld' import '@scss/app.scss' |
當然開頭的 @ 是我習慣自訂用來區別純單字的符號,你也可以不要使用,更多方法可以參考官網說明。