这篇博文介绍了如何在使用vuecli工具创建的Vue项目中改变默认端口。
Vue应用程序是通过vue-cli工具使用vue create命令创建的。在默认情况下,应用程序是以默认的package.json脚本创建的,如下所示
"scripts": {
"serve": "vue-cli-service serve",
"start": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
}
当你运行npm run serve 或npm run start ,它启动网络服务器,监听8080端口。
B:\vue-app>npm run start
DONE Compiled successfully in 9556ms
App running at:
- Local: http://localhost:8081/
- Network: http://192.168.29.53:8081/
Note that the development build is not optimized.
To create a production build, run npm run build.
这篇文章涵盖了改变vuejs项目中默认端口的多种方法。
第一种方法,是在终端窗口改变端口选项
在终端中,向npm命令传递-- -- port 7000 选项。
B:\vue-app>npm run start -- --port 7000
> vue-google-font@0.1.0 start B:\blog\jswork\vue-google-font
> vue-cli-service serve "--port" "7000"
DONE Compiled successfully in 1836ms
App running at:
- Local: http://localhost:7000/
- Network: http://192.168.29.53:7000/
Note that the development build is not optimized.
To create a production build, run npm run build.
当你每次使用命令行运行时,都需要传递这个选项。这种方法是暂时的。
第二,同样可以通过改变package.json中的脚本块来简化。
"scripts": {
"serve": "vue-cli-service serve",
"start": "vue-cli-service serve --port 7000",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
},
改变webpack devserver的端口
VueCli内部使用webpack开发服务器。
- 在你项目的根目录下创建一个vue.config.js
- 在vue.config.js文件中添加以下内容
module.exports = {
devServer: {
historyApiFallback: true,
port: 7000,
noInfo: true,
overlay: true
},
}
在devServer部分将属性端口改为所需的端口号。
总结
讨论了在vue应用程序中用-port选项和webpack devServer端口选项来配置默认端口变化的多种方法。