Vue + Webpack 构建显示空白页面

Vue + Webpack build show blank page

我在使用 vue 应用程序 + webpack 时遇到了一些问题。当我 运行 npm 运行 dev 一切顺利。当我进入生产模式时,npm 运行 构建,构建过程完成。但是当我打开 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 上的资产配置有问题,所以这里是我的文件夹结构以备不时之需。

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

抱歉,如果我无法显示任何进一步的代码,谢谢。

我假设您 运行 您的作品位于根项目文件夹的子目录中,例如http://example.com/folder.

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

示例:

build: {
  assetsPublicPath: '/folder/'
}

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

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

查看更多here.


从您那里收集到更多数据后,可能是您主机上的配置加载了错误的页面。

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

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

在我的例子中,我所要做的就是在 router.js
中添加一个重定向 { path: "/index.html", redirect: "/" }

在我使用 <template> 的场景中,我必须在 vue.config.js.

中启用 runtimeCompiler

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

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

在路径的尽头

我遇到了同样的问题。我找到了一个解决方案(我想它就在这里,但我不记得也找不到了)。解决方案是在 vue.config.js:

中显式声明 publicPath 变量
module.exports = {
publicPath: "",
chainWebpack: config => {
    config.plugin("html").tap(args => {
        args[0].title = "My Vue App";
        return args;
    });
}

};

它有效,但我想知道 为什么 它有效,所以我进行了一些挖掘,在 vue-cli documentation 中,我了解到 publicPath 变量指示 BASE_URL 环境变量。它默认为“/”,因此如果您 运行 您的 Vue 应用程序位于根目录中,则没有必要。但是,如果像我在我的项目中所做的那样,您 运行 它来自 domain.com/appdir/index.html 之类的子目录,它将显示一个空白页面,因为它正在尝试从中提取内容“/”路径(例如:domain.com/)