今天,我正在設定一個使用Webpack、React和Bootstrap(不包括jQuery)的專案。原本看似簡單直接的任務結果卻花了我比預期多的時間,所以我決定將步驟記錄在下面:

步驟1:安裝所有依賴

首先,安裝所有需要的依賴:

npm install react react-dom bootstrap react-bootstrap babel-preset-react --save
npm install webpack css-loader style-loader file-loader url-loader babel-core babel-loader babel-preset-es2015 --save-dev

步驟2:在webpack.config.js中添加Loaders

接下來,在你的webpack.config.js文件中添加必要的loaders:

var path = require("path")
var webpack = require("webpack")

module.exports = {
  entry: "./main.js",
  output: { path: __dirname, filename: "bundle.js" },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        loader: "babel-loader",
        exclude: /node_modules/,
        options: {
          presets: ["es2015", "react"],
        },
      },
      {
        test: /\.css$/,
        use: ["style-loader", "css-loader"],
      },
      {
        test: /\.png$/,
        loader: "url-loader?limit=100000",
      },
      {
        test: /\.jpg$/,
        loader: "file-loader",
      },
      {
        test: /\.(woff|woff2)(\?v=\d+\.\d+\.\d+)?$/,
        loader: "url-loader?limit=10000&mimetype=application/font-woff",
      },
      {
        test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
        loader: "url-loader?limit=10000&mimetype=application/octet-stream",
      },
      {
        test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
        loader: "file-loader",
      },
      {
        test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
        loader: "url-loader?limit=10000&mimetype=image/svg+xml",
      },
    ],
  },
}

步驟3:在main.js中引入Bootstrap CSS

在你的main.js文件(或者是你的進口文件)中,引入Bootstrap CSS:

import App from "./app.jsx"
import Bootstrap from "bootstrap/dist/css/bootstrap.css"

步驟4:在app.jsx中引入React Bootstrap

最後,在您的app.jsx中,導入React Bootstrap組件:

import React from "react"
import ReactDOM from "react-dom"
import { Button } from "react-bootstrap"

const buttonsInstance = <Button>Click me!</Button>

ReactDOM.render(buttonsInstance, document.getElementById("here"))

HTML設定

別忘了附上一個帶有適當ID的div,以及bundle.js

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello React</title>
  </head>
  <body>
    <div id="here"></div>
    <script src="bundle.js"></script>
  </body>
</html>

這就完成了!如果有任何問題,歡迎隨時向我提問。