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

相关推荐
zzzzzz31018 小时前
9K Star 炸裂开源!这个 C 语言写的代码知识图谱,把 Linux 内核索引压缩到了 3 分钟
linux·服务器·sql
XIAOHEZIcode18 小时前
Linux系统鼠标偏移常见原因以及修复方案
linux·运维·游戏
用户0328472220701 天前
如何搭建本地yum源(上)
运维
大树884 天前
金刚石散热越强,管路越先见顶
大数据·运维·服务器·人工智能·ai
摇滚侠4 天前
Linux CentOS7 rpm 安装 MySQL 5.7
linux·运维·mysql
霸道流氓气质4 天前
领域驱动设计(DDD)在 Spring Boot 微服务中的实践指南
运维·spring boot·微服务
小宇宙Zz4 天前
Maven依赖冲突
java·服务器·maven
Inhand陈工4 天前
基于台达PLC与映翰通IG502的智慧水产养殖精准投喂与远程运维解决方案
运维·人工智能·物联网·阿里云·信息与通信
酣大智4 天前
ARP代理--工作原理
运维·网络·arp·arp代理
shushangyun_4 天前
2026年快消品B2B系统推荐:支持终端门店订货、促销政策自动化的工具?
java·运维·网络·数据库·人工智能·spring·自动化