[英]Why can't I preview Vue project locally?
From the Vue CLI https://cli.vuejs.org/guide/deployment.html , it stated that the dist
directory is meant to be served by an HTTP server.从 Vue CLI https://cli.vuejs.org/guide/deployment.html中,它指出dist
目录是由 Z293C9EA246FF9985DC6F62A6507F 服务器提供的。 But why can't I preview it from the index.html?但是为什么不能从 index.html 预览呢? Cause my understanding is that Vue is just a front end JavaScript framework, so one should be able to preview it from any browser.因为我的理解是 Vue 只是一个前端 JavaScript 框架,所以应该可以从任何浏览器预览它。 If am to create a simple vue project using a cdn, it can be directly previewed on the browser.如果是使用cdn创建一个简单的vue项目,可以直接在浏览器上预览。 But this is not the case for the vue project created through the CLI.但是通过 CLI 创建的 vue 项目并非如此。 Can someone explain this.有人可以解释一下吗。
Take a look into the Chrome Dev Tools.查看 Chrome 开发工具。 You will see a couple of errors similar to those:您将看到一些类似于以下的错误:
As you can see, there are a bunch of files that fail to be imported.如您所见,有一堆文件无法导入。 This is because these files are not imported using a relative file path, but an absolute one (starting from root, as visible by the prepended /
in all files in the index.html
).这是因为这些文件不是使用相对文件路径导入的,而是使用绝对路径导入的(从根目录开始,在index.html
中的所有文件中的前置/
可见)。
If you run a local server from the dist
directory root will resolve to this directory, allowing the files to be imported properly and your site to be visible in the browser.如果您从dist
目录运行本地服务器,根目录将解析到该目录,从而允许正确导入文件并且您的站点在浏览器中可见。
However if you simply open the index.html file in your browser, /
will resolve to the root of your operating system, which does not contain the files.但是,如果您只是在浏览器中打开 index.html 文件, /
将解析到您的操作系统的根目录,其中不包含这些文件。 If you were to copy all those files into the root of your OS, so that the paths would resolve successfully, you would not need a server to view your Vue application.如果您要将所有这些文件复制到操作系统的根目录中,以便成功解析路径,则不需要服务器来查看您的 Vue 应用程序。
CLI projects are built with the use on a server in mind. CLI 项目的构建考虑了在服务器上的使用。 The idea is to just be able to deploy the files in the dist
directory to a server and have a working Vue application.这个想法是能够将dist
目录中的文件部署到服务器并拥有一个工作的 Vue 应用程序。
Just to add to a great answer from @aside.只是为了添加@aside的一个很好的答案。
You can use a publicPath configuration option of Vue CLI and set it to ''
or ./
- this should be enough to make it work from file system您可以使用 Vue CLI 的publicPath配置选项并将其设置为''
或./
- 这应该足以使其在文件系统中工作
The value can also be set to an empty string (
''
) or a relative path (./
) so that all assets are linked using relative paths.该值也可以设置为空字符串 (''
) 或相对路径 (./
),以便使用相对路径链接所有资产。 This allows the built bundle to be deployed under any public path, or used in a file system based environment like a Cordova hybrid app.这允许将构建的捆绑包部署在任何公共路径下,或在基于文件系统的环境中使用,例如 Cordova 混合应用程序。
vue.config.js
module.exports = {
publicPath: ''
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.