vue3项目vue.config.js配置“代理”、“端口”、“打包名”、“图片压缩”

4,727次阅读
没有评论

共计 1799 个字符,预计需要花费 5 分钟才能阅读完成。

前言

我们在搭建 vue3 项目的时候不可避免的会遇到“代理”、“端口”、“打包名”、“图片压缩”等配置问题,本文逐一讲述该怎么样在 vue.config.js 中去配置。


一、配置代理端口和代理转发

const {defineConfig} = require('@vue/cli-service')

module.exports = defineConfig({
    devServer: {
        host: 'localhost',
        port: 3000,  // 启动端口号
        proxy: {
            '/api': { // 请求接口中要替换的标识
                target: 'http://117.62.22.235:17009', // 代理地址
                ChangeOrigin: true, // 是否允许跨域
                secure: true,
                pathRewrite: {'^/api': ''// 这里理解成用‘/api’代替 target 里面的地址,后面组件中我们掉接口时直接用 api 代替 比如我要调用'http://40.00.100.100:3002/user/add',直接写‘/api/user/add’即可}
            }
        }
    }
})


二、修改打包名

const {defineConfig} = require('@vue/cli-service')

module.exports = defineConfig({
    publicPath: './', // 打包位置
    outputDir: 'distBigScreenForBase' // 包名
})

三、图片压缩

图片压缩先要引入 image-webpack-loader 插件

命令:npm install image-webpack-loader –save-dev

const {defineConfig} = require('@vue/cli-service')

module.exports = defineConfig({
    // 图片压缩
    chainWebpack: config => {const imagesRule = config.module.rule('images')
        imagesRule
            .use('image-webpack-loader')
            .loader('image-webpack-loader')
            .options({bypassOnDebug: true})
            .end()}
})

四、完整代码

const {defineConfig} = require('@vue/cli-service')

module.exports = defineConfig({
    publicPath: './', // 打包位置
    outputDir: 'distBigScreenForBase', // 包名
    devServer: {
        host: 'localhost',
        port: 3000,  // 启动的端口号
        proxy: {
            '/api': { // 请求接口中要替换的标识
                target: 'http://117.62.22.235:17009', // 代理地址
                ChangeOrigin: true, // 是否允许跨域
                secure: true,
                pathRewrite: {'^/api': ''// 这里理解成用‘/api’代替 target 里面的地址,后面组件中我们掉接口时直接用 api 代替 比如我要调用'http://40.00.100.100:3002/user/add',直接写‘/api/user/add’即可}
            }
        }
    },
    // 图片压缩
    chainWebpack: config => {const imagesRule = config.module.rule('images')
        imagesRule
            .use('image-webpack-loader')
            .loader('image-webpack-loader')
            .options({bypassOnDebug: true})
            .end()},
})

总结

vue3 的配置和 vue2 有所不同,不能照搬照套 vue2,那样会报错。这里没有用 vite,用的是 vue cli, 所以在 vue.config.js 中配置。如果是 vite 项目则在 vite.config.js,具体可参考 https://mp.csdn.net/mp_blog/creation/editor/131852773 代码可以直接 copy,亲测有效,只需要修改成自己想要的文件名、路径即可。

原文地址: vue3 项目 vue.config.js 配置“代理”、“端口”、“打包名”、“图片压缩”

    正文完
     0
    Yojack
    版权声明:本篇文章由 Yojack 于2024-10-02发表,共计1799字。
    转载说明:
    1 本网站名称:优杰开发笔记
    2 本站永久网址:https://yojack.cn
    3 本网站的文章部分内容可能来源于网络,仅供大家学习与参考,如有侵权,请联系站长进行删除处理。
    4 本站一切资源不代表本站立场,并不代表本站赞同其观点和对其真实性负责。
    5 本站所有内容均可转载及分享, 但请注明出处
    6 我们始终尊重原创作者的版权,所有文章在发布时,均尽可能注明出处与作者。
    7 站长邮箱:laylwenl@gmail.com
    评论(没有评论)