【问题标题】:Why importing the Vue.js source works, but not the module?为什么导入 Vue.js 源代码有效,但模块无效?
【发布时间】:2017-12-29 09:37:15
【问题描述】:

以下 HTML 代码

<!DOCTYPE html>
<html lang="en">
    <body>
        Greeting below: 
        <div id="time">
            {{greetings}}
        </div>
        <script src='bundle.js'></script>
    </body>
</html>

连同entry.js 文件

// either the import or the require work
Vue = require('./vue.js')
//import Vue from './vue.js'
new Vue({
    el: "#time",
    data: {
        greetings: "hello world"
    }
})

还有webpack.config.js

module.exports = {
    entry: './entry.js',
    output: {
        filename: 'bundle.js'
    }
}

工作正常(vue.js 是从站点或 CDN 本地下载的)。

然后我尝试使用通过npm install vue --save-dev 安装的vue 模块,方法是将entry.js 更改为

import Vue from 'vue'
new Vue({
    el: "#time",
    data: {
        greetings: "hello world"
    }
})

这个版本不再工作了:整个&lt;div&gt;没有被渲染(只显示Greeting below)。

应该怎么做才能让 Vue.js 与 webpack 一起使用?

Vue 文档多次提到 webpack,但仅在组件或生产构建的上下文中。

【问题讨论】:

标签: javascript webpack vue.js webpack-2


【解决方案1】:

您可以改为导入已编译 (dist) 版本的 vue。

import Vue from 'vue/dist/vue.js'

【讨论】:

  • 模块说明符不应该以'./'或诸如此类的开头吗?
  • 示例中的假设是您从node_modules 文件夹中导入它。
【解决方案2】:

要诊断问题,最好查找任何错误,无论是来自命令行上的构建工具还是浏览器中的开发工具。如果您打开 devtools 控制台,您将看到来自 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.

Vue 有两个不同的版本,Runtime + Compiler vs. Runtime-only。如果您在 DOM 中有模板,则需要对其进行编译才能使用它们。默认情况下,Vue 只包含运行时,因为它更轻量级,而且通常模板在构建时已经预编译为 JavaScript。

还要包含您需要导入的编译器vue/dist/vue.esm

import Vue from 'vue/dist/vue.esm'

这与来自 CDN 的版本相同,只是它使用 ES 模块,webpack 将处理它,您应该更喜欢它而不是 vue/dist/vue.js,后者正是来自 CDN 的版本。

或者,您可以使用 webpacks resolve.alias 来定义别名,因此当您导入 vue 时,它将改为导入 vue/dist/vue.esm

resolve: {
    alias: {
        'vue$': 'vue/dist/vue.esm.js'
    }
}

为了能够使用仅运行时构建,您可以将Single File Components.vue 文件一起使用。为此,您必须配置 vue-loader,它将在构建时预编译模板。

【讨论】:

  • 感谢您的完整回答 - 但我不使用组件。正如您在问题中看到的,这只是一个学习与 Vue.js 集成的基本 Vue.js 应用程序。在这种情况下:使用import Vue from 'vue' 有什么问题?
  • 我知道您没有使用任何组件。但是您在 DOM 中使用了一个模板:&lt;div id="time"&gt;{{greetings}}&lt;/div&gt;,这需要模板编译器,它不在常规导入中 (vue),但它在 npm 包中的vue/dist/vue.esm.js 中可用。您下载的源代码确实包含模板编译器。
猜你喜欢
  • 1970-01-01
  • 2015-07-11
  • 1970-01-01
  • 2021-01-16
  • 2011-09-09
  • 1970-01-01
相关资源
最近更新 更多