【问题标题】:Vue + Typescript + webpack: Import html into componentVue + Typescript + webpack:将 html 导入组件
【发布时间】:2019-08-15 13:49:43
【问题描述】:

我有一个 typescript + vue + webpack 应用程序,我想要将 html 与代码分开。
我关注了this tutorial,并做了一个简单的Hello Word。

Webpack 配置

const path = require('path');

module.exports = {
    mode: "development",
    entry: './src/app.ts',
    output: {
        path: path.resolve('dist'),
        filename: 'bundle.js'
    },
    module: {
        rules: [
            {
                test: /\.(ts|tsx)?$/,
                loader: 'ts-loader',
                exclude: /node_modules/                
            },
            {
                test: /.html$/,
                loader: "vue-template-loader",
                exclude: /index.html/
            }
        ]
    },
    resolve: {
        extensions: [
            '.js',
            '.vue',
            '.tsx',
            '.ts'
        ]
    }
};

HTML

<div>
    <h2>Hello from {{message}}</h2>
</div>

Vue 组件

import Vue from "vue";
import Component from "vue-class-component";
// template: '<button @click="onClick">Click!</button>'
import WithRender from "./home.html";

@WithRender
@Component
export default class HomeComponent extends Vue {

    public message: string = "Word";

    constructor() {
        super();
    }

    mounted() { }
}

在我添加了这个 shim

declare module '*.html' {

        import Vue, { ComponentOptions, FunctionalComponentOptions } from 'vue'
        interface WithRender {
            <V extends Vue, U extends ComponentOptions<V> | FunctionalComponentOptions>(options: U): U
            <V extends typeof Vue>(component: V): V
        }

        const withRender: WithRender
        export default withRender
}

我(几乎)了解 typescript decorators 的工作原理,但我不了解 shim 代码,如何将这段代码 inject 的 html 放入 Vue组件?

我从Typescript site读到了关于装饰器的文章

【问题讨论】:

    标签: typescript vue.js webpack


    【解决方案1】:

    vue-template-loader 将 HTML 模板编译为 render 函数,@WithRender 将其插入到类定义中。

    例如,这个 HTML:

    <div>Hello world</div>
    

    转换成这个render函数:

    render(h) {
      return h('div', 'Hello world')
    }
    

    然后,将@WithRender(导入上面示例 HTML 模板的结果)应用于class Foo extends Vue {} 会产生:

    class Foo extends Vue {
      render(h) {
        return h('div', 'Hello world')
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-06-04
      • 2016-05-26
      • 2018-03-12
      • 2017-06-19
      • 1970-01-01
      • 2020-10-17
      • 2017-03-10
      • 2017-08-02
      • 2021-08-29
      相关资源
      最近更新 更多