vue项目打包及部署到本地服务器

大家都知道使用npm run build进行打包,打包后你直接打开dist/下的index.html,会发现文件可以打开,但是页面是空白的,所有的js,css,img等路径都有问题,是指向根目录的。 此时需要修改config/index.js里的assetsPublicPath的字段重新打包,初始项目是/,它是指向项目根目录的也是为什么会出现错误的原因,这时改为./

     ./ 当前目录
    ../ 父级目录

    / 根目录

    根目录:在计算机的文件系统中,根目录指逻辑驱动器的最上一级目录,它是相对子目录来说的;它如同一棵大树的“根”一般,所有的树杈以它为起点,故被命名为根目录。以微软公司开发的Windows操作系统为例:打开我的计算机(计算机),双击C盘就进入C盘的根目录。双击D盘就进入D盘的根目录

    build: {
        env: require('./prod.env'),
        index: path.resolve(__dirname, '../dist/index.html'),
        assetsRoot: path.resolve(__dirname, '../dist'),
        assetsSubDirectory: 'static',
        assetsPublicPath: './',
        productionSourceMap: true,
        // Gzip off by default as many popular static hosts such as
        // Surge or Netlify already gzip all static assets for you.
        // Before setting to `true`, make sure to:
        // npm install --save-dev compression-webpack-plugin
        productionGzip: false,
        productionGzipExtensions: ['js', 'css'],
        // Run the build command with an extra argument to
        // View the bundle analyzer report after build finishes:
        // `npm run build --report`
        // Set to `true` or `false` to always turn it on or off
        bundleAnalyzerReport: process.env.npm_config_report
      }

    再从dist根目录打开index文件就可以访问了。

    这样打开的是单页面应用,如果要查看项目运行效果,则需要启动本地服务器。以nginx代理本地服务器为例,需要在nginx配置文件中,设置代理到build后dist文件夹的路径下,也可以另起一个路径,将build后生成的代码拷贝到该文件夹下。

#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    upstream ac_server{
        server 127.0.0.1:8689;
    }
      

    server {
        listen       80;
        server_name  ac.com;
        
        location / {
            root   D:/workspace/acHTML/dist;
            index  index.html app.html admin.html;
        }
        
        location ~ ^/html|js|css|shtml|jpg/(.*) {
            root   D:/workspace/acHTML/dist;
            index  index.html index.htm;
        }

                location ~ ^/ac/(.*) {
            index                index.html;
            proxy_pass          http://ac_server;
            proxy_set_header     Host ac.com;
            proxy_set_header     X-Forwarded-For $remote_addr;
        }
    }

}

启动nginx,在浏览器中输入localhost即可访问到index.html页面,也可以输入localhost/app.html访问到app.html页面,然后就可以查看你的项目运行效果啦。


猜你喜欢

转载自blog.csdn.net/tiguer/article/details/80389090