如何在js文件中预编译Vue对象



我有一个Electron项目,我正在使用webpack作为模块绑定器,下面是我项目的相关代码和配置。

webpack.config.js:

const path = require('path')
const {VueLoaderPlugin} = require("vue-loader")
module.exports = {
mode: "development",
entry: path.join(__dirname, 'src/index.js'),
output: {
path: path.join(__dirname, 'dist'),
filename: "bundle.js"
},
plugins: [
new VueLoaderPlugin()
],
module: {
rules: [
{
test: /.vue$/,
use: [
{loader: "vue-loader"}
]
},
{
test: /.css$/,
use: [
{loader: "vue-style-loader"},
{loader: "css-loader"}
]
}
]
}
}

src/index.js:

import Vue from 'vue'
new Vue({
template: '<h1>{{ message }}</h1>',
data: {
message: "Hello World"
}
}).$mount('#app')

src/index.html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello World</title>
</head>
<body>
<div id="app"></div>
<script src="../dist/bundle.js"></script>
</body>
</html>

我知道它可以在webpack.config.js:中配置

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

但是index.js中的Vue对象只是一个入口,我不想使用Vue.esm.js来让这么小的代码顺利运行,我想使用Vue.runtime-only.js,但它需要预编译模板。

如何预编译此Vue对象?

我找到了一个解决方案,无法直接编译js文件中的Vue对象。

但是您可以将index.js中的中文Vue对象的模板提取到App.Vue文件中:

<template>
<div>
<h1>Hello World.</h1>
</div>
</template>

index.js导入App.vue:

import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false
new Vue({
// Load the precompiled template with render .
render: h => h(App)
}).$mount('#app')

最新更新