從零開始搭建webpack+react開發環境

環境主要依賴版本

  • webpack@4.8.1
  • webpack-cli@2.1.3
  • webpack-dev-server@3.1.4
  • react@16.3.2
  • babel-core@6.26.3
  • babel-preset-env@1.6.1
  • bable-preset-react@6.24.1

webpack安裝及配置

1. 起步

新建項目目錄,初始化npm,新建開發源目錄javascript

mkdir webpack-react && cd webpack-react
npm init -y
mkdir src
複製代碼

2.webpack-cli

webpack從4.x版本開始,須要同時安裝webpack,webpack-cli(此工具用於在命令行中運行webpack)。css

npm install webpack webpack-cli --save-dev
複製代碼

3.wepback配置文件

在項目根目錄新建webpack.config.js文件,此文件爲webpack運行核心文件。html

webpack.config.js 基本配置

// webpack.config.js
const path = require('path');

module.exports = {
    entry: './src/index.js',                           // 入口文件
    output: {                                             // webpack打包後出口文件
        filename: 'app.js',                             // 打包後js文件名稱
        path: path.resolve(__dirname, 'dist')    // 打包後自動輸出目錄
    }
}
複製代碼

package.json 文件 scripts配置java

"scripts": {
    "build": "webpack"
}
複製代碼

此時在命令行運行npm run build,就能執行webpack了,webpack會自動去找項目根目錄裏的webpack.config.js文件,執行打包。node

npm run build
// webpack打包後的項目
├── dist
│   └── app.js             // 打包後的app.js
├── package.json
├── src
│   └── index.js           // 源目錄入口文件
└── webpack.config.js
複製代碼

webpack.config.js module相關配置

webpack 視全部文件都爲模塊,圖片,css文件,字體等靜態資源都會打包進js文件,因此會須要用到loader文件,更多Loaders能夠查詢網址,接下來咱們安裝一些必要的Loader文件。react

npm install style-loader css-loader url-loader --save-dev
複製代碼

webpack.config.js加入module模塊webpack

module.exports = {
	entry: './src/index.js',
	output: {
		filename: 'app.js',
		path: path.resolve(__dirname, 'dist')
	},
	module: {
		rules: [
			{
				test: /\.css$/,
				use: ['style-loader', 'css-loader']
			},
			{
				test: /\.(png|svg|jpg|gif)$/,
				use: ['url-loader']
			},
			{
				test: /\.(woff|woff2|eot|ttf|otf)$/,
				use: ['url-loader']
			}
		]
	}
}
複製代碼

引入loader後,就能夠在你的src/index.js文件import你想引入的css文件或者其餘靜態資源。web

cd src && touch main.css
複製代碼

src/index.js 文件引入cssnpm

import "./main.css";
複製代碼

webpack.config.js plugins配置

主要的js文件和靜態文件都能成功打包成一個js文件後,咱們須要把這個js文件放到html文件裏,webpack插件***html-webpack-plugin***就是幹這個事兒的,它能自動生成一個html文件並把咱們打包好的js文件放入html。json

npm install html-webpack-plugin --save-dev
複製代碼

webpack.config.js 配置plugins

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin'); // 引入插件

module.exports = {
	entry: './src/index.js',
	output: {
		filename: 'app.js',
		path: path.resolve(__dirname, 'dist')
	},
	module: {
		rules: [
			{
				test: /\.css$/,
				use: ['style-loader', 'css-loader']
			},
			{
				test: /\.(png|svg|jpg|gif)$/,
				use: ['url-loader']
			},
			{
				test: /\.(woff|woff2|eot|ttf|otf)$/,
				use: ['url-loader']
			}
		]
	},
	plugins: [
		new HtmlWebpackPlugin({title: 'production'})		// 配置plugin
	]
};
複製代碼

執行npm run build後,咱們能夠看到dist目錄多出一個index.html文件。

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>name</title>
  </head>
  <body>
 // 打包後的app.js已經被自動插入了html文件
  <script type="text/javascript" src="app.js"></script></body>
</html>
複製代碼

到這裏,webpack最簡單最基本的需求已經配置完畢。 此時項目結構爲:

├── dist                        // 生產目錄
│   ├── app.js
│   └── index.html
├── package.json
├── src                        // 源目錄
│   ├── index.js
│   └── main.css
└── webpack.config.js
複製代碼

React 的webpack配置

安裝react

npm install react react-dom --save
複製代碼

安裝react,wepback轉換依賴

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配置文件

在項目根目錄下新建.babelrc文件,此文件爲bable核心配置,babel會自動在項目根目錄下識別。

// .babelrc
{
	"presets": ["env", "react"]
}
複製代碼

webpack babel-loader 配置

// 在webpack.config.js 的modules.rules中加入此配置
{
	test: /\.(js|jsx)$/,
	exclude: /node_modules/,
	use: {
		loader: 'babel-loader'
	}
}				    
複製代碼

html-webpack-plugin 模板配置

咱們知道react須要獲取頁面一個根元素,而後render纔會生效,咱們能夠新建一個html文件,讓html-webpack-plugin插件基於這個文件來進項打包。

因此咱們在根目錄下新建一個html文件,以此文件做模板。

// index.html
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
        // react須要的渲染根元素
	<div id="root"></div>
</body>
</html>
複製代碼

此時webpack.config.js配置:

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

module.exports = {
	entry: './src/index.js',
	output: {
		filename: 'app.js',
		path: path.resolve(__dirname, 'dist')
	},
	module: {
		rules: [
			{
				test: /\.(js|jsx)$/,
				exclude: /node_modules/,
				use: {
					loader: 'babel-loader'
				}
			},
			{
				test: /\.css$/,
				use: ['style-loader', 'css-loader']
			},
			{
				test: /\.(png|svg|jpg|gif)$/,
				use: ['url-loader']
			},
			{
				test: /\.(woff|woff2|eot|ttf|otf)$/,
				use: ['url-loader']
			}
		]
	},
	plugins: [
		new HtmlWebpackPlugin({
			title: 'production',
			template: './index.html'    // 模板文件位置
		})		
	]
};
複製代碼

書寫React,運行webpack

// src/index.js
import React from 'react';
import ReactDom from 'react-dom';

import './main.css'

ReactDom.render(
	<h1>hello world</h1>,
	document.getElementById('root')
);
複製代碼

運行npm run build,生成dist目錄,打開dist目錄中的index.html文件,能夠發現瀏覽器已正常渲染"hello world"。

dev環境熱更新配置

react的wepack完成之後,是否是發現每修改一次代碼,想看到效果,得從新打包一次才行。webpack-dev-server配置能夠幫助咱們實現熱更新,在開發環境解放咱們的生產力。

安裝webpack-dev-server

npm install webpack-dev-server  --save-dev
複製代碼

webpack.config.js 配置

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

module.exports = {
	entry: './src/index.js',
	output: {
		filename: 'app.js',
		path: path.resolve(__dirname, 'dist')
	},
	module: {
		rules: [
			{
				test: /\.(js|jsx)$/,
				exclude: /node_modules/,
				use: {
					loader: 'babel-loader'
				}
			},
			{
				test: /\.css$/,
				use: ['style-loader', 'css-loader']
			},
			{
				test: /\.(png|svg|jpg|gif)$/,
				use: ['url-loader']
			},
			{
				test: /\.(woff|woff2|eot|ttf|otf)$/,
				use: ['url-loader']
			}
		]
	},
	plugins: [
		new HtmlWebpackPlugin({
			title: 'production',
			template: './index.html'    
		}),
		// hot 檢測文件改動替換plugin
		new webpack.NamedModulesPlugin(),      
		new webpack.HotModuleReplacementPlugin()		
	],
       // webpack-dev-server 配置
	devServer: {
		contentBase: './dist',
		hot: true
	},
};
複製代碼

運行webpack-dev-server

在 package.json 文件 加入 scripts 配置:

"scripts": {
  "build": "webpack",
  "dev": "webpack-dev-server --open --mode development"  // webpack-dev-server
},
複製代碼

命令行運行 npm run dev

能夠在瀏覽器中輸入localhost:8080 內容即爲dist目錄下的index.html內容。修改src/index.js中的內容或者依賴,即實時在瀏覽器熱更新看到。

至此,react的webpack的基礎開發環境已所有配置完畢。

相關文章
相關標籤/搜索