Vue 学习笔记(三十六):npm start

有些项目的启动方式是 npm run devnpm run serve,还有些是 npm start ,并且可以主动打开浏览器,是怎么实现的?

我们已知 npm run devnpm run serve 是在 package.json 中配置的,

1
2
3
4
5
"scripts": {
"dev": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
}

同样,npm start 也是这里配置的:

1
2
3
4
5
6
"scripts": {
"start": "npm run serve",
"serve": "vue-cli-service serve --open",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
}

后面加上 —-open 表示自动打开浏览器。这里 npm start 实际执行的是 npm run serve, 而 npm run serve 实际执行的是 vue-cli-service serve --open ,这里我们可以做个测试,配置package.json 如下:

1
2
3
4
5
6
7
"scripts": {
"start": "npm run serve",
"serve": "vue-cli-service serve --open --port 8090",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint",
"testtest": "echo hahaha"
}

执行 npm run testtest ,会得到:

1
2
3
4
5
6
$ npm run testtest

> simple-router-demo@0.1.0 testtest /Users/xxx/vueCliProjects/simple-router-demo
> echo hahaha

hahaha

它实际执行了 echo hahaha

另外,vue-cli-service serve --open 还可以加 —port 指定端口号。查看更多参数,./node_modules/.bin/vue-cli-service -h ,然后根据输出的提示命令进一步查看即可 ./node_modules/.bin/vue-cli-service help serve

1
2
3
4
5
6
7
8
9
10
11
12
13
Usage: vue-cli-service serve [options] [entry]

Options:

--open open browser on server start
--copy copy url to clipboard on server start
--stdin close when stdin ends
--mode specify env mode (default: development)
--host specify host (default: 0.0.0.0)
--port specify port (default: 8080)
--https use https (default: false)
--public specify the public network URL for the HMR client
--skip-plugins comma-separated list of plugin names to skip for this run

vue-cli-service 直接运行是找不到命令的,它并非全局安装,而是 ./node_modules/.bin/vue-cli-service ,npm scripts 中以 vue-cli-service 访问它,终端命令则需要带上述路径。

Q&A:

  1. start 可以是其它任意字符串吗?例如 package.json 中配置start一行改成 "sss": "npm run serve",然后执行 npm sss

    不行,会被提示:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    Usage: npm <command>

    where <command> is one of:
    access, adduser, audit, bin, bugs, c, cache, ci, cit,
    clean-install, clean-install-test, completion, config,
    create, ddp, dedupe, deprecate, dist-tag, docs, doctor,
    edit, explore, fund, get, help, help-search, hook, i, init,
    install, install-ci-test, install-test, it, link, list, ln,
    login, logout, ls, org, outdated, owner, pack, ping, prefix,
    profile, prune, publish, rb, rebuild, repo, restart, root,
    run, run-script, s, se, search, set, shrinkwrap, star,
    stars, start, stop, t, team, test, token, tst, un,
    uninstall, unpublish, unstar, up, update, v, version, view,
    whoami