【问题标题】:How to precompile Vue objects in js files?如何在 js 文件中预编译 Vue 对象?
【发布时间】:2022-01-11 10:04:45
【问题描述】:

我有一个 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 对象?

【问题讨论】:

    标签: javascript node.js vue.js webpack


    【解决方案1】:

    我找到了解决办法,没有办法直接编译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')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-17
      • 2022-06-15
      • 2019-02-01
      • 1970-01-01
      • 2021-04-26
      • 2020-05-04
      • 1970-01-01
      • 2021-12-25
      相关资源
      最近更新 更多