1. 程式人生 > >webpack學習(八):配置react

webpack學習(八):配置react

demo地址: https://github.com/Lkkkkkkg/webpack-demo
目前配置了 HtmlWebpackPlugin , CleanWebpackPlugin 外掛, 使用了 source map 功能 , 和 webpack-dev-serve 伺服器, 配置詳情瀏覽 webpack 配置系列: https://blog.csdn.net/qq593249106/article/details/84892069

在前面的配置後, 更改了目錄結構, 新建一個 App.js 為了分離 React 入口檔案和主檔案, 還新建了一個 index.html 作為模板檔案, 是為了 HtmlWebpackPlugin 外掛生成的頁面有 < div id = 'root '></ div> 這個根 div 讓 react 完成渲染


目錄結構:

|- /node_modules
|- /src //用於放原始檔的資料夾
  |- /components
  |- /index //模板檔案
    |- index.html //模板檔案
    |- index.js //入口檔案
    |- App.js //react主檔案
|- package.json
|- webpack.config.js //webpack配置檔案

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <
title
>
React</title> </head> <body> <div id="root"> </div> </body> </html>

index.js

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

render(<App />, document.getElementById("root"))

App.js

import React from 'react'
const App = () => ( <h1> Hello, React!<br /> </h1> ) export default App

別忘了修改一下入口檔案配置, 加上一個 mode: development 屬性, 代表是開發模式
webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');


module.exports = {
	mode: 'development',
    entry: './src/components/index/index.js', //入口檔案
    devtool: 'inline-source-map', // 不同選項適用於不同環境
    devServer: {
        contentBase: './dist', //將dist目錄下的檔案(index.html)作為可訪問檔案, 如果不寫這個引數則預設與webpack.cofig.js的同級目錄
        port: 8080 //埠號設為8080, 預設也是8080
    },
    plugins: [ //webpack 通過 plugins 實現各種功能, 比如 html-webpack-plugin 使用模版生成 html 檔案
        new CleanWebpackPlugin(['dist']), //設定清除的目錄
        new HtmlWebpackPlugin({
            filename: 'index.html', //設定生成的HTML檔案的名稱, 支援指定子目錄,如:assets/admin.html
            template: "./src/components/index/index.html" //指定模板檔案的位置
        })
    ],
    output: {
        filename: 'bundle.js', //根據入口檔案輸出不同出口檔案
        path: path.resolve(__dirname, 'dist')
    }
};

package.json

{
  "name": "demo01",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack",
    "dev": "webpack-dev-server --open"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "clean-webpack-plugin": "^1.0.0",
    "html-webpack-plugin": "^3.2.0",
    "webpack": "^4.27.1",
    "webpack-cli": "^3.1.2",
    "webpack-dev-server": "^3.1.10"
  },
  "dependencies": {
    "lodash": "^4.17.11"
  }
}

安裝

安裝 react, 終端輸入:

npm install react react-dom --save-dev

React 元件由 JSX 組成, 瀏覽器無法識別 JSX , 需要 babel 進行轉換

  • babel-croe (為babel核心檔案)
  • babel-preset-env (將ES6轉義成ES5)
  • babel-preset-react (將JSX轉義成js)
  • babel-loader (webpack的babe轉換)
npm install babel-core babel-preset-env babel-preset-react babel-loader --save-dev

安裝完後, 在根目錄下新建一個 .babelrc 檔案, 它是bable的核心配置檔案, 內容如下:
.babelrc

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

配置 webpack.config.js

然後在 webpack 配置轉 jsx 和 es6 的 rule:
webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');


module.exports = {
	mode: 'development',
    entry: './src/components/index/index.js', //入口檔案
    devtool: 'inline-source-map', // 不同選項適用於不同環境
    devServer: {
        contentBase: './dist', //將dist目錄下的檔案(index.html)作為可訪問檔案, 如果不寫這個引數則預設與webpack.cofig.js的同級目錄
        port: 8080 //埠號設為8080, 預設也是8080
    },
    module: {
        rules: [ //配置載入器, 用來處理原始檔, 可以把es6, jsx等轉換成js, sass, less等轉換成css
            {
                exclude: /node_modules|packages/, //路徑
                test: /\.js$/, //配置要處理的檔案格式,一般使用正則表示式匹配
                use: 'babel-loader', //使用的載入器名稱
            },
        ]
    },
    plugins: [ //webpack 通過 plugins 實現各種功能, 比如 html-webpack-plugin 使用模版生成 html 檔案
        new CleanWebpackPlugin(['dist']), //設定清除的目錄
        new HtmlWebpackPlugin({
            filename: 'index.html', //設定生成的HTML檔案的名稱, 支援指定子目錄,如:assets/admin.html
            template: "./src/components/index/index.html" //指定模板檔案的位置
        })
    ],
    output: {
        filename: 'bundle.js', //根據入口檔案輸出不同出口檔案
        path: path.resolve(__dirname, 'dist')
    }
};

執行伺服器

終端輸入 npm run dev

npm run dev

發現報錯 Error: Cannot find module ‘@babel/core’
[email protected] requires Babel 7.x (the package ‘@babel/core’). If you’d like to use Babel 6.x (‘babel-core’), you should install ‘[email protected]’.

通過看 package.json 檔案發現我的 bable-loader 是8版本, 嘗試解除安裝, 然後重新安裝 bable-loader7 版本:

npm uninstall babel-loader
npm install babel-[email protected]7.1.5 --save-dev

重新執行伺服器:

npm run dev

彈出網頁, 配置成功
在這裡插入圖片描述