Vue + Webpack 构建的页面显示空白页

9

我在使用vue应用和webpack时遇到了一些问题。当我运行npm run dev时一切都很顺利。但是当我进入生产模式,运行npm run build时,构建过程完成了。但是当我打开dist index.html或将带有index.html的捆绑包复制到共享托管public_html文件夹中时,它只显示空白。

以下是我的设置:

package.json

{
  "scripts": {
    "dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
    "start": "npm run dev",
    "build": "node build/build.js"
  },
  "dependencies": {
    "axios": "^0.17.1",
    "bootstrap": "^4.0.0",
    "jquery": "^3.3.1",
    "popper.js": "^1.12.9",
    "vue": "^2.5.2",
    "vue-router": "^3.0.1",
    "vuex": "^3.0.1"
  },
  "devDependencies": {
    "autoprefixer": "^7.1.2",
    "babel-core": "^6.22.1",
    "babel-helper-vue-jsx-merge-props": "^2.0.3",
    "babel-loader": "^7.1.1",
    "babel-plugin-syntax-jsx": "^6.18.0",
    "babel-plugin-transform-object-rest-spread": "^6.26.0",
    "babel-plugin-transform-regenerator": "^6.26.0",
    "babel-plugin-transform-runtime": "^6.22.0",
    "babel-plugin-transform-vue-jsx": "^3.5.0",
    "babel-preset-env": "^1.3.2",
    "babel-preset-stage-2": "^6.22.0",
    "chalk": "^2.0.1",
    "compression-webpack-plugin": "^1.1.6",
    "copy-webpack-plugin": "^4.0.1",
    "cross-env": "^5.1.3",
    "css-loader": "^0.28.0",
    "extract-text-webpack-plugin": "^3.0.0",
    "file-loader": "^1.1.4",
    "friendly-errors-webpack-plugin": "^1.6.1",
    "html-webpack-externals-plugin": "^3.6.0",
    "html-webpack-plugin": "^2.30.1",
    "node-notifier": "^5.1.2",
    "node-sass": "^4.7.2",
    "optimize-css-assets-webpack-plugin": "^3.2.0",
    "ora": "^1.2.0",
    "portfinder": "^1.0.13",
    "postcss-import": "^11.0.0",
    "postcss-loader": "^2.0.8",
    "postcss-url": "^7.2.1",
    "precss": "^3.1.0",
    "rimraf": "^2.6.0",
    "sass-loader": "^6.0.6",
    "semver": "^5.3.0",
    "shelljs": "^0.7.6",
    "style-loader": "^0.20.1",
    "uglifyjs-webpack-plugin": "^1.1.1",
    "url-loader": "^0.5.8",
    "vue-loader": "^13.3.0",
    "vue-style-loader": "^3.0.1",
    "vue-template-compiler": "^2.5.2",
    "webpack": "^3.6.0",
    "webpack-bundle-analyzer": "^2.9.0",
    "webpack-dev-server": "^2.9.1",
    "webpack-merge": "^4.1.0"
  },
  "engines": {
    "node": ">= 6.0.0",
    "npm": ">= 3.0.0"
  },
  "browserslist": [
    "> 1%",
    "last 2 versions",
    "not ie <= 8"
  ]
}

Webpack文件

配置文件:config/index.js

'use strict'
// Template version: 1.3.1
// see http://vuejs-templates.github.io/webpack for documentation.

const path = require('path')

module.exports = {
  dev: {

    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {},

    // Various Dev Server settings
    host: 'localhost', // can be overwritten by process.env.HOST
    port: 8080, // 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, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-


    /**
     * Source Maps
     */

    // https://webpack.js.org/configuration/devtool/#development
    devtool: 'cheap-module-eval-source-map',

    // If you have problems debugging vue-files in devtools,
    // set this to false - it *may* help
    // https://vue-loader.vuejs.org/en/options.html#cachebusting
    cacheBusting: true,

    cssSourceMap: true
  },

  build: {
    // Template for index.html
    index: path.resolve(__dirname, '../dist/index.html'),

    // Paths
    assetsRoot: path.resolve(__dirname, '../dist'),
    assetsSubDirectory: 'static',
    assetsPublicPath: './',

    /**
     * Source Maps
     */

    productionSourceMap: false,
    // https://webpack.js.org/configuration/devtool/#production
    devtool: '#source-map',

    // Gzip off by default as many popular static hosts such as
    // Surge or Netlify already gzip all static assets for you.
    // Before setting to `true`, make sure to:
    // npm install --save-dev compression-webpack-plugin
    productionGzip: false,
    productionGzipExtensions: ['js', 'css'],

    // Run the build command with an extra argument to
    // View the bundle analyzer report after build finishes:
    // `npm run build --report`
    // Set to `true` or `false` to always turn it on or off
    bundleAnalyzerReport: process.env.npm_config_report
  }
}

webpack.base.conf.js

'use strict'
const path = require('path')
const utils = require('./utils')
const config = require('../config')
const vueLoaderConfig = require('./vue-loader.conf')

function resolve (dir) {
  return path.join(__dirname, '..', dir)
}

module.exports = {
  context: path.resolve(__dirname, '../'),
  entry: {
    app: './src/main.js'
  },
  output: {
    path: config.build.assetsRoot,
    filename: '[name].js',
    publicPath: process.env.NODE_ENV === 'production'
      ? config.build.assetsPublicPath
      : config.dev.assetsPublicPath
  },
  resolve: {
    extensions: ['.js', '.vue', '.json'],
    alias: {
      'vue$': 'vue/dist/vue.esm.js',
      '@': resolve('src'),
    }
  },
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: vueLoaderConfig
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')]
      },
      {
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('img/[name].[hash:7].[ext]')
        }
      },
      {
        test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('media/[name].[hash:7].[ext]')
        }
      },
      {
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
        }
      },
      {
        test: /\.(scss)$/,
        use: [{
          loader: 'style-loader', // inject CSS to page
        }, {
          loader: 'css-loader', // translates CSS into CommonJS modules
        }, {
          loader: 'postcss-loader', // Run post css actions
          options: {
            plugins: function () { // post css plugins, can be exported to postcss.config.js
              return [
                require('precss'),
                require('autoprefixer')
              ];
            }
          }
        }, {
          loader: 'sass-loader' // compiles SASS to CSS
        }]
      }
    ]
  },
  node: {
    // prevent webpack from injecting useless setImmediate polyfill because Vue
    // source contains it (although only uses it if it's native).
    setImmediate: false,
    // prevent webpack from injecting mocks to Node native modules
    // that does not make sense for the client
    dgram: 'empty',
    fs: 'empty',
    net: 'empty',
    tls: 'empty',
    child_process: 'empty'
  }
}

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0, shrink-to-fit=no">
    <title>Vue Application</title>
  </head>
  <body>
    <div id="app"></div>
    <!-- built files will be auto injected -->
  </body>
</html>

main.js

import Vue from 'vue'
import App from './App.vue'
import store from './vuex/store'
import router from './router/router'
import helper from './helper'
import './assets/styles/main.scss'

new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>'
})

App.vue

<template>
  <div id="app">
    <div id="wrapper">
  <!-- the router outlet, where all matched components would be viewed -->
  <!-- A named view, 'header' -->
    <router-view name="header"></router-view>
    <div class="clearfix"></div>
    <!-- A named view, 'dashboard' -->
      <router-view name="dashboard"></router-view>
    <!-- A named view, 'content' -->
    <router-view name="content"></router-view>
    <!-- A named view, 'footer' -->
    <router-view name="footer"></router-view>
    </div>
  </div>
</template>

<script>
export default {
  name: 'App',
}
</script>

我的主要怀疑对象是 webpack 上我的 asset 配置出了问题,所以这里是我的文件夹结构,以防有所帮助。

src
  assets
    styles
      main.scss
  App.vue
  main.js

如果我无法展示更多的代码,先说声抱歉,谢谢。

5个回答

10

我假设您的生产环境是在根项目文件夹的子目录下运行的,例如:http://example.com/folder

如果您的项目位于 folder 子目录中,则需要在 config/index.js 中为 build 属性配置 assetsPublicPath

示例:

build: {
  assetsPublicPath: '/folder/'
}

此外,您的路由文件应该将base属性设置为:

export default new VueRouter({
  base: '/folder/'
})

查看更多内容请在此处查看。


根据您提供的更多数据,可能是主机上的配置加载了错误的页面。

对于Apache,您的Aliasvhost应指向dist目录。例如(我的用例)

Alias /foo /var/www/htdocs/foo/dist

1
嗨,感谢您的快速回复。我已经尝试过了,但仍然没有运气。如果我查看页面源代码并检查HTML元素,我可以清楚地看到脚本已经加载到bundled.js中,但是当我查看div#app时,在routerview部分,子元素为空白。有什么想法吗? - kola
你正在运行Linux Web服务器吗?你必须配置你的目录指向“dist”文件夹。例如,你的别名或虚拟主机应该指向“/var/www/html/your-project/dist”。 - Ru Chern Chong
在路由器上配置基本属性对我很有帮助。谢谢! - hbobenicio

4
在我的情况下,我只需要在router.js中添加一个重定向。
{ path: "/index.html", redirect: "/" }

1
我遇到了相同的问题。我找到了一个解决方案(我认为是在SO上找到的,但我不记得并且再也找不到了)。解决方案是在vue.config.js中明确声明publicPath变量:
module.exports = {
publicPath: "",
chainWebpack: config => {
    config.plugin("html").tap(args => {
        args[0].title = "My Vue App";
        return args;
    });
}

};

它起作用了,但我想知道为什么它起作用,所以我进行了一些探究,在vue-cli文档中,我了解到publicPath变量决定了BASE_URL环境变量。它默认为“/”,因此如果您在根目录中运行Vue应用程序,则不需要它。但是,如果像我在项目中一样从子目录运行它,例如domain.com/appdir/index.html,它将显示一个空白页面,因为它试图从“/”路径(例如:domain.com/)拉取东西。


0
在我的情况下,我使用<template>,我必须在我的vue.config.js中启用runtimeCompiler

runtimeCompiler


0

这对我起作用:在 router/index.js 中添加

{
    path: '*',
    name: 'catchAll',
    component: Home
}

在路径的末尾


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