看到有意思的demo想練練手時,須要環境去實現功能,這個時候就須要快速搭建一個環境,接下來就教你如何快速實現搭建一個react+webpack環境。
到這一步,在你的文件夾下就會出現一個myapp的文件夾,你接下來的項目就是在這裏面進行的,固然你也能夠換名字的。css
後面的安裝插件或者其餘依賴的時候,要先將終端運行的環境調整到當前文件夾,即myapp(在終端運行cd myapp便可)html
調整好文件夾後就能夠安裝yarn了,運行npm install yarn
這個時候你會發如今你的myapp文件夾下多了關於yarn的文件,這就代表你可使用yarn來加載依賴了node
{ "name": "myapp", "version": "0.1.0", "private": true, "dependencies": { "react": "^16.5.0", "react-dom": "^16.5.0", "react-scripts": "1.1.5" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test --env=jsdom", "eject": "react-scripts eject" } }
打開package.json,你會發現裏面其實已經有內容了,在終端運行yarn start,就會彈出這樣的界面
react
這樣就說明目前你搭建的一切正常,下面就是瘋狂的刪文件的階段了(由於不須要那麼多文件)webpack
將文件夾裏的內容刪成上圖這樣,而後在src下建立一個index.html文件做爲入口文件,其餘的文件中的內容也要修改web
{ "name": "myapp", "version": "0.1.0", "private": true, "dependencies": { "react": "^16.5.0", "react-dom": "^16.5.0" }, "scripts": { } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <div id ='root'></div> </body> </html>
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import './index.css'; class App extends Component{ render(){ return( <div class = 'APP' /> ) } } ReactDOM.render(<APP/>,getElementById('root'))
index.css中的內容能夠不變,基本的react就搭成了,如今就是加上webpack進行打包的時候了。npm
const path = require('path') const webpack = require('webpack') function resolve(relatedPath) { return path.join(__dirname, relatedPath) } module.exports = { entry: { index: resolve('../myapp/src/index.js') }, output: { path: resolve('../myapp/dist'), filename: '[name].[hash:4].js', }, resolveLoader: { moduleExtensions: ['-loader'] }, module: { rules: [ { test: /\.js[x]?$/, exclude: /node_modules/, loader: 'babel', query: { presets: ['react', 'es2015', 'stage-0'] } }, { test: /\.css/, loader: 'css' }, { test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, loader: 'url', options: { limit: 8192, name: 'img/[name].[hash:4].[ext]' } }, { test: /\.html$/, //靜態資源 loader: 'html', } ], } }
打包事後的文件會在myapp下的dist文件夾中生成,入口文件是src下面的index.js。json
直接將文件中的內容改爲下面的樣子babel
{ "name": "myapp", "version": "0.1.0", "private": true, "dependencies": {//新增了webpack "react": "^16.5.0", "react-dom": "^16.5.0", "webpack": "~3.10.0" }, "devDependencies": {//新增了babel轉換JSX和其餘插件 "babel-core": "~6.26.0", "babel-eslint": "~8.2.1", "babel-loader": "~7.1.2", "babel-plugin-import": "^1.8.0", "babel-plugin-transform-decorators-legacy": "~1.3.4", "babel-plugin-transform-runtime": "~6.23.0", "babel-preset-env": "^1.6.1", "babel-preset-es2015": "^6.24.1", "babel-preset-react": "^6.24.1", "babel-preset-stage-0": "^6.24.1", "css-loader": "~0.28.9", "url-loader": "~0.6.2" }, "scripts": {//新增了打包的配置文件 "build": "webpack --config webpack.config.js" } }
若是你的myapp下也生成了這個dist文件夾,而且在裏面有index文件,那麼恭喜你,一個最簡單的react+webpack環境就搭好了。app
webpack的功能很強大,隨着後面的組件之間的調用愈來愈複雜,會有相應的插件去處理相應的問題,那些之後再講吧。