使用webpack搭建react开发环境的方法(4)

4.新建一个名为webpack.prod.js的文件作为生产环境配置

const merge = require('webpack-merge');
 const path=require('path');
 let webpack=require('webpack');
 const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
 const common = require('./webpack.common.js');
 module.exports = merge(common, {
   mode:'production',
   plugins: [
     new UglifyJSPlugin()
   ]
 });

配置react

1.安装react、

react-dom npm i react react-dom -S 

2.新建App.js,添加以下内容.

import React from 'react';
class App extends React.Component{
  render(){
    return (<div>佳佳加油</div>);
  }
}
export default App;

3.在index.js添加以下内容.

import React from 'react';
import ReactDOM from 'react-dom';
import {AppContainer} from 'react-hot-loader';
import App from './App';
ReactDOM.render(
  <AppContainer>
    <App/>
  </AppContainer>,
  document.getElementById('root')
);

if (module.hot) {
  module.hot.accept();
}

4.安装 react-hot-loader

npm i -D react-hot-loader 

5.修改配置文件 在 webpack.config.js 的 entry 值里加上 react-hot-loader/patch,一定要写在entry 的最前面,如果有 babel-polyfill 就写在babel-polyfill 的后面

6.在 .babelrc 里添加 plugin, "plugins": ["react-hot-loader/babel"]

处理SASS

1.安装 style-loader css-loader url-loader

npm install style-loader css-loader url-loader --save-dev 

2.安装 sass-loader node-sass

npm install sass-loader node-sass --save-dev 

3.安装 mini-css-extract-plugin ,提取单独打包css文件

npm install --save-dev mini-css-extract-plugin 

4.配置webpack配置文件

webpack.common.js

{
  test:/\.(png|jpg|gif)$/,
  use:[
    "url-loader"
  ]
},

webpack.dev.js

{
  test:/\.scss$/,
  use:[
    "style-loader",
    "css-loader",
    "sass-loader"
  ]
}

webpack.prod.js

const merge = require('webpack-merge');
 const path=require('path');
 let webpack=require('webpack');
 const MiniCssExtractPlugin=require("mini-css-extract-plugin");
 const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
 const common = require('./webpack.common.js');
 module.exports = merge(common, {
   mode:'production',
   module:{
     rules:[
       {
         test:/\.scss$/,
         use:[
           // fallback to style-loader in development
           process.env.NODE_ENV !== 'production' ? 'style-loader' : MiniCssExtractPlugin.loader,
           "css-loader",
           "sass-loader"
         ]
       }
     ]
   },
   plugins: [
     new UglifyJSPlugin(),
     new MiniCssExtractPlugin({
       // Options similar to the same options in webpackOptions.output
       // both options are optional
       filename: "[name].css",
       chunkFilename: "[id].css"
     })
   ]
 });

      

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/197.html