Vue 不使用 Webpack 渲染模板,而是考虑仅运行时构建



首先,让我说明我的目标是将 Vue 集成到我现有的代码库中。我还发现 Webpack 非常有用,并根据我的需求对其进行了设置。并不是说我对 webpack 非常称职,但得到了基本的想法并以某种方式做到了。

为了在现有项目中使用 Vue,我选择将其与纯 Javascript 集成,由于复杂性、项目要求和时间,我不编译.vue文件。因此,在我的代码库中,我想初始化一个针对 DOM 元素的Vue实例,并在我的 HTML 中对模板进行硬编码。让我在代码中演示它以使其更清晰。以下是我的HTML的一部分:

<div id="entry-component">
<p>Hello {{ message }}!</p>
</div>
<!-- I use Django and `verbatim` here to escape Django templating inside. -->
<!-- Also, consider `component` here as a part of HTML page, not in sense of Vue.
A page can have multiple `whatever-component` and initialize multiple `Vue` instances. -->

还有我的Javascript文件:

// app.js
// entry point for webpack
// some imports here...
import 'vue'
// I do this because I hardcoded my template (`message` variable) inside
// my HTML and only want runtime Vue.
import './components/entry.js'
// this contains my `Vue` instance
////////////////////////
// ./components/entry.js
import Vue from 'vue'
// otherwise it throws error complaining it cannot resolve what `Vue` is
const entryComponent = new Vue({
el: "#entry-component",
data: {message: "world"}
})

因此,这编译成功。但是,我启动了我的开发服务器,转到包含此组件的相关页面,然后发生了一些奇怪的事情。

首先,它甚至没有渲染Hello部分。这实际上意味着 Vue 成功加载并挂载在目标 DOM 元素上。这是我没有得到的部分。我已经告诉过"用message替换{{message}}.为什么它不渲染它并完全清除#entry-component的内容?

提前谢谢。

故障 排除

运行时 Vue 警告 (?(

我认为可能相关的另一件事是浏览器在开发控制台中发出的警告:

[Vue warn]: You are using the runtime-only build of Vue where the template compiler is not available. Either pre-compile the templates into render functions, or use the compiler-included build.

这可能是因为我在app.js中确实import 'vue'.我只想要运行时 Vue。我不知道这是否会导致在 HTML 中硬编码的模板无法呈现。这似乎是一个错误,不知道它是否停止了客户端 Javascript 的执行。

显式导入 Vue 的 dist build

上面的错误给了我一些线索,并想尝试显式导入 vue 的发行版。我在下面导入了,但没有运气:

// app.js
// instead of > import 'vue'
import 'vue/dist/vue.js'  // still same error
import 'vue/dist/vue.esm.js'  // nope
import 'vue/dist/vue.common.js'  // no

我也在dist文件夹中阅读了README.md。它说vue.js拥有一切,包括编译器,但仍然没有运气。


环境

  • 我不知道它是否相关,但我使用 Django,我加倍确定我使用verbatim来逃避 Django 模板化。
  • Vue ^2.6.10
  • 网络包 ^4.41.2
  • Webpack CLI ^3.3.10
  • NPM 6.12.1
  • 节点 12.13.0

我自己已经解决了这个问题,想为谷歌员工分享答案。

所以,看起来我实际上已经导入了两个不同的Vue版本。一个在app.js中,另一个在相关的组件文件中。

import Vue from 'vue'

但是,该类实际上构建了一个不存在模板编译器的捆绑包Vue。因此,您需要做两件事:

  1. 首先,您需要删除条目文件上的导入,在本例中为app.js.
  2. 然后,您需要指定在相关文件中获取Vue类的位置,在本例中为包含模板编译器的构建。见下文:
// entry.js
import Vue from 'vue/dist/vue.js'
// this contains the template compiler

这解决了我的问题。

相关内容

最新更新