天天看點

web前端常用的五種方式搭建本地靜态html頁面伺服器

方式一: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.json的scripts下添加如下代碼:

"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主要的配置代碼:

http {
    # nginx負載均衡配置
    upstream dynamic_balance {
        #ip_hash;
        server 192.168.100.123: 8081;
    }
    # 省略其他
    server {
        listen 80;
        server_name localhost;
        #通路工程路徑
        root website;
        index index.html index.htm;
        
        #轉發把原http請求的Header中的Host字段也放到轉發的請求
        proxy_set_header Host $host;
        #擷取使用者真實IP
        proxy_set_header X - real - ip $remote_addr;
        proxy_set_header X - Forwarded - For $proxy_add_x_forwarded_for;
        
        #接口轉發
        location /base/ {
            proxy_pass http: //dynamic_balance; 
        }
        
        #啟用history模式( 什麼請求都隻傳回index.html)
        location / {
            try_files $uri $uri / /index.html;
        }
    }
}      

參考

  • live-server官網
  • http-server官網
  • LiveNode.js 解決前端跨域問題
  • LiveNode-github