問題1: component使用css物件,改為className使用css檔案,我們必須靠css loader幫我轉換代碼,當components將代碼轉為class,才有辦法正確的吃到style顯示css樣式。
css-loader
https://webpack.js.org/loaders/css-loader/
style-loader
https://webpack.js.org/loaders/style-loader/
src/css/style.css
.sidebar {
position: fixed;
top: 51px;
bottom: 0;
left: 0;
z-index: 1000;
display: block;
padding: 20px;
overflow-x: hidden;
overflow-y: auto;
background-color: #f5f5f5;
border-right: 1px solid #eee;
}
.content {
top: 51px;
}
.h1BottomHr {
padding-bottom: 9px;
margin-bottom: 20px;
border-bottom: 1px solid #eee;
}
.navbar > div.container-fluid {
background-color: #343a40!important;
}
.fixed-top {
position: fixed;
top: 0;
right: 0;
left: 0;
z-index: 1030;
}
.ironmanchampion {
background-image: url("../image/event2.png");
background-repeat: no-repeat;
height: 300px;
width: auto;
}
index.js import css
src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import Layout from './components/Layout';
import './css/styles.css';
ReactDOM.render(
<Layout />,
document.getElementById('app')
);
style改為className
src/components/Layout.js
css object
<Col xs={2} style={sidebar}>
become
<Col xs={2} className="sidebar">
問題2: file會因為路徑問題而無法顯示,所以我們必須依懶fil-loader來處理路徑轉換,才有辦法正常顯示圖片。
file-loader
https://webpack.js.org/loaders/file-loader/
輸出畫面
問題3: 當使用者點選"使用者清單"可顯示畫面,按下"重新整理"則出現"Cannot GET /userinfo",因為react是由component來切換頁面,實際路徑找不到userinfo必須依懶HTML5 History API。
devServer.historyApiFallback
https://webpack.js.org/configuration/dev-server/#devserver-historyapifallback
Cannot GET /userinfo
webpack loader設定檔
const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: [path.resolve(__dirname, 'src/index.js')],
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: "/"
},
devServer: {
contentBase: path.join(__dirname, "dist"),
port: 8080,
hot: true,
historyApiFallback: true
},plugins: [
new webpack.NamedModulesPlugin(),
new webpack.HotModuleReplacementPlugin()
],
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: "babel-loader",
options: {
presets:['es2015', 'react']
}
},{
test: /\.css$/,
use: [ 'style-loader', 'css-loader' ]
},{
test: /\.(jpg|png|svg|gif)$/,
exclude: /node_modules/,
loader: 'file-loader',
options: {
outputPath: 'image/',
name: '[name].[ext]?[hash]',
publicPath: '/'
}
}
]
}
};
今天解決css、file與404問題,小專案雖然簡單但問題卻一堆,實作上總是容易踩到一堆雷。另外,bootstrap使用css請用v3因為引用v4發現跑版嚴重,如果想要用v4等beta結束再針對v4調整比較好。小專案先到此,如果日後有新發現在慢慢重構更新。
git repository react-bootstrap
https://github.com/kwon44/react-bootstrap