環境準備工做:windows七、webStorm 2017.1.四、Nodejs 8.7.0、npm 5.4.2javascript
PS:安裝的時咱們都帶上版本,這樣即使webpack版本發生變化,也不會出現版本問題。css
初始化package.json文件
npm inithtml
npm安裝react、react-dom包java
npm install react@16.3.0 react-dom@16.3.0 --save
或者node
npm i -S react@16.3.0 react-dom@16.3.0
npm安裝webpack、webpack-cli等包react
npm install webpack@4.4.1 webpack-cli@2.0.13 webpack-dev-server@3.1.1 webpack-merge@4.1.2 babel-cli@6.26.0 babel-preset-env@1.6.1 babel-preset-react@6.24.1 babel-preset-react-hmre@1.1.1 babel-loader@7.1.4 --save-dev
或者webpack
npm i -D webpack@4.4.1 webpack-cli@2.0.13 webpack-dev-server@3.1.1 webpack-merge@4.1.2 babel-cli@6.26.0 babel-preset-env@1.6.1 babel-preset-react@6.24.1 babel-preset-react-hmre@1.1.1 babel-loader@7.1.4
文件夾結構git
各個文件的內容github
Index.jsxweb
import React from 'react'; class Index extends React.Component { render() { return ( <div> 這是首頁women修改一下 </div> ); } } export default Index;
index.js
import React from 'react'; import ReactDOM from 'react-dom'; import Index from './views/Index'; ReactDOM.render(<Index/>, document.getElementById('app'));
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta content="telephone=no" name="format-detection"> <title>react</title> </head> <body> <div id="app"></div> <script type=text/javascript src=js/index.js></script> </body> </html>
base.config.js
let config = { entry: { 'index':'./src/index.js' }, resolve: { extensions: [".js", ".json", ".jsx", ".css"], } }; module.exports = config;
dev.config.js
const webpack = require('webpack');//引入webpack const opn = require('opn');//打開瀏覽器 const merge = require('webpack-merge');//webpack配置文件合併 const path = require("path"); const baseWebpackConfig = require("./base.config");//基礎配置 const webpackFile = require("./file.config");//一些路徑配置 let config = merge(baseWebpackConfig, { /*設置開發環境*/ mode: 'development', output: { path: path.resolve(webpackFile.devDirectory), filename: 'js/[name].js', chunkFilename: "js/[name].js", publicPath: '' }, plugins: [ /*設置熱更新*/ new webpack.HotModuleReplacementPlugin(), ], module: { rules: [ { test: /\.(js|jsx)$/, use: [ 'babel-loader', ], include: [ path.resolve(__dirname, "../src") ], exclude: [ path.resolve(__dirname, "../node_modules") ], } ] }, /*設置api轉發*/ devServer: { host: '0.0.0.0', port: 8080, hot: true, inline: true, contentBase: path.resolve(webpackFile.devDirectory), historyApiFallback: true, disableHostCheck: true, proxy: [ { context: ['/api/**', '/u/**'], target: 'http://127.0.0.1:8080/', secure: false } ], /*打開瀏覽器 並打開本項目網址*/ after() { opn('http://localhost:' + this.port); } } }); module.exports = config;
file.config.js
module.exports = { devDirectory:'static',/*開發目錄*/ proDirectory:'dist',/*發佈目錄*/ resource:'resource',/*靜態資源*/ };
package.json文件中添加腳本命令
"dev": "webpack-dev-server --devtool eval --progress --colors --profile --config webpack/dev.config.js"
最後執行運行命令
效果圖