如何在vue-cli项目中更改端口号

219

如何在Vue-cli项目中更改端口号,以便它在另一个端口而不是8080上运行。


在 macOS 上,请记住这个 https://dev59.com/i6Dia4cB1Zd3GeqPJtHu#46813423 - Pawel Ka
21个回答

8
  1. 打开 package.json
  2. 添加名为 serve 的脚本,"serve": "Vue-cli-service serve --port 8081"
  3. npm run serve 运行后,服务器将在 8081 端口上运行
{
  "name": "app-name",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve --port 8081", 
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  }
}

8
如果您使用 yarn
yarn serve --port 3000

7
使用vue-cli 3的另一种方法是在项目根目录(与package.json同级)中添加.env文件,其内容如下:PORT=3000。 运行npm run serve现在会显示应用正在端口3000上运行。

7

这里有很多答案,版本不同而有所不同,因此我想确认并进一步阐述Julien Le Coupanec在2018年10月提供的答案当使用Vue CLI时。截至本帖发布时,Vue.js的最新版本为vue@2.6.10,在查看了本帖中众多答案后,以下概述的步骤对我来说是最有意义的。 Vue.js文档涉及了这个谜题的一些部分,但不够明确。

  1. Open the package.json file in the root directory of the Vue.js project.
  2. Search for "port" in the package.json file.
  3. Upon finding the following reference to "port", edit the serve script element to reflect the desired port, using the same syntax as shown below:

    "scripts": {
      "serve": "vue-cli-service serve --port 8000",
      "build": "vue-cli-service build",
      "lint": "vue-cli-service lint"
    }
    
  4. Make sure to re-start the npm server to avoid unnecessary insanity.

文档显示,可以通过在npm run serve命令的末尾添加--port 8080来有效地获得相同的结果,例如:npm run serve --port 8080。我更喜欢直接编辑package.json以避免额外输入,但对一些人来说,在内联编辑npm run serve --port 1234可能会很方便。

5

要更改端口(NPM),请转到package.json。在scripts中编写您自己的脚本,例如:

"start": "npm run serve --port [PORT YOU WANT]"

接下来您可以通过输入npm start来启动应用程序。

"scripts":{"start":"npm run serve --- --port 3000"}


1
请提供详细的解释以便下一个用户更好地理解您的答案。此外,为了防止链接在未来无法使用,请提供链接内容的基本覆盖范围。 - Elydasian

3
如果您想暂时更改端口号,可以在npm run serve命令中添加一个--port选项。
npm run serve -- --port 6058

3
package.jsonserve脚本中,添加PORT环境变量:
"serve": "PORT=4767 vue-cli-service serve",

2

你应该能够理解这段代码:

"serve": "vue-cli-service serve --port 8081",


1
在我的Vue项目中,我需要在Visual Studio Code中的/config/index.js中进行设置。请在此处更改:
module.exports = {
    dev: {
          // Paths
          assetsSubDirectory: 'static',
          assetsPublicPath: '/',
          proxyTable: {},

          host: 'localhost', // can be overwritten by process.env.HOST
          port: 8090, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
          autoOpenBrowser: false,
          errorOverlay: true,
          notifyOnErrors: true,
          poll: false    
         }
}

我差不多也是这么做的。我的文件名是'vue.config.js',位于vue项目的根目录下。所需端口可以在路径module.exports.dev.port中找到。这里设置为8090。其他键值对对我来说并不必要。这是用于开发模式下使用“npm run serve”启动! - Dirk Schumacher

0

如果您正在通过Visual Studio Community或Professional运行此程序(可能带有.Net Core项目),则会发现无论您采取什么步骤,启动解决方案时它都会使用8080端口。

好吧,在.vscode目录中有一个需要编辑的launch.json文件。 MS根本不告诉您这一点,而且文件搜索似乎也找不到它。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接