1. 程式人生 > >基於webpack構建一個React應用

基於webpack構建一個React應用

1,建立一個空白檔案 React-music-player

2,使用npm init 建立一個package.json檔案,並安裝相關依賴

"dependencies": {
    "autoprefixer": "^9.0.2",
    "pubsub-js": "^1.6.0",
    "react": "^16.4.1",
    "react-dom": "^16.4.1",
    "react-hot-loader": "^4.3.4",
    "react-router": "^4.3.1"
},
"devDependencies": {
    "babel-core": "^6.26.3",
    "babel-loader": "^7.1.5",
    "babel-plugin-react-transform": "^3.0.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "css-loader": "^1.0.0",
    "extract-text-webpack-plugin": "^3.0.2",
    "html-webpack-plugin": "^3.2.0",
    "json-loader": "^0.5.7",
    "less": "^3.8.0",
    "less-loader": "^4.1.0",
    "style-loader": "^0.21.0",
    "webpack": "^4.16.3",
    "webpack-cli": "^3.1.0",
    "webpack-dev-server": "^3.1.5"
}

3,建立webpack.config.js 檔案,新增相關程式碼

注意:webpack v2 之後都用rules取代了loaders

var path=require('path');

module.exports = {
    entry:'./app/index.js',
    output:{
        path:path.resolve(__dirname, './dist'),
        filename:'bundle.js'
    },
    module:{
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                loader: "babel-loader",
                query:
                {
                    presets:['react','es2015']
                }
            },
            {
                test: /\.json?$/,
                loader: 'json'
            },
            {
                test: /\.css$/,
                loader: "style!css"
            },
            {  
                test: /\.less/,
                loader: 'style-loader!css-loader!less-loader'
            }
        ]
    }
}

4,新增其他檔案,包括入口檔案index.js,打包資料夾dist

 

 

 

5,對資料夾使用webpack命令進行打包操作

6,新增一個html檔案,引入index.js測試效果

7,使用webpack-dev-server搭建開發環境,實現自動重新整理

修改入口檔案和外掛引入配置

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

	entry:[
		//webpack-dev-server的入口新增,熱更新工具
		'webpack-dev-server/client?http://localhost:3000',
		'webpack/hot/only-dev-server',
		'react-hot-loader/patch',
		path.join(__dirname,'app/index.js')
	],
	output:{
		path:path.resolve(__dirname, '/dist/'),
		filename:'[name].js',
		publicPath:'/'
	},
	plugins:[
	//使用一個外掛,可以根據模板自動生成html,外掛處理模板連結最後的打包檔案
		new HtmlWebpackPlugin({
			template:'./index.tpl.html', //模板
			inject:'body',
			filename:'./index.html'
		}),
		new webpack.optimize.OccurrenceOrderPlugin(),
        	new webpack.HotModuleReplacementPlugin(),
       	 	new webpack.NoEmitOnErrorsPlugin(),
       	 	new webpack.DefinePlugin({
         		 'process.env.NODE_ENV': JSON.stringify('development')
       		})
	],

8,配置一個server.js檔案

var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
var config = require('./webpack.config');
//新建一個server,將webpack.config的配置傳入
new WebpackDevServer(webpack(config), {
    publicPath: config.output.publicPath,
    hot: true,
    historyApiFallback: true,
// It suppress error shown in console, so it has to be set to false.
    quiet: false,
// It suppress everything except error, so it has to be set to false as well
// to see success build.
    noInfo: false,
    stats: {
// Config for minimal console.log mess.
        assets: false,
        colors: true,
        version: false,
        hash: false,
        timings: false,
        chunks: false,
        chunkModules: false
    }

}).listen(3000, 'localhost', function (err) { //監聽埠
    if (err) {
        console.log(err);
    }
    console.log('Listening at localhost:3000');

});

9,修改index.js, 引入一個Hello元件

import React from 'react'
import { render } from 'react-dom'
import './index.less'
import Hello from './component/hello'

render(
    <Hello></Hello>,
    document.getElementById('root')
);

10,新建一個component資料夾,放入Hello.js元件和Hello.less樣式表,並匯出Hello元件

 

11,新的檔案結構變為

import React from 'react'
import './hello.less'

export default class Hello extends React.Component {
    render(){
        return(
            <div className="hello-component">
                Hello React
            </div>
        );
    }
}

12,為了實現瀏覽器實時更新,修改配置檔案

index.js

import React from 'react'
import { render } from 'react-dom'
import Hello from './component/hello'
import { AppContainer} from 'react-hot-loader'

render(
//將Hello元件包裹在AppContainer元件中
    <AppContainer>
        <Hello />
    </AppContainer>,
    document.getElementById('root')
);


if(module.hot){
    module.hot.accept('./component/hello',() => {
        const NewHello = require('./component/hello').default;
        render(
            <AppContainer>
                <NewHello />
            </AppContainer>,
            document.getElementById('root')
        );
    });
}

13,執行node server命令即可實現實時除錯