webpack - 手把手教你使用 webpack 搭建 react 开发环境(从零开始搭建 webpack+react 开发环境的详细步骤)

安装和使用webpack

  1. 初始化项目
mkdir react-redux && cd react-redux
npm init -y
  1. 安装webpack
npm i webpack -D

npm i -D 是 npm install --save-dev 的简写,是指安装模块并保存到 package.json 的 devDependencies中,主要在开发环境中的依赖包. 如果使用webpack 4+ 版本,还需要安装 CLI。

npm install -D webpack webpack-cli
  1. 新建一下项目结构
  react-redux
  |- package.json
+ |- /dist
+   |- index.html
  |- /src
    |- index.js

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="root"></div>
<script src="bundle.js"></script>
</body>
</html>

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 可以以进行打包

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进行开发的时候都看不到编译后的文件

  1. 热更新

配置一个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
  1. 在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"] //从左向右解析
}
  1. 修改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
  1. 新建一个名为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'
                }
            }
        ]
    }
};
  1. 新建一个名为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(),
    ],
});
  1. 新建一个名为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;
  1. 在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();
}
  1. 安装react-hot-loader
npm i -D react-hot-loader
  1. 修改配置文件 在 webpack.config.js 的 entry 值里加上 react-hot-loader/patch,一定要写在entry 的最前面,如果有 babel-polyfill 就写在babel-polyfill 的后面

  2. 在 .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
  1. 安装sass-loader node-sass
npm install sass-loader node-sass --save-dev
  1. 安装mini-css-extract-plugin,提取单独打包css文件
npm install --save-dev mini-css-extract-plugin
  1. 配置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"
         })
     ]
 });
  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 24
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 24
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

街尾杂货店&

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值