webpack 快速構建 React 學習環境(1)

螞蟻哈哈哈發表於2018-06-29

React 官方有一套腳手架工具,是初學者的最好選擇,可以讓初學者集中注意力在 React 本身。

本人對腳手架有點兒牴觸(可能主要是對未知的恐懼),從開始學習 React 就走了自己搭建開發環境的路線,這裡總結下搭建過程,希望能幫助和我一樣不願使用腳手架工具,但又急需一個練習環境的初學者。

文章同步釋出在個人部落格站點

本節目標

基於 webpack 構建一個最小 React 專案開發環境,以把下面的 React 元件成功渲染在頁面上為目標,即顯示 Hello React 到頁面。

import React from 'react';
import ReactDOM from 'react-dom';
export default class HelloReact extends React.Component{
constructor(props) {
super(props);

} render(){
return( <
div>
Hello React<
/div>
);

}
}ReactDOM.render(<
HelloReact />
, document.getElementById('root'));
複製程式碼

建立專案目錄:

mkdir react-democd react-demo複製程式碼

初始化 npm 環境:

npm init  //這裡基本一路回車即可;需要你的系統安裝有 node。我安裝的 node: v8.2.1、npm: 5.3.0。複製程式碼

完成後會在專案根目錄下生成 package.json 檔案:

{ 
"name": "react-demo", "version": "1.0.0", "description": "", "main": "index.js", "scripts": {
"test": "echo \"Error: no test specified\" &
&
exit 1"

}, "author": "wewin", "license": "ISC"
}複製程式碼

package.json 檔案的作用是記錄各個軟體的依賴關係,類似 Rails 中的 Gemfile

基本依賴安裝

React 專案依賴的軟體包 react、react-dom 是必須的。因為目標是要構建使用 webpack 打包的開發環境,webpack、webpack-cli 不能少。

npm i react -Dnpm i react-dom -Dnpm i webpack -Dnpm i webpack-cli -D複製程式碼

此時專案結構如下:

react-demo tree -L 1 ..├── node_modules  // npm 包的安裝目錄├── package-lock.json└── package.json1 directory, 2 files複製程式碼

node_modules 是依賴包的安裝目錄,package-lock.json 是依賴包版本鎖定。可以保證多個環境或者多個協作者開發環境中依賴包版本一致性。

此時 package.json 內容如下

{ 
"name": "react-demo", "version": "1.0.0", "description": "", "main": "index.js", "scripts": {
"test": "echo \"Error: no test specified\" &
&
exit 1"

}, "author": "wewin", "license": "ISC", "devDependencies": {
"react": "^16.4.1", "react-dom": "^16.4.1", "webpack": "^4.12.2", "webpack-cli": "^3.0.8"
}
}複製程式碼

建立專案基本結構

首先建立 src、build 兩個目錄

➜  react-demo tree . -L 1.├── build  // React 打包的出口, webpack 下預設打包在 dist 目錄下,個人習慣放在 build 下├── node_modules├── package-lock.json├── package.json└── src // 原始碼檔案,後面開發基本在這個目錄下完成複製程式碼

在 src 目錄下建立 webpack 打包的入口檔案

cd srctouch index.js複製程式碼

建立 webpack 配置檔案

使用 webpack 打包需要建立一個 webpack 配置檔案, webpack4 很多配置項都有了預設值,這裡是我自己的一個簡單配置。

1、最基本的打包入口、出口的配置 (webpack4 入口、出口有預設配置)

const path = require('path');
module.exports = {
entry: './src/index.js', output: {
path: path.resolve(__dirname, 'build'), // 打包出口,即打包後的檔案會放在這個目錄下 filename: '[name].[hash:8].js' // 打包後的檔名 publicPath: './', // 靜態資源相對路徑
}
};
複製程式碼

2、使用 html-webpack-plugin 外掛自動生成檔案 html 檔案,並插入 <
script>
標籤的特性。 [html-webpack-plugin] (https://github.com/jantimon/html-webpack-plugin#options) 外掛很智慧,可以根據你的配置生成你想要的 html。

安裝和配置這個外掛:

npm i html-webpack-plugin -D複製程式碼

webpack.config.js:

const path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/index.js', output: {
path: path.resolve(__dirname, 'build'), filename: '[name][hash:8].js', publicPath: './',
}, plugins: [new HtmlWebpackPlugin({
filename: 'index.html', // 指定生成的檔名,預設就是 index.html template: 'src/index.html' // 指定 html 生成使用用的模版檔案,我指定 使用 ```src/index.html``` 作為模版檔案
})]
};
複製程式碼

模版檔案 src/index.html, 內容如下:

<
!DOCTYPE html>
<
html lang="en">
<
head>
<
title>
Hello React<
/title>
<
/head>
<
body>
<
div id="root">
<
/div>
<
/body>
<
/html>
複製程式碼

第一個 React 應用。

就是開頭提到的在頁面上顯示 ‘Hello React’ 的小應用。

src/index.js:

import React from 'react';
import ReactDOM from 'react-dom';
export default class HelloReact extends React.Component{
constructor(props) {
super(props);

} render(){
return( <
div>
Hello React<
/div>
);

}
}ReactDOM.render(<
HelloReact />
, document.getElementById('root'));
複製程式碼

編譯 React 應用

./node_modules/.bin/webpack 複製程式碼

報錯如下:

WARNING in configurationThe 'mode' option has not been set, webpack will fallback to 'production' for this value. Set 'mode' option to 'development' or 'production' to enable defaults for each environment.複製程式碼

這是需要加 ‘mode’ 引數,加引數後執行:

./node_modules/.bin/webpack --mode=development複製程式碼

報錯:

ERROR in ./src/index.js 1:18Module parse failed: Unexpected token (1:18)You may need an appropriate loader to handle this file type.>
import React from react;
| import ReactDOM from react-dom;
複製程式碼

這是因為 react 使用的 es6 語法需要使用: babel-loader 來翻譯 es6 及最新的 js 語法

安裝 babel loader

npm i "babel-loader@^8.0.0-beta" @babel/core @babel/preset-env -D複製程式碼

webpack.config.js 配置:

const path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/index.js', output: {
path: path.resolve(__dirname, 'build'), filename: '[name].[hash:8].js', publicPath: './',
}, module: {
rules: [ {
test: /\.js$/, exclude: /(node_modules)/, use: {
loader: 'babel-loader'
},
}, ],
}, plugins: [new HtmlWebpackPlugin()]
};
複製程式碼

在專案根目錄下建立 babel 的配置檔案 .babelrc:

{ 
"presets": [ ["@babel/preset-env", {
"targets": {
"node": "current"
}
}] ]
}複製程式碼
./node_modules/.bin/webpack --mode=development複製程式碼

繼續報錯:

ERROR in ./src/index.jsModule build failed (from ./node_modules/babel-loader/lib/index.js):SyntaxError: /Users/wewin/reactLearn/react-demo/src/index.js: Unexpected token (10:12)   8 |   9 |   render(){>
10 | return( <
div>
Hello React<
/div>
);
| ^ 11 |
} 12 |
} 13 |複製程式碼

這是因為 babel 需要配置 react preset 來支援 react 語法解析。

安裝 @babel/preset-react :

npm i @babel/preset-react -D複製程式碼

修改 babel 配置檔案 .babelrc:

{ 
"presets": [ ["@babel/preset-env", {
"targets": {
"node": "current"
}
}], "@babel/preset-react" ]
}複製程式碼

再次編譯

./node_modules/.bin/webpack --mode=development複製程式碼

congratulations! 成功編譯:

Hash: e09b122cfb00f2a585f8Version: webpack 4.12.2Time: 898msBuilt at: 2018-06-29 08:19:29           Asset       Size  Chunks             Chunk Namesmain.e09b122c.js    713 KiB    main  [emitted]  main      index.html  200 bytes          [emitted][./src/index.js] 648 bytes {main
} [built] + 21 hidden modulesChild html-webpack-plugin for "index.html": 1 asset [./node_modules/html-webpack-plugin/lib/loader.js!./src/index.html] 337 bytes {0
} [built] [./node_modules/webpack/buildin/global.js] (webpack)/buildin/global.js 489 bytes {0
} [built] [./node_modules/webpack/buildin/module.js] (webpack)/buildin/module.js 497 bytes {0
} [built]複製程式碼

編譯成功後在 build 目錄下生成了 index.html 和打包後的 js 檔案 main.e09b122c.js,index 檔案就是 html-webpack-plugin 外掛生成的,會自動插入生成的 js 檔案。

build/index.html:

<
!DOCTYPE html>
<
html lang="en">
<
head>
<
title>
Hello React<
/title>
<
/head>
<
body>
<
div id="root">
<
/div>
<
script type="text/javascript" src="./main.e09b122c.js">
<
/script>
<
/body>
<
/html>
複製程式碼

用瀏覽器開啟 build/index.html 檔案,就可以看到 Hello React 正常輸出。

總結

本篇主要目的是總結如何搭建一個最小 React 專案的開發環境,適合牴觸腳手架工具,但是又需要一個 React 練習環境的初學者。對 webpack 及相關外掛的相關東西基本一筆就帶過了。這個作為開發還不夠智慧,如不能熱載入,每次對程式碼有修改就要重新編譯,重新重新整理頁面,簡直毫無開發體驗可言,這些,請參考第二篇: webpack 快速構建 React 學習環境(2)– 熱更新

來源:https://juejin.im/post/5b3597d851882574be4921f9

相關文章