Настройка скрипта svelte и typescript «watch» для разработки расширения vscode

#typescript #visual-studio-code #vscode-extensions #svelte

#typescript #visual-studio-code #vscode-расширения #стройный

Вопрос:

я новичок в разработке расширений typescript, svelte и vscode, и это мой первый вопрос 😁.

Моя цель — включить автоматическую компиляцию файлов svelte и typescript для моего проекта.

Я начал создавать проект шаблона typescript с помощью «yo code» в моем терминале, затем я добавил rollup.conifg.js файл для работы с файлами в подпапке my /webviews с его собственным файлом tsconfig.json.

Сначала я установил скрипты в package.json для запуска компиляции файлов svelte. Все работает нормально, за исключением предупреждения

 > rollup -c amp;amp; tsc -p ./

[rollup-plugin-svelte] Unknown "dev" option. Please use "compilerOptions" for any Svelte compiler configuration.
[rollup-plugin-svelte] Unknown "css" option. Please use "compilerOptions" for any Svelte compiler configuration.

webviews/pages/HelloWorld.ts → out/compiled/HelloWorld.js...
(!) Plugin typescript: @rollup/plugin-typescript: Typescript 'sourceMap' compiler option must be set to generate source maps.
created out/compiled/HelloWorld.js in 1.9s
 

В этом случае мои скрипты в файле package.json были установлены следующим образом

 "scripts":
    {
        "vscode:prepublish": "npm run compile",
        "compile": "rollup -c amp;amp; tsc -p ./",
        "lint": "eslint src --ext ts",
        "watch": "tsc -watch -p ./",
        "pretest": "npm run compile amp;amp; npm run lint",
        "test": "node ./out/test/runTest.js"
    }
 

Поэтому я хотел настроить скрипт «watch» на автоматическое ожидание изменения файла (ts и svelte файлов).
Я отредактировал раздел скрипта в файле package.json следующим образом:

 "scripts":
    {
        "vscode:prepublish": "npm run compile",
        "compile": "rollup -c amp;amp; tsc -p ./",
        "lint": "eslint src --ext ts",
        "watch": "concurrently "rollup -c -w" "tsc -watch -p ./"",
        "pretest": "npm run compile amp;amp; npm run lint",
        "test": "node ./out/test/runTest.js"
    }
 

Терминал «Task — watch» показывает мне, что два сценария работают нормально, но «другой» тестовый сеанс vscode, который обычно запускается, не отображается.

 12:18:24 AM - Starting compilation in watch mode...
[1] 
[0] [rollup-plugin-svelte] Unknown "dev" option. Please use "compilerOptions" for any Svelte compiler configuration.
[0] [rollup-plugin-svelte] Unknown "css" option. Please use "compilerOptions" for any Svelte compiler configuration.
[0] rollup v2.35.1
[0] bundles webviews/pages/HelloWorld.ts → out/compiled/HelloWorld.js...
[0] created out/compiled/HelloWorld.js in 2.8s
[1] 
[1] 12:18:28 AM - Found 0 errors. Watching for file changes.
 

На самом деле мой rollup.config.js файл является

 import svelte from "rollup-plugin-svelte";
import resolve from "@rollup/plugin-node-resolve";
import commonjs from "@rollup/plugin-commonjs";
import { terser } from "rollup-plugin-terser";
import sveltePreprocess from "svelte-preprocess";
import typescript from "@rollup/plugin-typescript";
import path from "path";
import fs from "fs";

const production = !process.env.ROLLUP_WATCH;

export default fs
  .readdirSync(path.join(__dirname, "webviews", "pages"))
  .map((input) => {
    const name = input.split(".")[0];
    return {
      input: "webviews/pages/"   input,
      output: {
        sourcemap: true,
        format: "iife",
        name: "app",
        file: "out/compiled/"   name   ".js",
      },
      plugins: [
        svelte({
          // enable run-time checks when not in production
          dev: !production,
          // we'll extract any component CSS out into
          // a separate file - better for performance
          css: (css) => {
            css.write(name   ".css");
          },
          preprocess: sveltePreprocess(),
        }),

        // If you have external dependencies installed from
        // npm, you'll most likely need these plugins. In
        // some cases you'll need additional configuration -
        // consult the documentation for details:
        // https://github.com/rollup/plugins/tree/master/packages/commonjs
        resolve({
          browser: true,
          dedupe: ["svelte"],
        }),
        commonjs(),
        typescript({
          tsconfig: "webviews/tsconfig.json",
          sourceMap: !production,
          inlineSources: !production,
        }),

        // In dev mode, call `npm run start` once
        // the bundle has been generated
        // !production amp;amp; serve(),

        // Watch the `public` directory and refresh the
        // browser on changes when not in production
        // !production amp;amp; livereload("public"),

        // If we're building for production (npm run build
        // instead of npm run dev), minify
        production amp;amp; terser(),
      ],
      watch: {
        clearScreen: false,
      },
    };
  });
 

итак, мой файл tsconfig.json в корневой папке

 {
    "compilerOptions": {
        "module": "commonjs",
        "target": "es6",
        "outDir": "out",
        "lib": [
            "es6"
        ],
        "sourceMap": true,
        "rootDir": "src",
        "strict": true   /* enable all strict type-checking options */
        /* Additional Checks */
        // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
        // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
        // "noUnusedParameters": true,  /* Report errors on unused parameters. */
    },
    "exclude": [
        "node_modules",
        ".vscode-test",
        "webviews"
    ]
}
 

и мой tsconfig.js файл в моей папке «webviews», используемой для файлов svelte

 {
    "extends": "@tsconfig/svelte/tsconfig.json",
    "include": ["./**/*", ],
    "exclude": ["../node_modules/*"],
    "compilerOptions": {"strict": true, }
}
 

Есть ли какая-либо неправильная конфигурация? У кого-нибудь есть какие-либо советы?

Комментарии:

1. Как выглядит ваша конфигурация накопительного пакета и tsconfig? Не могли бы вы добавить его в вопрос?

2. Я добавил недостающие файлы

Ответ №1:

С помощью этих параметров вы хотите "rollup-plugin-svelte": "^6.0.0" . В переходе на 7 произошли серьезные изменения. Посмотрите список изменений.

Комментарии:

1. Вы спасли мой день!