webpack前端开发环境配置整理

前后端分离已经不是什么新鲜事件了,虽说仓库已经分开开发了,但是数据接口还是避免不了的,如何方面快速成功的调用到后台的服务也需要前端不断的get新技能,今天就分享一下前端本地开发环境的配置。
可能涉及的知识点:
1、后台:跨域、鉴权
2、nginx 配置
3、webpack 配置

就拿 vue 项目 vue init webpack 创建的项目,以前的文章介绍过vue create 和 vue init 区别,有兴趣的小伙伴可以翻翻下。

这个是项目整体目录
从简单到复杂一步一步循序渐进,如果你的项目里面只是通过接口查询数据,都是通过携带参数取数据,这类情况可以只通过配置webpack的 proxyTable 就可以解决,

//config/index.js
dev: {

    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {}, // 修改这里

    // Various Dev Server settings
    host: 'localhost', // can be overwritten by process.env.HOST
    port: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
    autoOpenBrowser: false,
    errorOverlay: true,
    notifyOnErrors: true,
    poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-

    // Use Eslint Loader?
    // If true, your code will be linted during bundling and
    // linting errors and warnings will be shown in the console.
    useEslint: true,
    // If true, eslint errors and warnings will also be shown in the error overlay
    // in the browser.
    showEslintErrorsInOverlay: false,

    /**
     * Source Maps
     */

    // https://webpack.js.org/configuration/devtool/#development
    devtool: 'cheap-module-eval-source-map',

    // If you have problems debugging vue-files in devtools,
    // set this to false - it *may* help
    // https://vue-loader.vuejs.org/en/options.html#cachebusting
    cacheBusting: true,

    cssSourceMap: true
  },

proxyTable

proxyTable:{
    '/api': {
        target: 'http://192.168.33.33:9999',
        secure: false,
        changeOrigin: true,
        pathRewrite: {
          '/rest': '' // 重写公共路径
        }
      },
}

启动项目 http://localhost:8080
请求接口 http://localhost:8080/api 实际代理到 http://192.168.33.33:9999/rest
到这里 简单的请求就配置完了。

第二步,如果一些操作需要用户登录的情况,可能就会牵扯到域名,这块需要小伙伴配置下 nginx;
mac 环境安装 nginx
brew 命令可以百度下自行可以安装很简单

 brew install nginx

安装完成之后默认

cd /usr/local/etc/nginx
open nginx.conf  找到 include servers/*; 行 如果有注释请把注释去掉。

cd /servers

在 servers 目录可以创建自己的站点了,创建 8080.conf 然后把下面的代码贴进去,

server {
        listen       80;
        server_name  local.domian.com.cn;
        location / {
            proxy_pass  http://127.0.0.1:8080;
        }
    }
sudo nginx -t 
sudo nginx -s reload 

然后在hosts里面增加 刚才配置的域名指向 127.0.0.1 就可以访问这个地址代理到你的8080端口了。

这里就简单介绍这么多,具体nginx 配置项有很多,如有需要自行下去学习。
这里配置域名的时候注意你的业务项目的cookie 是重在几级域名下的,

看上图 domain这一栏,如果是一级域名可以就配成 local.google.com.hk 这样携带的头信息里面就直接传到后台了。

这样你在www.google.com.hk 登录之后, 再回来访问你的local.google.com.hk 看看是不是有了cookie 。

================================================

扩展下思维,如果你们
线上的域名 www .online.com
测试环境的 www .test.com
如果你要调用 www .online.com 的域名 的接口
你需要配置下 nginx 域名增加 local .online.com
webpack里面代理改成线上的接口地址是不是就可以本地调用线上数据了。

有问题的小伙伴可以给我留言评论

文章来源: webpack前端开发环境配置整理