基於webpack的React項目搭建(一)

 

前言 

工欲善其事,必先利其器。爲了更好的學習React,咱們先簡要的把開發環境搭建起來。本文主要介紹使用webpack搭建React項目,若是你對React或es6的基礎語法還不瞭解,建議先去學習學習。javascript

 

鑑於文章發佈到如今已有一年之久,不少庫版本也發生了不少變化,也致使了不少新手搭建出現許多問題。最近已將舊版本全面升級,項目架構也有所調整,開發環境保留了node啓動和webpack啓動webpack-dev-server,沒有加入狀態管理和ajax請求,eslint支持react-hooks,諸位可根據自身需求添加或修改便可。但願新版的調整能幫助各位節省搭建時間,享受代碼的樂趣。新版地址: https://github.com/cy6121/first-react,若是遇到任何問題,歡迎👏提issues。css

  • 基礎環境

node/npmhtml

  • webpack

現代JavaScript程序應用的模塊打包器。它主要分析你的項目結構,找到JavaScript模塊以及其餘一些瀏覽器不能直接運行的拓展語言(Scss、less、TypeScript),將其轉換和打包爲合適的格式供瀏覽器使用。前端

  • 項目建立

建立一個文件夾first-react,進入該目錄,在該目錄下打開一個終端,執行npm init。根據提示輸入內容,也能夠直接按回車鍵跳過。執行完後目錄中會多一個package.json文件,這是項目的核心文件,包含包依賴管理和腳本任務。 java

mkdir first-react
cd first-react 
npm init
  • 安裝react, react-dom, webpack

在項目根目錄下執行下面命令,其中--save的含義是項目上線運行所需的包,即生產環境(--save-dev是開發環境所需的包)。node

npm install react react-dom --save
npm install webpack --save-dev
  •  項目目錄和源碼

--your project
   |--dist(項目打包輸出目錄)
       |--bundle.js(該文件是由webpack打包生成)
       |--index.html  
   |--src
       |--index.js
   |--webpack
       |--webpack.config.js
   |--package.json       

  index.htmlreact

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div id="app">
    /* react DOM*/
    </div>
    <script src="bundle.js"></script>
</body>
</html>

  index.jswebpack

import React, { Component } from 'react';
import { render } from 'react-dom';

render(
    <div>Hello React!</div>,
    document.getElementById('app')
);

  webpack.config.jsgit

const path = require('path');
module.exports = {
    entry: path.resolve(__dirname, '../src/index.js'), //指定入口文件,程序從這裏開始編譯,__dirname當前所在目錄, ../表示上一級目錄, ./同級目錄
    output: {
        path: path.resolve(__dirname, '../dist'), // 輸出的路徑
        filename: 'bundle.js'  // 打包後文件
    },
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: ['es2015', 'react'],
                    }
                },
                exclude: /node_modules/
            }
        ]
    }
}

這裏若是在項目根目錄直接進行webpack構建會報錯(構建命令:webpack --config webpack/webpack.config.js),由於咱們使用了react,react是使用jsx語法實現的,而jsx不能直接被瀏覽器識別和執行,因此這裏須要引入Babel庫進行轉碼。es6

npm install babel-core babel-loader babel-preset-es2015 babel-preset-react --save 

  babel-loader: babel加載器

  babel-preset-es2015: 支持es2015

  babel-preset-react: jsx 轉換成js

最後再次進行構建,而後點擊build/index.html,便可看到Hello React!

webpack --config webpack/webpack.config.js // 更多webpack命令盡在webpack --help查閱, 若是出現webpack: command not found, 全局安裝webpack便可, npm install webpack -g;
// 固然你喜歡用腳本的方式執行,則無需安裝。可是須要注意在webpack4中須要安裝webpack-cli, npm install webpack-cli --save-dev。

  接下來咱們進行一下簡單的優化,執行效果一致。

index.js

import React from 'react';
import { render } from 'react-dom';
import App from './App'

const renderDom = Component => {
    render(
        <Component />,
        document.getElementById('app')
    );
}
renderDom(App);

 在項目根目錄下新建json文件.babelrc,將babel的配置單獨提取出來。

{
  "presets": [
    "es2015",
    "react"
  ]
}

webpack.config.js文件做相應的調整。

const path = require('path');
const webpack = require('webpack');
module.exports = {
    entry: path.resolve(__dirname, '../src/index.js'), //指定入口文件,程序從這裏開始編譯,__dirname當前所在目錄, ../表示上一級目錄, ./同級目錄
    output: {
        path: path.resolve(__dirname, '../dist'), // 輸出的路徑
        filename: 'bundle.js'  // 打包後文件
    },
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                loader: 'babel-loader',
                exclude: /node_modules/
            }
        ]
    }
}

在src下新建App.js。

import React, { Component } from 'react';

export default class App extends Component {
    render() {
        return (
            <div>Hello React!</div>
        );
    }
}
  •  以腳本方式執行構建

編輯package.json,加入自定義腳本,在項目根目錄執行npm run dev便可達到上面同樣的效果。

"scripts": {
    "dev": "webpack --config webpack/webpack.config.js"
  }
  •  搭建前端服務器

能夠發現,每次都要從新構建而後刷新index.html,才能獲得最新的效果,開發效率極低。幸虧webpack-dev-server能夠幫助咱們解決這個問題,webpack-dev-server是一個小型的靜態文件服務器,爲webpack打包的資源文件提供Web服務。而且提供自動刷新和Hot Module Replacement(模塊熱替換:前端代碼變更後無需刷新整個頁面,只把變化的部分替換掉)。OK,讓咱們開始安裝和配置webpack-dev-server。

npm install webpack-dev-server --save-dev  

 在項目根目錄下建立bin目錄,進入bin目錄,建立dev-server.js文件,編輯以下

'use strict'

const WebpackDevServer = require('webpack-dev-server');
const config = require('../webpack/webpack.config');
const webpack = require('webpack');
const path = require('path');
const compiler = webpack(config);

const server = new WebpackDevServer(compiler, {
    contentBase: path.resolve(__dirname, '../dist'), //默認會以根文件夾提供本地服務器,這裏指定文件夾
    historyApiFallback: true, //在開發單頁應用時很是有用,它依賴於HTML5 history API,若是設置爲true,全部的跳轉將指向index.html
    port: 9090, //若是省略,默認8080
    publicPath: "/"
});
server.listen(9090, 'localhost', function (err) {
    if (err) throw err
})

   編輯package.json,建立一條腳本

"scripts": {
    "dev": "node bin/dev-server"
  }

   最後,單獨在該項目根目錄起一個終端,執行npm run dev,啓動成功後訪問http://localhost:9090。若是看到Hello React!,恭喜你。 最後再作一下簡單的測試,將App.js修改以下後保存,能夠發現,項目會自動從新編譯運行,刷新瀏覽器便可看到最新的更改。

import React, { Component } from 'react';

export default class App extends Component {
    render() {
        return (
            <div>
                <h1>Hello React</h1>
                <h2>Hello React</h2>
            </div>
        );
    }
}
  • Html-webpack-plugin

  刪除根目錄下dist目錄,剛剛咱們是本身編寫和配置index.html,將打包後的js引入到index.html中。現刪除後啓動服務會報錯,如今咱們使用插件實現自動引入,免去手工配置,安裝html-webpack-plugin

npm install html-webpack-plugin --save-dev

  在src目錄新建index.template.html。

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title><%= htmlWebpackPlugin.options.title %></title>
    </head>
    <body>
        <div id="app">
        </div>
    </body>
</html>

  編輯webpack.config.js。最後從新啓動服務便可。如果想看打包後的文件能夠打開chorme,在Sources便可看見。或者使用webpack --config webpack/webpack.config.js進行構建,在項目目錄的dist目錄查看。

const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports
= { entry: path.resolve(__dirname, '../src/index.js'), //指定入口文件,程序從這裏開始編譯,__dirname當前所在目錄, ../表示上一級目錄, ./同級目錄 output: { path: path.resolve(__dirname, '../dist'), // 輸出的路徑 filename: 'app/[name]_[hash:8].js' // 打包後文件 }, module: { rules: [ { test: /\.(js|jsx)$/, loader: 'babel-loader', exclude: /node_modules/ } ] },
   plugins: [
     new HtmlWebpackPlugin({
       template: path.resolve(__dirname, '../src/index.template.html'),
       inject: true

     })
   ]
}
相關文章
相關標籤/搜索