关于live-server:常用的五种方式搭建本地静态html页面服务器

6次阅读

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

形式一:live-server

live-server是一款 npm 工具,能够在我的项目目录启动一个 node 服务,而后间接在浏览器中预览,并且 主动全局监听实时更新

两种装置形式:

全局装置 npm i live-server -g
本地装置  npm i live-server --save-dev

间接应用 live-server

首先在我的项目下 npm 初始化:npm init -y;

而后能够抉择全局装置或者本地装置 live-server,而后在 package.json 的 scripts 属性中增加如下代码:

"scripts": {"server": "live-server ./ --port=8181 --host=localhost --proxy=/api:http://www.abc.com/api/"}

中包含了代理设置proxy

而后 npm run server 执行下就会主动关上以后工程,默认指向 index.html 页面。

应用 node

首先本地装置live-server,执行如下指令:

npm i live-server --save-dev

而后在该我的项目下新建一个build.js,代码如下:

var liveServer = require("live-server");
var params = {
    port: 8181,
    host: "localhost",
    open: true,
    file: "index.html", 
    wait: 1000,
    logLevel: 2,  
    proxy: [['/api','http://www.abc.com/api/']]
};
liveServer.start(params);

最初在 package.jsonscripts下增加如下代码:

"scripts": {"dev": "node build.js"}

最初执行 npm run dev 就启动了本地动态页面,门路即是:http://localhost:8081/

具体参考地址:https://www.npmjs.com/package/live-server

形式二:http-server

全局装置http-server

npm i -g http-server

用法:

http-server [path] [options]

其中的 path 默认指向工程门路下的./public,如果不存在那么应用./

options就是常见的配置,比方端口、代理地址等,罕用配置:

  • -p or --port Port to use (defaults to 8080). It will also read from process.env.PORT.(设置端口)
  • -a Address to use (defaults to 0.0.0.0)(设置拜访地址)
  • -P or --proxy Proxies all requests which can’t be resolved locally to the given url. e.g.: -P http://someurl.com(设置代理地址)
  • -o [path] Open browser window after starting the server. Optionally provide a URL path to open. e.g.: -o /other/dir/(默认关上浏览器)

cmd进入动态目录工程,可执行如下操作:

http-server ./ -o --port 8085 --proxy http://192.168.11.120:8888/

当然该条命令也能够缩写成如下:

hs ./ -o -p 8085 -P http://192.168.11.120:8888/

咱们也能够初始化 package.json,执行npm init -y,而后在package.json 中的 scripts 字段中增加如下代码:

"scripts": {"dev": "http-server  ./ -o --port 8089 --proxy http://192.168.11.120:8888/"}

最初执行 npm run dev 也是一样的,应用http-server 次要毛病是 不能使浏览器主动刷新

 官网 github 地址:https://github.com/http-party/http-server

形式三:express 搭建

应用 express 简略搭建

应用 express 搭建前端动态页面环境,在工程下新建 build 文件夹,建一个 dev.js(开发环境启动文件) 以及index.js(配置文件、如端口)。

咱们只须要装置 express 以及 http-proxy-middleware 即可,如下:

npm i express http-proxy-middleware -D

index.js 代码:

module.exports = {
    port: 8081,
    host: 'localhost',
 proxyTable: [{
        api: '/api',
        target: 'http://192.168.1.112:8081/' }]
}

dev.js 代码如下:

const express = require('express');
const {createProxyMiddleware} = require('http-proxy-middleware');
const {port = 8080,proxyTable = []} = require('./index.js');

const app = express();
app.use('/', express.static('./')); // 设置动态资源拜访门路
proxyTable.forEach((item) => app.use(createProxyMiddleware(item.api, {
    target: item.target, // 指标服务器 host
    changeOrigin: true, // // 默认 false,是否须要扭转原始主机头为指标 URL
    ws: true // 是否代理 websockets
})))

app.listen(port,() => {console.log(`listen:${port}`);
})

在 package.json 中配置启动快捷键,如下:

"scripts": {"dev": "node config/dev.js"}

运行 npm run dev 即可启动本地服务器,本地运行localhost:8081 即可(默认运行工程下的动态文件 index.html),如果须要办法其余动态页面增加相应门路即可。

其中 http-proxy-middleware 理论就是将 http-proxy 封装,应用起来更加不便简略, 老版本 http-proxy-middleware 参考:http-proxy-middleware 应用办法和实现原理(源码解读), 其中新版本的 http-proxy-middleware 应用形式参考 github

应用 browser-sync 实现热更新优化

代码如下:

const express = require('express');
const path = require('path');
const timeout = require('connect-timeout');
const {createProxyMiddleware} = require('http-proxy-middleware');
const {port = 8080, proxyTable = [], host = 'localhost' } = require('./index.js');

const app = express();
const pathname = path.resolve(__dirname, '../');
const bs = require('browser-sync').create('server');

app.use(timeout(60 * 1e3));
app.use((req, res, next) => {if (!req.timedout) next();});
app.use('/', express.static(`${pathname}`)); // 设置动态资源拜访门路
proxyTable.forEach((item) => app.use(createProxyMiddleware(item.api, {
    target: item.target, // 指标服务器 host
    changeOrigin: true, // // 默认 false,是否须要扭转原始主机头为指标 URL
    ws: true // 是否代理 websockets
})))

app.listen(port, () => {
    bs.init({ // 开始一个 Browsersync 代理
        proxy: `http://${host}:${port}`,
        notify: true, // 告诉
        port: 8085, 
        // files: ['**'] // files 必须带上,不带上批改文件不会刷新;能够指定文件类型、文件等形式
        files: [`${pathname}/resources/**/*.html`,`${pathname}/index.html`,`${pathname}/public/**/*.js`,`${pathname}/public/**/*.css`]
    }) 
})

当然也能够用 watch 办法监听文件的变动,更改代码如下:

const express = require('express');
const path = require('path');
const timeout = require('connect-timeout');
const {createProxyMiddleware} = require('http-proxy-middleware');
const {port = 8080, hotUpdate = false, proxyTable = [], host = 'localhost' } = require('./index.js');

const app = express();
const pathname = path.resolve(__dirname, '../');
const bs = require('browser-sync').create('server');

app.use(timeout(60 * 1e3));
app.use((req, res, next) => {if (!req.timedout) next();});
app.use('/', express.static(`${pathname}`)); // 设置动态资源拜访门路
proxyTable.forEach((item) => app.use(createProxyMiddleware(item.api, {
    target: item.target, // 指标服务器 host
    changeOrigin: true, // // 默认 false,是否须要扭转原始主机头为指标 URL
    ws: true // 是否代理 websockets
})))

bs.watch(`${pathname}/resources/**/*.html`).on("change", bs.reload);
bs.watch(`${pathname}/index.html`).on("change", bs.reload);
bs.watch(`${pathname}/public/**/*.js`, function(event, file) {if (event === 'change') {bs.reload('*.js')
    }
})
bs.watch(`${pathname}/public/**/*.css`, function(event, file) {if (event === 'change') {bs.reload('*.css')
    }
})

app.listen(port, () => {
    bs.init({ // 开始一个 Browsersync 代理
        proxy: `http://${host}:${port}`,
        notify: true, // 告诉
        port: 8085
    }) 
})

注:Browsersync 让浏览器实时、疾速响应文件变动并主动刷新,Browsersync 阐明文档

形式四:应用 node 内置模块 http 启动服务

const http = require('http');
const fs = require('fs');
const path = require('path');
const httpProxy = require('http-proxy');
const childProcess = require('child_process'); // 可主动关上浏览器
const filepath = path.resolve(__dirname,'./');
const proxy = httpProxy.createProxyServer(); // 创立代理服务器
const {proxyTable = []} = require('./config/index.js');

http.createServer(function(req,res){fs.readFile(filepath + req.url,function(err,data) {proxyTable.forEach((item) => {if(req.url.indexOf(item.api) !== -1) { // 匹配上接口代理
                proxy.web(req,res,{target: item.target});
                proxy.on('error',function(e) { // 代理失败解决
                    console.log(e);
                })
            } else {if(err) {res.writeHeader(404,{'content-type': 'text/html;charset="utf-8"'});
                    res.write('<h1>404 谬误 </h1><p> 你拜访的页面 / 内容不存在 </p>');
                    res.end();} else {res.write(data);
                    res.end();}
            }
        })
        
    })
}).listen(8080,() => {console.log('服务启动了');
});

childProcess.exec('start http://localhost:8080/index.html');

而后在地址栏输出 localhost:8080/index.html(其中我的 index.html 就放在根门路,依据具体门路填写)

换一种形式:

const http = require('http');
const fs = require('fs');
const path = require('path');
const httpProxy = require('http-proxy');
const childProcess = require('child_process'); // 可主动关上浏览器
const filepath = path.resolve(__dirname,'./');
const proxy = httpProxy.createProxyServer(); // 创立代理服务器
const {proxyTable = []} = require('./config/index.js');
const server = new http.Server();

server.on('request',function(req,res){fs.readFile(filepath + req.url,function(err,data) {proxyTable.forEach((item) => {if(req.url.indexOf(item.api) !== -1) { // 匹配上接口代理
                proxy.web(req,res,{target: item.target});
                proxy.on('error',function(e) { // 代理失败解决
                    console.log(e);
                })
            } else {if(err) {res.writeHeader(404,{'content-type': 'text/html;charset="utf-8"'});
                    res.write('<h1>404 谬误 </h1><p> 你拜访的页面 / 内容不存在 </p>');
                    res.end();} else {res.write(data);
                    res.end();}
            }
        })
        
    })
})

server.listen(8080,() => {console.log('服务启动了');
});

childProcess.exec('start http://localhost:8080/index.html');

形式五:Nginx 配置

conf 配置代码如下:

#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 {

    upstream static_balance {
        #ip_hash;
        server 127.0.0.1:8080; 
    }

    upstream dynamic_balance {
        #ip_hash;
        server 192.168.1.118:8088;

    }

    include mime.types;
    default_type application / octet - stream;

    #log_format main '$remote_addr - $remote_user [$time_local]"$request" '
    # '$status $body_bytes_sent"$http_referer" '
    # '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log logs / access.log main;

    sendfile on;
    #tcp_nopush on;

    #keepalive_timeout 0;
    keepalive_timeout 65;

    #gzip on;

    server {

        listen 80 default_server;
        #listen[::]: 80 default_server ipv6only = on;
        server_name localhost;
        index index.html index.htm index.php;
        error_page 404 / 404. html;
        error_page 500 502 503 504 / 50 x.html;

        proxy_set_header Host $host;
        proxy_set_header X - real - ip $remote_addr;
        proxy_set_header X - Forwarded - For $proxy_add_x_forwarded_for;
        client_max_body_size 1000 m;

        location~.*.(html | htm | js | css | png | jpg | jpeg | gif | bcmap) $ {proxy_pass http: //static_balance;}

        location~ ^ /__webpack_hmr$ {proxy_pass http: //static_balance;}

    location / {proxy_pass http: //dynamic_balance;}

}

}

重要的配置代码:


http {
    upstream static_balance {
        #ip_hash;
        server 127.0.0.1:8080;
    }

    upstream dynamic_balance {
        #ip_hash;
        server 192.168.1.118:8088;

    }

    server {location~.*.(html | htm | js | css | png | jpg | jpeg | gif | bcmap) $ {proxy_pass http: //static_balance;}

        location~ ^ /__webpack_hmr$ {proxy_pass http: //static_balance;}

        location / {proxy_pass http: //dynamic_balance;}

    }
}

参考

  • live-server 官网
  • http-server 官网
  • LiveNode.js 解决前端跨域问题
  • LiveNode-github
正文完
 0