載入Css webpack並不能處理js以外的靜態資源,通過loader來支持他們 載入圖片 file loader可以處理圖片資源,字體資源 載入數據 ...
## 載入Css > webpack並不能處理js以外的靜態資源,通過loader來支持他們 ``` npm install --save-dev style-loader css-loader const path = require('path'); module.exports = { entry: './src/index.js', output: { filename: 'bundle.js', path: path.resolve(__dirname, 'dist') }, + module: { + rules: [ + { + test: /\.css$/, + use: [ + 'style-loader', + 'css-loader' + ] + } + ] + } }; ``` ## 載入圖片 > file-loader可以處理圖片資源,字體資源 ``` npm install --save-dev file-loader import _ from 'lodash'; import './style.css'; + import Icon from './icon.png'; function component() { var element = document.createElement('div'); // Lodash,現在由此腳本導入 element.innerHTML = _.join(['Hello', 'webpack'], ' '); element.classList.add('hello'); + // 將圖像添加到我們現有的 div。 + var myIcon = new Image(); + myIcon.src = Icon; + + element.appendChild(myIcon); return element; } document.body.appendChild(component()); //css裡面引入也是沒問題的 .hello { color: red; + background: url('./icon.png'); } const path = require('path'); module.exports = { entry: './src/index.js', output: { filename: 'bundle.js', path: path.resolve(__dirname, 'dist') }, module: { rules: [ { test: /\.css$/, use: [ 'style-loader', 'css-loader' ] }, { test: /\.(png|svg|jpg|gif)$/, use: [ 'file-loader' ] }, + { + test: /\.(woff|woff2|eot|ttf|otf)$/, + use: [ + 'file-loader' + ] + } ] } }; ``` ## 載入數據 ``` npm install --save-dev csv-loader xml-loader { + test: /\.(csv|tsv)$/, + use: [ + 'csv-loader' + ] + }, + { + test: /\.xml$/, + use: [ + 'xml-loader' + ] + } ```