自己簡要總結了一下webpack+react搭建環境的各個步驟 ...
近日自己項目遇到需要用webpack搭建react環境,查了挺多 ,自己總結一下
1.下載安裝最新版node.js(https://nodejs.org/en/)
2.主要看自己網路情況,可以選擇安裝淘寶鏡像去搭建環境
npm config set registry http://registry.npm.taobao.org/
3.通過npm/cnpm全局安裝webpack, Babel, Webpack-dev-server:
npm install babel webpack webpack-dev-server -g
4.選擇項目存放目錄,用npm init 初始化 npm 項目
5.在項目中安裝 react, react-dom
npm install react react-dom --save
6.在項目中安裝 Babel 轉換器,這裡用到插件 babel-preset-react, babel-preset-latest,latest 即最新的 ES 規範,包括了 Async/Await 這些新特性。
npm install babel-loader babel-core babel-preset-react babel-preset-latest --save
7.創建項目文件,main.js 即項目入口文件,App.js 即 React 組件主文件
文件目錄最終為:
8.配置webpack,編輯webpack.config.js
module.exports = { entry: './main.js', // 入口文件路徑 output: { path: '/', filename: 'index.js' }, devServer: { inline: true, port: 3333 }, module: { loaders: [ { test: /\.js$/, // babel 轉換為相容性的 js exclude: /node_modules/, loader: 'babel-loader', query: { presets: ['react', 'latest'] } } ] } }
9.寫index.html:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>React Hello World</title> </head> <body> <div id="app"></div> <script src="index.js"></script> </body> </html>
寫App.js:
import React from 'react'; class App extends React.Component { render() { return <div>Hello World!</div> } } export default App
寫Main.js:
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; ReactDOM.render(<App />, document.getElementById('app'));
10.配置 npm scripts, 編輯 package.json,在"scripts"屬性處添加一行:
"scripts": { "start": "webpack-dev-server" },
11.基本的框架搭建完畢,npm start 然後打開 http://localhost:3333 試試:
npm start