macOS Cataline
macOS Cataline

最近几年一直在使用macbook进行开发,现在这台电脑已经是换过的第三台了,每次拿到一台崭新的mac当然是兴奋的,但同时也是枯燥的,因为你还要重新把你上一台已经习惯的工作开发环境迁移过来,想想也比较头疼,重复性的事情太多,还包括一些遗忘的,都要回顾一下,缺少一些统一的笔记记录。本文就根据之前更换笔记本的经历记录下自己的macOS开发环境的搭建记录。可以预估的是如果我继续在目前的公司工作两年,可能又要换新的macbook,估计又会面临开发环境迁移的问题。

macOS Catalina预装了Apache(2.4.41),svn(1.10.4),git(2.21.0),PHP(7.4.1),Ruby(2.6.3),Python(2.7.10),Python(3.7.5),Perl(5.18.4)等常见的工具和脚本语言,而这些工具和脚本语言正是很多开发者所需要的,从这一点上来看,macOS确实做到了天然与开发者友好的可能。

macOS Big Sur(版本11.4)预装了Apache,git,php,ruby,python,perl等常见的工具和脚本语言,而这些工具和脚本语言正式很多开发者需要的,从这一点上来看,macOS确实做到了天然与开发者友好的可能。

xcode-select –install

xcode-select --install

执行上面命令后,弹出下面窗口,选择安装。

xcode-select –install

修改HostName

scutil --set HostName sobird

# 查看hostname
hostname
sobird

Oh My Zsh

sh -c "$(curl -fsSL https://raw.github.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"

设置一些快捷命令

alias sobird="ssh sobird@sobird.me -p22"
alias proxy="ssh sobird@sobird.me -p22 -D127.0.0.1:8086"

# Meituan Jumper
alias jp="ssh -i ~/.ssh/id_rsa_jumper xxx@jumper.sankuai.com"

Terminal

配置终端主题

git clone git@github.com:altercation/solarized.git

cd solarized/osx-terminal.app-colors-solarized

双击打开Solarized Dark ansi.terminal,配色将会自动导入Terminal,打开Terminal的偏好设置,选择导入的描述文件。

Vim

Vim 的配色最好和终端的配色保持一致

cd solarized
cd vim-colors-solarized/colors
mkdir -p ~/.vim/colors
cp solarized.vim ~/.vim/colors/

vi ~/.vimrc
syntax on
set background=dark
colorscheme solarized

ls

vi .zshrc

export CLICOLOR=1
export LSCOLORS=ExGxFxdaCxDaDahbadeche

# 使其生效
source .zshrc

GIT

配置全局用户

git config --global user.name sobird
git config --global user.email xxx@sobird.me

pull.rebase

git config --global pull.rebase false

当pull.rebase为false时,运行不带选项的命令git pull不会被改变含义,即不会变基。如果想变基,需要在执行命令时显式地加上选项–rebase,即git pull --rebase

如果不设置,则会在执行git pull命令出现下面报错:

hint: Pulling without specifying how to reconcile divergent branches is
hint: discouraged. You can squelch this message by running one of the following
hint: commands sometime before your next pull:
hint: 
hint:   git config pull.rebase false  # merge (the default strategy)
hint:   git config pull.rebase true   # rebase
hint:   git config pull.ff only       # fast-forward only
hint: 
hint: You can replace "git config" with "git config --global" to set a default
hint: preference for all repositories. You can also pass --rebase, --no-rebase,
hint: or --ff-only on the command line to override the configured default per
hint: invocation.

不忽略文件名大小写

git config --global core.ignorecase false

配置git push 使用当前分支

git config --global push.default current

常用命令别名配置

git config --global alias.st status
git config --global alias.co checkout
git config --global alias.ci commit
git config --global alias.br branch

或者打开git的全局配置文件

git config --global -e

# 填入下面内容
[alias]
        st = status
        co = checkout
        ci = commit
        br = branch

Homebrew

Homebrew是macOS下的软件包管理工具,非常好用,是自己从使用mac开始就安装使用的一个工具,虽然使用频率不高,但对mac开发环境的管理维护起到了非常重要的作用,他的作用就像apt之于ubuntu,yum至于CentOS,maven之于java,npm之于node,pip之于Python,composer之于PHP。

所以还能说什么呢,装就完了!

# 终端执行下面代码
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

# 更多详细安装使用查看以前的文章:https://sobird.me/mac-install-brew.htm

VS Code

Launching from the command line

可以从终端键入 code 命令来启动VS Code,同时按下 Cmd+Shift+P 输入 Shell Command

code

选择 Shell Command: Install ‘code’ command in PATH 完成安装。

插件

  1. Chinese (Simplified) Language Pack for Visual Studio Code
  2. ESLint
  3. Prettier – Code formatter
  4. ES7 React/Redux/GraphQL/React-Native snippets
  5. GitLens — Git supercharged
  6. Vetur
  7. Material Icon Theme
  8. open in browser
  9. Markdown Preview Enhanced
  10. psioniq File Header

配置

psioniq File Header

{
  "psi-header.config": {
    "forceToTop": true,
    "blankLinesAfter": 1,
    "author": "sobird",
    "authorEmail": "i@sobird.me",
    "company": "Meituan, Inc."
  },
  "psi-header.lang-config": [
    {
      "language": "lua",
      "begin": "--[[",
      "prefix": "--",
      "end": "--]]",
      "blankLinesAfter": 0
    },
    {
      "language": "python",
      "begin": "###",
      "prefix": "# ",
      "end": "###",
      "blankLinesAfter": 0,
      "beforeHeader": ["#!/usr/bin/env python3", "# -*- coding:utf-8 -*-"]
    },
    {
      "language": "vue",
      "begin": "<!--",
      "prefix": " - ",
      "end": "-->",
      "blankLinesAfter": 1,
      "forceToTop": false
    },
    {
      "language": "javascript",
      "begin": "/**",
      "prefix": " * ",
      "end": " */",
      "blankLinesAfter": 1,
      "forceToTop": false
    },
    {
      "language": "typescript",
      "mapTo": "javascript"
    }
  ],
  "psi-header.templates": [
    {
      "language": "*",
      "template": [
        "<<filename>>",
        "",
        "<<author>><<<authorEmail>>> at <<filecreated('YYYY/MM/DD H:mm:ss')>> created."
        //"Copyright (c) <<year>> <<company>>",
      ],
      "changeLogCaption": "HISTORY:",
      "changeLogHeaderLineCount": 2,
      "changeLogEntryTemplate": ["<<dateformat('YYYY-MM-DD')>>\t<<initials>>\t"]
    },
    {
      "language": "javascript",
      "template": [
        "<<filename>>",
        "",
        "<<author>><<<authorEmail>>> at <<filecreated('YYYY/MM/DD H:mm:ss')>> created."
        //"Copyright (c) <<year>> <<company>>",
      ]
    },
    {
      "language": "typescript",
      "mapTo": "javascript"
    }
  ],
}

Apache

macOS内置了Apache服务,如果要使用,可以按照如下的配置配合PHP使用。考虑到未来macOS升级带来Apache的自动升级。本人转向使用Nginx服务。

通过下面命令设置开机(禁止)启动

sudo launchctl load -w /System/Library/LaunchDaemons/org.apache.httpd.plist
sudo launchctl unload -w /System/Library/LaunchDaemons/org.apache.httpd.plist

httpd.conf

php 配置
打开下面三个模块的注释
LoadModule alias_module libexec/apache2/mod_alias.so
LoadModule rewrite_module libexec/apache2/mod_rewrite.so
LoadModule php7_module libexec/apache2/libphp7.so

#ServerName www.example.com:80
打开上面行注释并修改为:
ServerName localhost:80

否则启动的时候会报下面的错误:
 httpd: Could not reliably determine the server's fully qualified domain name, using 127.0.0.1. Set the 'ServerName' directive globally to suppress this message

Nginx

# 安装
brew install nginx

# 启动n
brew services start nginx

nginx.conf

Nginx安装之后的默认配置如下:


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

    #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       8080;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}
    include servers/*;
}

macOS下的virtual host配置是放在了servers下面,如果需要在本地新增虚拟主机,只需在此目录下添加配置文件即可。

设置开机启动

开机启动文件位置:/usr/local/Cellar/nginx/1.19.x/homebrew.mxcl.nginx.plist。拷贝此文件到~/Library/LaunchAgents/。执行下面命令加入开机启动项:

launchctl load -w ~/Library/LaunchAgents/homebrew.mxcl.nginx.plist

更改默认root

nginx 的默认root 是 html,一般指向的本地磁盘地址:/var/www/,我需要更改到我的个人www目录

server{
    ...
    root /Users/sobird/www;
    ...
    location / {
        #root   html;
        index  index.html index.htm;
    }
    ...
}

# ... 表示省略掉的配置

另外,webapps目录配置在/opt/web/下。

PHP

PHP是世界上最好的语言

所以连macOS系统都已经帮你内置了PHP(macOS12版本不再内置PHP)语言环境:

在macOS Monterey 版本之后,系统不再内置PHP,所以需要我们手动安装

brew install php

==> Caveats
To enable PHP in Apache add the following to httpd.conf and restart Apache:
    LoadModule php_module /usr/local/opt/php/lib/httpd/modules/libphp.so

    <FilesMatch \.php$>
        SetHandler application/x-httpd-php
    </FilesMatch>

Finally, check DirectoryIndex includes index.php
    DirectoryIndex index.php index.html

The php.ini and php-fpm.ini file can be found in:
    /usr/local/etc/php/8.0/

To restart php after an upgrade:
  brew services restart php
Or, if you don't want/need a background service you can just run:
  /usr/local/opt/php/sbin/php-fpm --nodaemonize
==> Summary
🍺  /usr/local/Cellar/php/8.0.12: 500 files, 77.8MB
➜  ~ php -v
PHP 8.0.12 (cli) (built: Oct 21 2021 14:38:26) ( NTS )
Copyright (c) The PHP Group
Zend Engine v4.0.12, Copyright (c) Zend Technologies
    with Zend OPcache v8.0.12, Copyright (c), by Zend Technologies

➜  ~ php-fpm -v
PHP 8.0.12 (fpm-fcgi) (built: Oct 21 2021 14:38:38)
Copyright (c) The PHP Group
Zend Engine v4.0.12, Copyright (c) Zend Technologies
    with Zend OPcache v8.0.12, Copyright (c), by Zend Technologies

PHP是我非常喜欢的一门语言,这是我在大学四年级期间在学校图书馆里自学的一门语言,也算是当年比较流行的一门Web语言,可惜自己毕业工作后并没有去做PHP相关的开发,反而去做了前端开发,然后一抹黑的走到现在。

当然,这我自己快十年的工作过程中,PHP这门语言给了我很多帮助,比如:

  • 8天写了一个留言本系统
  • 设计了一个MVC框架
  • DiscuzX源码学习
  • 日常写爬虫去爬取网络数据
  • WordPress主题&插件开发
  • 等等…

因为PHP是有史以来最好的语言,没有之一。它快速,非常强大,而且免费。

Project Beehive Forum

正因如上所说,我以前开发的东西也都免费,没有赚到什么钱~~

php-fpm配置

在nginx下一般采用php-fpm的方式来解运行php文件,为此我们需要在nginx中配置php-fpm服务。nginx与php-fpm有两种通信方式:Unix socket 和 TCP监听127.0.0.1。

Unix socket

unix socket是一种终端,可以使同一台操作系统上的两个或多个进程进行数据通信。这种方式需要在nginx配置文件中填写php-fpm的pid文件位置,效率要比tcp socket高。

# 配置
location ~ \.php$ {
    root           html;
    fastcgi_index  index.php;
    include fastcgi-php.conf;
    fastcgi_pass unix:/run/php/php-fpm.sock;
}

TCP监听

TCP监听0.0.0.0:9000端口来进行通信,php-fpm的默认配置就是这种方式:listen = 127.0.0.1:9000

location ~ \.php$ {
    # 具体配置根据实际情况调整
    root           html;
    fastcgi_pass   127.0.0.1:9000;
    fastcgi_index  index.php;
    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
    include        fastcgi_params;
}

考虑到我的nginx和php-fpm在同一台机器上以及效率问题,将默认的TCP监听模式改为Unix Socket模式,涉及到如下文件:

# 打开php-fpm.conf文件
vi /usr/local/etc/php/7.4/php-fpm.conf

pid = run/php-fpm.pid
error_log = log/php-fpm.log
; daemonize = no

# 打开 www.conf文件
vi /usr/local/etc/php/7.4/php-fpm.d/www.conf
# 修改listen为如下内容
listen = /usr/local/var/run/php-fpm.sock

加入开机启动

# 执行下面命令即可自动加入开机启动
brew services start php

phpMyAdmin

phpMyAdmin是一款MySQL数据库管理软件,作为一名前端工程师,确实不太擅长使用终端命令行的方式来查询数据,所以这是我工作环境中必备的一款软件,毕竟免费开源,不用白不用。当然一个问题是,在一些大数据的导出导入操作,还是在命令行下操作来的方便且效率也高。一般可以通过homebrew安装:

brew install phpmyadmin

phpmyadmin报错:mysqli_real_connect(): (HY000/2002): No such file or directory

修改phpmyadmin配置文件
$cfg['Servers'][$i]['host'] = ‘localhost’;
改成
$cfg['Servers'][$i]['host'] = '127.0.0.1’;

或者 修改php.ini

默认下面的两个配置为空,指定mysql.sock的位置即可
pdo_mysql.default_socket= /tmp/mysql.sock
mysqli.default_socket =/tmp/mysql.sock
➜  ~ apachectl -v
Server version: Apache/2.4.41 (Unix)
Server built:   Nov  9 2019 07:53:54

除了在命令行下执行PHP外,Web开发中更多需要网页浏览PHP页面,这就需要Apache来解析PHP并提供Web服务。这也是我工作开发环境的必装软件,如果系统没有装这个软件,总感觉少点啥。

httpd-vhosts.conf

<VirtualHost *:80>
    ServerAdmin xxx@sobird.me
    DocumentRoot "/Users/sobird/www"
    <Directory /Users/sobird/www>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride None
        Order allow,deny
        allow from all
        Require all granted
    </Directory>
</VirtualHost>

phpmyadmin.conf

Alias /phpmyadmin /usr/local/share/phpmyadmin
<Directory /usr/local/share/phpmyadmin/>
    Options Indexes FollowSymLinks MultiViews
    AllowOverride All
    <IfModule mod_authz_core.c>
        Require all granted
    </IfModule>
    <IfModule !mod_authz_core.c>
        Order allow,deny
        Allow from all
    </IfModule>
</Directory>

MySQL

# 一行代码安装
brew install mysql

登录phpmyadmin时,报mysqli_real_connect(): The server requested authentication method unknown to the client [caching_sha2_password]错误

mysql8.0用户密码加密方式为caching_sha2_password,phpmyadmin暂不支持,需要修改下mysql的加密方式:

登录mysql:
mysql -u root -p 
查看当前加密方式:
use mysql; select user,plugin from user where user='root'; 
修改加密方式(注,后面的password为你新的mysql密码):
alter user 'root'@'localhost' identified with mysql_native_password by 'password'; 
生效:
flush privileges; 

最好还要配置下my.cnf,添加下面一行

[mysqld]
....
default_authentication_plugin=mysql_native_password

Java

Java开发环境需要JDK的支持,在安装之前可以通过下面命令来查看是否已安装了JDK。

java --version
java 11.0.5 2019-10-15 LTS
Java(TM) SE Runtime Environment 18.9 (build 11.0.5+10-LTS)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.5+10-LTS, mixed mode)

# 或者
/usr/libexec/java_home 
/Library/Java/JavaVirtualMachines/jdk-11.0.5.jdk/Contents/Home
# 显示下面内容表示未安装
Unable to find any JVMs matching version "(null)".
No Java runtime present, try --request to install.

否则弹出下面提示框,则表示没有安装JDK。

访问Java 11 LTS 下载jdk-11.0.5_osx-x64_bin.dmg到本地,双击即可完成JDK的安装。

NodeJS

brew install node

npm i typescript -g
npm i eslint -g
npm i nrm -g

nrm ls
nrm use taobao

SVN

在macOS 10.15.4 版本之前,SVN命令是集成在了xcode工具包里,可以通过下面命令进行安装:

sudo rm -rf $(xcode-select -print-path)
xcode-select --install

在macOS 10.15.4更新至 10.15.5后,输入如svn命令将会提示:

svn: error: The subversion command line tools are no longer provided by Xcode.

也就是在该版本之后,svn命令不再由xcode工具包提供,而是需要用户自行安装:

brew install svn
...
==> subversion
svntools have been installed to:
  /usr/local/opt/subversion/libexec

The perl bindings are located in various subdirectories of:
  /usr/local/opt/subversion/lib/perl5

You may need to link the Java bindings into the Java Extensions folder:
  sudo mkdir -p /Library/Java/Extensions
  sudo ln -s /usr/local/lib/libsvnjavahl-1.dylib /Library/Java/Extensions/libsvnjavahl-1.dylib