1. 程式人生 > >React-Router+antd+webpack+babel的一個詳細demo

React-Router+antd+webpack+babel的一個詳細demo

antd專案確實是一個非常優秀的開源專案,但是用起來相關文件的說明比較少,特別是從一開始建立一個自己的專案時候需要配置babel,webpack等等,這部分的內容相關介紹就少之又少。因此我寫了一個demo,這個demo配置了必要的webpack和babel項,你只要克隆下來,然後npm run dev就可以了。對於第一次理解antd特別有用。專案地址點選這裡

webpack配置說明

const path = require("path");
module.exports = {
  module: {
    noParse: [/jquery/],
    rules: [{
            test: require
.resolve('antd'), //此時我們window.antd與window.ANTD都是存在的 use: [{ loader: require.resolve('expose-loader'), options: 'antd' },{ loader: require.resolve('expose-loader'), options: 'ANTD' }] }] }, //此時我們通過require("antd");就會將antd的所有的元件都暴露到window物件上
resolve: { alias: { "antd" :"antd" }, }, devServer:{ publicPath:'/', open :true, port:8090, // contentBase: path.join(process.cwd(), "public"), // webpack-dev-server中的html無法訪問外部的html頁面或者其他靜態資源 historyApiFallback: { rewrites: [ { from: "/docs/react/common.js"
, to: '/common.js' }, { from: "/docs/react/index.js", to: '/index.js' }, { from: "/docs/pattern/common.js", to: '/common.js' }, { from: "/docs/pattern/index.js", to: '/index.js' }, { from: "/docs/resource/common.js", to: '/common.js' }, { from: "/docs/resource/index.js", to: '/index.js' }, { from: "/docs/spec/common.js", to: '/common.js' }, { from: "/docs/spec/index.js", to: '/index.js' }, { from: "/components/alert/common.js", to: '/common.js' }, { from: "/components/alert/index.js", to: '/index.js' }, { from: "/components/button/common.js ", to: '/common.js' }, { from: "/components/button/index.js", to: '/index.js' } ] }, contentBase:false, hot:false } }

這裡我使用了expose-loader將antd暴露為一個全域性變數。但是,一定要注意,這個webpack配置檔案設定的只是針對這個專案的特定配置,通用的配置請檢視這裡,我會自動合併這兩處的webpack配置內容~~這也是你為什麼一開始要手動安裝webpackcc的原因~

npm install webpackcc -g

babel配置

{
    presets: [
    'es2015', 'stage-0', 'react'
    ],
    plugins: [
    'transform-runtime',
     "react-hot-loader/babel",
     "add-module-exports",
     "jsx-control-statements",
     ['import', {
      libraryName: 'antd',
      style: 'css'
    }]
    ]
 }

其中最重要的就是其中的babel-plugin-import,當你引入antd的一個元件的時候,他會自動引入其中的css~~