Node.js project auto open localhost with ip address All In One


Node.js project auto open localhost with ip address All In One

// webpack
const url = `http://${devServerHost}:${devServerPort}`;

// shell
open(url);

solutions

  1. npm scripts

npm scripts & auto open default browser & run multi commands

macOS

{
  "auto": "npm run dev & open http://localhost:8000",
}

Windows

// bad
{
  "start": "npm run dev & start http://localhost:8000",
}
// good 
{
  "start": "start http://localhost:8000 & npm run dev",
}

// bad
{
  "start": "npm run dev & npm run open",
  "open": "start http://localhost:8000",
}
  1. bash scripts

  2. npm libs


webpack.dev.conf.js 文件現在的配置信息情況:
const path = require("path");
const HtmlWebpackPlugin = require('html-webpack-plugin');
const open = require('opn');//打開瀏覽器
const chalk = require('chalk');// 改變命令行中輸出日志顏色插件
const ip = require('ip').address();

module.exports = {
    // 入口文件配置項
    entry: path.resolve(__dirname, 'src/index.js'),
    // 輸出文件配置項
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'js/bundle.js',
        publicPath: ""
    },
    // webpack4.x 環境配置項
    mode:"development",
    // 插件配置項
    plugins: [
        new HtmlWebpackPlugin({
            filename: 'index.html',//輸出文件的名稱
            template: path.resolve(__dirname, 'src/index.html'),//模板文件的路徑
            title:'webpack-主頁',//配置生成頁面的標題
        }),
    ],
    // 開發服務配置項
    devServer: {
        port: 8080,
        contentBase: path.resolve(__dirname, 'dist'),
        historyApiFallback: true,
        host: ip,
        overlay:true,
        after(){
            open(`http://${ip}:${this.port}`)
            .then(() => {
                console.log(chalk.cyan(`http://${ip}:${this.port} 已成功打開`));
            })
            .catch(err => {
                console.log(chalk.red(err));
            });
        }
    }
}

refs

https://github.com/xgqfrms-GitHub/Node-CLI-Tools/issues/17

https://github.com/xgqfrms-GitHub/Node-CLI-Tools/issues/23

https://github.com/kaivin/webpack4.x/blob/master/README/05:獲取ip並打開瀏覽器.md



©xgqfrms 2012-2020

www.cnblogs.com/xgqfrms 發布文章使用:只允許注冊用戶才可以訪問!

原創文章,版權所有©️xgqfrms, 禁止轉載 🈲️,侵權必究⚠️!



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM