首頁 > web前端 > js教程 > 主體

怎樣利用webpack搭建react開發環境

php中世界最好的语言
發布: 2018-05-29 17:30:29
原創
1473 人瀏覽過

這次帶給大家怎樣利用webpack搭建react開發環境,利用webpack搭建react開發環境的注意事項有哪些,以下就是實戰案例,一起來看一下。

1.初始化項目

mkdir react-redux && cd react-redux
npm init -y
登入後複製

#2.安裝webpack

npm i webpack -D
登入後複製

npm i -D是npm install --save-dev 的簡寫,是指安裝模組並保存到package.json 的devDependencies中,主要在開發環境中的依賴包. 如果使用webpack 4 版本,還需要安裝CLI。

npm install -D webpack webpack-cli
登入後複製

3.新專案結構

react-redux
 |- package.json
+ |- /dist
+  |- index.html
 |- /src
  |- index.js
登入後複製

index.html




  
  Title

登入後複製

index.js

document.querySelector('#root').innerHTML = 'webpack使用';
登入後複製

非全域安裝下的打包。

node_modules\.bin\webpack src\index.js --output dist\bundle.js --mode development
登入後複製

開啟dist目錄下的html顯示webpack使用

#設定webpack

1.使用設定文件

const path=require('path');
module.exports={
  entry:'./src/index.js',
  output:{
    filename:'bundle.js',
    path:path.resolve(dirname,'dist')
  }
};
登入後複製

執行指令: node_modules\.bin\webpack --mode production 可以進行打包2.NPM 腳本(NPM Scripts) 在在package.json 新增一個npm 腳本(npm script): "build": "webpack --mode production" 運行 npm run build 即可打包

使用webpack構建本機伺服器

webpack-dev-server 提供了一個簡單的web 伺服器,並且能夠即時重新載入。

1.安裝 npm i -D webpack-dev-server 修改設定檔webpack.config.js

const path=require('path');
module.exports={
  entry:'./src/index.js',
  output:{
    filename:'bundle.js',
    path:path.resolve(dirname,'dist')
  },
  //以下是新增的配置
  devServer:{
    contentBase: "./dist",//本地服务器所加载的页面所在的目录
    historyApiFallback: true,//不跳转
    inline: true,//实时刷新
    port:3000,
    open:true,//自动打开浏览器
  }
};
登入後複製

執行webpack-dev-server --progress ,瀏覽器開啟localhost:3000,修改程式碼會即時顯示修改的結果. 新增scripts腳本,執行npm start 自動開啟http://localhost:8080/

"start": "webpack-dev-server --open --mode development"
登入後複製

啟動webpack-dev-server後,在目標文件夾中是看不到編譯後的文件的,實時編譯後的文件都保存到了內存當中。因此使用webpack-dev-server進行開發的時候都看不到編譯後的檔案

2.熱更新

配置一個webpack自帶的插件並且還要在主要js檔案裡檢查是否有module.hot

plugins:[
    //热更新,不是刷新
    new webpack.HotModuleReplacementPlugin()
  ],
登入後複製

在主要js檔案裡加入以下程式碼

if (module.hot){
  //实现热更新
  module.hot.accept();
}
登入後複製

在webpack.config.js中開啟熱更新

devServer:{
    contentBase: "./dist",//本地服务器所加载的页面所在的目录
    historyApiFallback: true,//不跳转
    inline: true,//实时刷新
    port:3000,
    open:true,//自动打开浏览器
    hot:true //开启热更新
  },
登入後複製

熱更新允許在運行時更新各種模組,而無需進行完全刷新.

配置Html模板

1.安裝html-webpack-plugin外掛程式

npm i html-webpack-plugin -D
登入後複製

2.在webpack.config.js裡引用插件

const path=require('path');
let webpack=require('webpack');
let HtmlWebpackPlugin=require('html-webpack-plugin');
module.exports={
  entry:'./src/index.js',
  output:{
    //添加hash可以防止文件缓存,每次都会生成4位hash串
    filename:'bundle.[hash:4].js',
    path:path.resolve('dist')
  },
  //以下是新增的配置
  devServer:{
    contentBase: "./dist",//本地服务器所加载的页面所在的目录
    historyApiFallback: true,//不跳转
    inline: true,//实时刷新
    port:3000,
    open:true,//自动打开浏览器
    hot:true //开启热更新
  },
  plugins:[
    new HtmlWebpackPlugin({
      template:'./src/index.html',
      hash:true, //会在打包好的bundle.js后面加上hash串
    })
  ]
};
登入後複製

運行 npm run build 進行打包,這時候每次npm run build的時候都會在dist目錄下創建很多打好的包.應該每次打包之前都將dist目錄下的文件清空,再把打包好的文件放進去,這裡使用clean-webpack-plugin插件.通過 npm i clean-webpack-plugin -D 指令安裝.然後在webpack.config.js中引用外掛程式.

const path=require('path');
let webpack=require('webpack');
let HtmlWebpackPlugin=require('html-webpack-plugin');
let CleanWebpackPlugin=require('clean-webpack-plugin');
module.exports={
  entry:'./src/index.js',
  output:{
    //添加hash可以防止文件缓存,每次都会生成4位hash串
    filename:'bundle.[hash:4].js',
    path:path.resolve('dist')
  },
  //以下是新增的配置
  devServer:{
    contentBase: "./dist",//本地服务器所加载的页面所在的目录
    historyApiFallback: true,//不跳转
    inline: true,//实时刷新
    port:3000,
    open:true,//自动打开浏览器
    hot:true //开启热更新
  },
  plugins:[
    new HtmlWebpackPlugin({
      template:'./src/index.html',
      hash:true, //会在打包好的bundle.js后面加上hash串
    }),
     //打包前先清空
    new CleanWebpackPlugin('dist')
  ]
};
登入後複製

之後打包便不會產生多餘的檔案.

編譯es6和jsx

1.安裝babel npm i babel-core babel-loader babel-preset-env babel-preset-react babel-preset-stage-0 -D babel-loader : babel載入器babel-preset-env : 根據配置的env 只編譯那些還不支援的特性。 babel-preset-react: jsx 轉換成js

##2.新增.babelrc設定檔

{
 "presets": ["env", "stage-0","react"] //从左向右解析
}
登入後複製
3.修改webpack.config.js

const path=require('path');
module.exports={
  entry:'./src/index.js',
  output:{
    filename:'bundle.js',
    path:path.resolve(dirname,'dist')
  },
  //以下是新增的配置
  devServer:{
    contentBase: "./dist",//本地服务器所加载的页面所在的目录
    historyApiFallback: true,//不跳转
    inline: true//实时刷新
  },
  module:{
    rules:[
      {
        test:/\.js$/,
        exclude:/(node_modules)/, //排除掉nod_modules,优化打包速度
        use:{
          loader:'babel-loader'
        }
      }
    ]
  }
};
登入後複製

#開發環境與生產環境分離

1.安裝webpack-merge

npm install --save-dev webpack-merge
登入後複製
2.新建一個名為webpack.common.js檔案作為公共設定,寫入以下內容:

const path=require('path');
let webpack=require('webpack');
let HtmlWebpackPlugin=require('html-webpack-plugin');
let CleanWebpackPlugin=require('clean-webpack-plugin');
module.exports={
  entry:['babel-polyfill','./src/index.js'],
  output:{
    //添加hash可以防止文件缓存,每次都会生成4位hash串
    filename:'bundle.[hash:4].js',
    path:path.resolve(dirname,'dist')
  },
  plugins:[
    new HtmlWebpackPlugin({
      template:'./src/index.html',
      hash:true, //会在打包好的bundle.js后面加上hash串
    }),
    //打包前先清空
    new CleanWebpackPlugin('dist'),
    new webpack.HotModuleReplacementPlugin() //查看要修补(patch)的依赖
  ],
  module:{
    rules:[
      {
        test:/\.js$/,
        exclude:/(node_modules)/, //排除掉nod_modules,优化打包速度
        use:{
          loader:'babel-loader'
        }
      }
    ]
  }
};
登入後複製
3.新建一個名為webpack.dev.js檔案作為開發環境設定

const merge=require('webpack-merge');
const path=require('path');
let webpack=require('webpack');
const common=require('./webpack.common.js');
module.exports=merge(common,{
  devtool:'inline-soure-map',
  mode:'development',
  devServer:{
    historyApiFallback: true, //在开发单页应用时非常有用,它依赖于HTML5 history API,如果设置为true,所有的跳转将指向index.html
    contentBase:path.resolve(dirname, '../dist'),//本地服务器所加载的页面所在的目录
    inline: true,//实时刷新
    open:true,
    compress: true,
    port:3000,
    hot:true //开启热更新
  },
  plugins:[
    //热更新,不是刷新
    new webpack.HotModuleReplacementPlugin(),
  ],
});
登入後複製
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 (

佳佳加油

);   } } 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(
  
    
  ,
  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"
     })
   ]
 });
登入後複製

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

详细解析微信小程序入门教程+案例

怎样使用angularjs中http服务器

以上是怎樣利用webpack搭建react開發環境的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!