首页 > 解决方案 > `vue-cli-service build` 不生成模板的代码

问题描述

我试图了解为什么我在 Vue 项目的屏幕上看不到任何内容。我查看了一个 Vue CLI 生成的项目,并在以下代码中看到了这段代码main.js

new Vue({
  render: h => h(App),
}).$mount('#appmodified')

但我正在使用以下代码,基于示例 TODO 沙箱

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

当我运行时,这种实例化 Vue 的方式不会返回任何警告或错误npm run build

> @ build C:\wamp64\www\vuewtest
> vue-cli-service build


\  Building for production...

 DONE  Compiled successfully in 1858ms                                                                                        13:14:40

  File                                 Size               Gzipped

  dist\js\chunk-vendors.6018a262.js    65.29 KiB          23.49 KiB
  dist\js\index.377fe308.js            1.96 KiB           1.01 KiB

  Images and other types of assets omitted.

 DONE  Build complete. The dist directory is ready to be deployed.
 INFO  Check out deployment instructions at https://cli.vuejs.org/guide/deployment.html

尽管构建完成且没有错误,为什么我的代码在浏览器中没有显示任何内容?

main.js

import Vue from 'vue'
import App from './App'

Vue.config.productionTip = false

/* eslint-disable no-new */

//************ this works ************
new Vue({
    render: h => h(App),
}).$mount('#appmodified')

//************ this does not work *************
new Vue({
    el: '#appmodified',
    template: '<App/>',
    components: { App }
})

vue.config.js

module.exports = {
    "publicPath": "",
    pages: {
        index:{
            entry: "main.js",
            template: "index.html"
        }
    }
}

package.json

{
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build"
  },
  "dependencies": {
    "@vue/cli-service": "^3.9.2",
    "vue": "^2.6.10",
    "vue-template-compiler": "^2.6.10"
  }
}

标签: vue.jsvuejs2

解决方案


虽然您可能在构建时看不到错误/警告,但您仍应在浏览器控制台中收到运行时警告:

[Vue 警告]:您正在使用仅运行时构建的 Vue,其中模板编译器不可用。要么将模板预编译为渲染函数,要么使用包含编译器的构建。

默认情况下,Vue CLI 项目不包括运行时编译器,需要在运行时编译字符串模板或 in-DOM HTML(请参阅Runtime + Compiler vs. Runtime-only)。如果您更喜欢使用组件的属性,请使用以下标志template配置 Vue :runtimeCompiler

// vue.config.js
module.exports = {
  runtimeCompiler: true
}

推荐阅读