一聚教程网:一个值得你收藏的教程网站

热门教程

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

时间:2022-06-25 16:02:34 编辑:袖梨 来源:一聚教程网

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.binwebpack srcindex.js --output distbundle.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.binwebpack --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"
     })
   ]
 });

热门栏目