webpack04服务器配置

webpack配置

  • entry
  • output
    • filename
    • path
    • publicPath 。。 打包引入的基本路径,,,比如引入一个bundle.js,。引用之后的路径就是 publicPath+filename
      -devServer:
    • static : 静态文件的位置。。。
    • host
    • port
    • open
    • compress : 静态资源是否用gzip压缩
    • historyApiFallback: 服务器刷新页面会404,,因为如果是react,或者vue路由导过去的页面,,直接拉去服务器是没有的,会404,设置为true,会将所有404页面请求重定向到index.html
    • proxy : 设置代理
      • changeOrigin :改变请求来源,,
      • target
      • pathRewrite
js 复制代码
# 使用webpack serve启动服务器
 "dependencies": {
    "axios": "^1.7.9",
    "html-webpack-plugin": "^5.6.3",
    "webpack": "^5.97.1",
    "webpack-cli": "^6.0.1",
    "webpack-dev-server": "^5.2.0"
  },
js 复制代码
const HtmlWebpackPlugin = require("html-webpack-plugin")

const path = require("path");
module.exports={
    mode:"development",
    devtool: "source-map",
    entry: "./src/index.js",
    output:{
        path:path.resolve(__dirname,"./dist"),
        filename:"bundle.js",
        publicPath:"/"

    },
    devServer:{
        static:["public",{
            directory: path.resolve(__dirname,"./abc"),
            watch:true
        }],// 静态文件的位置

        host:"0.0.0.0",// ,局域网可以通过ip访问  ==》 localhost会被解析成127.0.0.1,回环地址:主机自己发出去的包,直接被自己接收
        port:9000,
        open:true,
        compress:true, // 是否为静态文件开启gzip
        proxy:[
            {
                context:["/api"],
                target:"http://localhost:8080/",
                pathRewrite:{
                    "^/api":""
                },
                changeOrigin:true

            }
        ],
        historyApiFallback:true
    },
    plugins:[
       new HtmlWebpackPlugin({
           template:"./index.html"
       })
    ]
}

webpack自动编译

webpack开启监听自动编译:

  • 命令行执行 npx webpack --watch
  • webpack.config.js中设置watch:true

但是这样只会监听到源码变化后,自动编译代码,,,浏览器不会自动刷新,,

webpack提供了一个 webpack-dev-server,,可以在监听到文件变化后,自动刷新浏览器


webpack编译react和vue
编译react
shell 复制代码
npm i babel-loader @babel/preset-env  @babel/preset-react
js 复制代码
import React, {Component} from "react";
import ReactDOM from "react-dom/client"



class App extends Component{
    constructor() {
        super();
        this.state = {
            message:"hello react"
        }
    }

    render() {
        return (
            <h3>{this.state.message}</h3>
        )
    }
}


export default App
js 复制代码
import App from "./App.jsx";

const  sum = (a,b)=>{
    return a+b;
}

console.log("123")
//
// import LogoImg from "../abc/logo.jpg"
import axios from "axios";

axios.post("/api/users/login").then(res=>{
    console.log(res,"res")
})

import ReactApp from "./App.jsx"

import React from "react";
import ReactDOM from "react-dom/client";

var root = ReactDOM.createRoot(document.querySelector("#app"));
root.render(<App/>)
js 复制代码
    module:{
        rules:[
            {
                test:/\.jsx?$/,
                exclude:/node_modules/,
                use:{
                    loader:"babel-loader",
                    options:{
                        presets: [
                            ["@babel/preset-env"],
                            ["@babel/preset-react"]]
                    }
                }
            }
        ]
    },
webpack编译vue3
shell 复制代码
npm i vue vue-loader vue-complete-compiler
xml 复制代码
<template>
  <div class="container">{{ message }}</div>
</template>

<script setup>

import {ref} from "vue";

const message = ref("hello vue")
</script>


<style>
.container{
  color: red;
}
</style>

主函数引入vue

js 复制代码
import Vue, {createApp} from "vue"
import VueApp from "./app.vue"


var app = createApp(VueApp);
app.mount("#root")

webpack中配置编译vue:

编译vue需要使用一个插件VueLoaderPlugin

js 复制代码
const HtmlWebpackPlugin = require("html-webpack-plugin")

// vue文件的加载,,还用到一个插件
// const VueLoaderPlugin = require("vue-loader/lib/plugin")
const {VueLoaderPlugin} = require("vue-loader")

const path = require("path");
module.exports={
    mode:"development",
    devtool: "source-map",
    entry: "./src/index.js",
    output:{
        path:path.resolve(__dirname,"./dist"),
        filename:"bundle.js",
        publicPath:"/"

    },
    module:{
        rules:[
            {
                test:/\.jsx?$/i,
                exclude:/node_modules/,
                use:{
                    loader:"babel-loader",
                    options:{
                        presets: [
                            ["@babel/preset-env"],
                            ["@babel/preset-react"]]
                    }
                }
            },
            {
                test:/\.css$/i,
                use:["style-loader","css-loader"]
            },
            {
                test: /\.vue$/i,
                use:["vue-loader"]
            }
        ]
    },
    devServer:{
        static:["public",{
            directory: path.resolve(__dirname,"./abc"),
            watch:true
        }],// 静态文件的位置

        host:"0.0.0.0",// ,局域网可以通过ip访问  ==》 localhost会被解析成127.0.0.1,回环地址:主机自己发出去的包,直接被自己接收
        port:9000,
        open:true,
        compress:true, // 是否为静态文件开启gzip
        proxy:[
            {
                context:["/api"],
                target:"http://localhost:8080/",
                pathRewrite:{
                    "^/api":""
                },
                changeOrigin:true

            }
        ],
        historyApiFallback:true
    },
    plugins:[
       new HtmlWebpackPlugin({
           template:"./index.html"
       }),
        new VueLoaderPlugin()
    ]
}

webpackDevMiddleware

webpack-dev-server默认开启的是 express的服务,,如果我不想使用express,,而想使用其他的,比如koa,可以使用webpack-dev-middleware去定制服务器,,,

通过webpack的配置信息,将源代码打包成 一个中间件,,让服务器引用进去

shell 复制代码
npm i express webpack-dev-middleware
js 复制代码
const express = require("express")
// 引入webpack,编译后面的文件
const webpack = require("webpack")
const webpackDevMiddleware = require("webpack-dev-middleware")

const app = express()

// 加载配置文件 ,,, webpack对这个信息进行编译
const config = require("../webpack.config")
const compiler = webpack(config)

// 将编译之后的对象,,通过这个webpackDevMiddleware这个中间件去处理  变成express可以使用的中间件
var middleware = webpackDevMiddleware(compiler);

// 使用这个中间件      =====>  webpack会根据配置,将源代码进行编译,编译完成之后放入express中间件中,,
app.use(middleware)

app.listen(3000,()=>{
    console.log("服务器已经开启在3000端口。。。。")
})
webpack的resolve属性

resolve常用的属性:

  • extensions : 扩展名解析,这里写了之后,源文件就不用写后缀名
  • mainFiles : 如果引入的是文件夹,,他会找这个文件夹下面指定名字的文件,,然后去拼接上extensions给出的后缀,进行解析
  • alias: 别名
js 复制代码
    resolve:{
        extensions:[".jsx",".js",".vue"],
        mainFiles:["index","main"],
        alias:{
            "@":path.resolve(__dirname,"./src")
        }
    },

gitee:https://gitee.com/water-kid/learn-webpack/tree/main/webpack04

相关推荐
noravinsc12 分钟前
国产化中间件 替换 nginx
运维·nginx·中间件
惜.己28 分钟前
Linux常用命令(十四)
linux·运维·服务器
linkingvision1 小时前
H5S 视频监控AWS S3 对象存储
linux·运维·aws·视频监控s3对象存储
doupoa2 小时前
Fabric 服务端插件开发简述与聊天事件监听转发
运维·python·fabric
BillKu2 小时前
服务器多JAR程序运行与管理指南
运维·服务器·jar
QQ2740287562 小时前
BlockMesh Ai项目 监控节点部署教程
运维·服务器·web3
小疆智控3 小时前
数字化工厂升级引擎:Modbus TCP转Profinet网关助力打造柔性生产系统
服务器·网络·tcp/ip
南棱笑笑生3 小时前
20250512给NanoPi NEO core开发板在Ubuntu core20.04系统更新boot.img
linux·运维·ubuntu
XMYX-03 小时前
Linux du 命令终极指南:从基础到精通
linux·服务器
小锋学长生活大爆炸3 小时前
【教程】Docker更换存储位置
运维·docker·容器