xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

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, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2021-12-22 23:48  xgqfrms  阅读(43)  评论(12编辑  收藏  举报