繁体   English   中英

TypeScript 可以理解 Svelte 组件吗?

[英]Can TypeScript understand Svelte components?

Svelte 最终输出原生 JavaScript 类。 所以,TypeScript 可以理解这些。 但是,Svelte 组件必须首先从它们的初始.html格式进行编译。 在那之前,可以理解的是,默认情况下,TypeScript 无法理解它们的初始形式。 因此,即使在运行时导入成功,它也会报告“找不到模块”错误。 有没有办法让 TypeScript 理解它们?

一种解决方法是为.html模块提供类型定义,近似于标准的 Svelte 组件接口。 但是,更希望为每个单独的组件简单地使用真实的组件类输出本身,从而产生最准确的类型信息。

顺便说一句,我没有提到像 Webpack 或 Rollup 这样的工具,它们通常为 Svelte 执行编译步骤。 我不知道这些工具是否与这个问题相关。

更新 1:我更深入地研究了 TypeScript, 似乎可以为它创建插件 但是,它们似乎有限,因此可能没有用。

更新 2:也有一些关于 TypeScript 中自定义模块加载器的讨论​​(这里这里)。

是的 使用rollup-plugin-svelterollup-plugin-typescript ,它应该可以工作。 我现在在汇总文件中使用它,如下所示:

import commonjs from 'rollup-plugin-commonjs'
import replace from 'rollup-plugin-replace'
import resolve from 'rollup-plugin-node-resolve'
import svelte from 'rollup-plugin-svelte'
import typescript from 'rollup-plugin-typescript'

const path = require('path')
const fs = require('fs')

export default {
  input: 'src/index.ts',
  plugins: [
    typescript(),
    commonjs({
      include: 'node_modules/**'
    }),
    resolve({
      browser: true,
      preferBuiltins: false // for url npm module; otherwise rollup assumes node
    }),
    // Replace is to shut up redux
    replace({
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
    }),
    svelte({
      // By default, all .html and .svelte files are compiled
      extensions: ['.my-custom-extension', '.html', '.svelte'],

      // You can restrict which files are compiled
      // using `include` and `exclude`
      // include: 'src/components/**/*.html',

      // By default, the client-side compiler is used. You
      // can also use the server-side rendering compiler
      // generate: 'ssr',

      // Extract CSS into a separate file (recommended).
      css: function (css) {
        fs.writeFileSync('./dist/svelte.css', css)
      }
    })
  ],
  output: {
    format: 'iife',
    file: path.join(__dirname, './dist/index_dist.js') // equivalent to --output
  }
}

是的 Svelte 官方支持打字稿! https://svelte.dev/blog/svelte-and-typescript

入门模板带有 setupTypeScript.js 实用程序: https : //github.com/sveltejs/template#using-typescript

目前它不能与 eslint 结合使用,但正在研究中

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM