[英]Vue replaces HTML with comment when compiling with webpack
我面临的问题是,一旦我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')
}
})
您正在运行没有模板编译器的仅运行时构建。
查看https://v2.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
虽然 Leonie 的答案是功能性的,但生产构建通常不需要包括模板编译器。 我会说这可能是不希望的,因为动态构建模板可能会对性能产生影响,我认为在这个答案中就是这种情况。 此外,Leonie 的回答似乎在生产版本中包含了 Vue 的完整开发版本,由于此版本中包含所有额外内容,因此应该不鼓励这样做。 相反,可以在构建步骤中预编译模板。
执行此操作的最简单方法是使用单文件组件 (SFC),如上一个链接中所述:
[] 相关的构建设置会自动为您执行预编译,因此构建的代码包含已编译的渲染函数而不是原始模板字符串。
我需要根据自己的情况使用的另一种方法是为组件定义定义显式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 的完整开发版本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.