简体   繁体   中英

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. But why can't I preview it from the 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. If am to create a simple vue project using a cdn, it can be directly previewed on the browser. But this is not the case for the vue project created through the CLI. Can someone explain this.

Take a look into the Chrome Dev Tools. 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 ).

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.

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. 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.

CLI projects are built with the use on a server in mind. The idea is to just be able to deploy the files in the dist directory to a server and have a working Vue application.

Just to add to a great answer from @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

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.

vue.config.js

module.exports = {
    publicPath: ''
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM