在使用webpack进行编译时,Vue将HTML替换为注释

时间:2018-03-17 10:15:37

标签: javascript webpack vue.js

我遇到的问题是,一旦我import vue,vue的包装元素(在我的情况下为#app)将被替换为以下注释

<!--function (e,n,r,o){return sn(t,e,n,r,o,!0)}-->

控制台中没有错误,webpack编译得很好,但我从vue的mounted方法获取控制台日志。

我的index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="app">
        <h1>some content</h1>
        {{test}}
    </div>
    <script src="dist/bundle.js"></script>
</body>
</html>

webpack.config.js

const path = require('path');

module.exports = {
    entry: './src/app.js',
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist')
    }
}

的src / app.js

import Vue from 'vue'

const app = new Vue({
    el: "#app",
    data: {
        test: "asdf"
    },
    mounted() {
        console.log('mounted')
    }
})

2 个答案:

答案 0 :(得分:3)

您正在运行没有模板编译器的仅运行时版本。

查看https://vuejs.org/v2/guide/installation.html#Webpack

您需要为'vue'创建别名,因此webpack包含来自node_modules /的正确的vue / dist / *。js:

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

另见https://forum.vuejs.org/t/what-is-the-compiler-included-build/13239

答案 1 :(得分:0)

虽然Leonie的回答是实用的,但生产构建通常不需要模板编译器。我想说这可能是不希望的,因为动态构建模板可能会对性能产生影响,我认为答案就是这种情况。此外,看起来Leonie的答案在生产版本中包含Vue的完整开发版本,由于所有extra content included in this version,因此不应鼓励使用。相反,可以在构建步骤中pre-compile templates

最简单的方法是使用单文件组件(SFC),如上一个链接所述:

  

[The]关联的构建设置自动执行以下操作的预编译:   您,因此构建的代码包含已经编译的渲染函数   而不是原始模板字符串。

我需要根据自己的情况使用的另一种方法是,为组件定义定义一个显式的render函数,而不是template,因此不需要编译。我之所以需要它,是因为我当时生成的Vue项目的所有组件都使用了SFC,但根“安装”组件除外,该组件是使用以下对象明确定义的:

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

这在开发模式下工作正常,但由于遇到“功能注释”问题而无法生产。从Leonie的答案中得出的见解,我将以下代码片段替换为以下内容:

new Vue({
  el: '#app',
  store,
  router,
  components: { App },
  render: (h) => {
    return h(App)
  }
})

这解决了我的生产版本中的问题,而无需我包括Vue的完整开发版本。