Coder Social home page Coder Social logo

fi3ework / vite-plugin-checker Goto Github PK

View Code? Open in Web Editor NEW
890.0 13.0 72.0 1.65 MB

💬 Vite plugin that provide checks of TypeScript, ESLint, vue-tsc, Stylelint and more.

Home Page: https://vite-plugin-checker.netlify.app

License: MIT License

JavaScript 5.13% TypeScript 80.58% HTML 3.98% CSS 1.81% Vue 8.31% Shell 0.18%
typescript vite vite-plugin vls vue-tsc vue eslint stylelint volar

vite-plugin-checker's Introduction

vite-plugin-checker's People

Contributors

akiyamka avatar angus96 avatar art0rz avatar ascott18 avatar asselin avatar cexbrayat avatar elwynelwyn avatar fgblomqvist avatar fi3ework avatar fredericlb avatar github-actions[bot] avatar hyoban avatar indexxuan avatar jfairley avatar jhoermann avatar jonkoops avatar justinhelmer avatar kylewlacy avatar mammad2c avatar modyqyw avatar nclavaud avatar nvh95 avatar soilspoon avatar specy avatar stephtr avatar wight554 avatar yuddomack avatar yusufkandemir avatar zlyyyy avatar zsparal avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

vite-plugin-checker's Issues

Show warnings only in console

Hi, love this plugin!

Is there a way to now show any kind of warning (TS, ESlint, ...) as an overlay but show them only in the console? A bit like CRA behaves?

Thank you

enableBuild causes no files to be outputted

If we have enableBuild set to true (the default), no files get outputted when building the app. Dev mode still works fine, but doing vite build results in this being the last message in terminal:

✓ 5396 modules transformed.

As in, it seems to skip rendering the chunks? Setting enableBuild to false makes the build work again.

The checker does not wait for all child processes to finish in build mode

When running with multiple checkers in build mode, the parent process exits as soon as one of the checkers fails. Unfortuntately, all the remaning child processes keep running and print their output to the console even after the parent process closes. I think it should wait for all the checkers to complete, print their results and exit with a non-zero status code in case of errors.

Vue2 - VLS throwing errors

I'm trying to use this plugin in Vue 2.

Typescript checker works as expected, however when I install and enable vls in config - I'm getting bunch of errors pointing at <template> tags in each component, for example:

  • ERROR(VLS) Duplicate identifier '(Missing)'.
  • ERROR(VLS) Cannot find name '__vlsRenderHelper'.
  • ERROR(VLS) Cannot find name '__vlsComponentData'.
  • ERROR(VLS) 'this' implicitly has type 'any' because it does not have a type annotation.
  • ERROR(VLS) Argument of type '{ props: { msg: string; }; on: {}; directives: never[]; }' is not assignable to parameter of type '__vlsComponentData__hello_world<Record<string, any>, any> & ThisType'

This happens even in brand new project created via Vite (vue-ts). The only thing I'm changing in original boilerplate is the vite plugin for vue, vue version, adding vue-template-compiler, plus ofc updating components to use options API.

Does anyone have an idea what might be causing such behavior?

Why ts error in .vue file can not be displayed in Vite HMR overlay

My IDE is Webstorm, I can get ts error in Typescript terminal, but it can not be dispalyed in Vite HMR overlay

export default defineComponent({
    name: 'App',
    components: {
        HelloWorld
    },
    setup() {
        const a = ref<string>(22223);
        a.value = 22212;
        return {a};
    }
});

image

And Vite HMR overlay also doesn't show the error

image

is is possible to show the error on broswer just like Vue CLI?

image

vls configuration currently does not recognize setup+ts

First of all, this is a very powerful plug-in, thanks to the author!

But I have a problem, it would be perfect if anyone can improve it.


Scenes:(a simple demo with setup + ts)

My needs:

watch in the devlopment environment,So I can't use vueTsc directly(Because it only applies to the build environment)

<template>
  <p v-cloak>{{ name }}</p>
</template>

<script lang="ts" setup>
import { ref } from 'vue';
const name = ref('test');
</script>

The following error will appear:

  • ERROR(VLS) Module '"xxx.vue"' has no default export

  • ERROR(VLS) Property 'name' does not exist on type 'unknown'.

  • ERROR(VLS) 'name' is declared but its value is never read.

vls configuration currently does not recognize setup+ts

but typescript: true can only applies to xxx.tsx in the development environment,it does not meet my needs


Need your help, Thanks!

TS isolatedModules setting conflciting with vite-plugin-checker

Hello,

Thanks for this library, it's great!

I did want to ask about isolatedModules being set to true in tsconfig.json.

The Vite docs, write that it should be set to true right here.

The only way I could get this plugin to show any of the typescript errors is if it was set to false or removed it from tsconfig.

Thanks again!

Custom tsconfig.json is not respected in build mode

When using vite build, the TS checker uses the default tsconfig.json which leads to incorrect error reporting. I noticed it when building an Electron project with separate tsconfig.json files for the main and renderer and the custom include/files/exclude configuration was ignored when specifying the tsconfig file.

Vue 2 support ?

Great Works.
It seems use vue-tsc or tsc, does these work for vite + vue2 ?

Add log level

We can ignore some suggestion level outputs, such as

image

References to checker plugin in production build

The new version 0.4.0 adds the following line to the index.html

<script type="module">import { inject } from "/@vite-plugin-checker-runtime"; inject();</script>

This is done also for a production build, in my eyes this is wrong and should only happen for dev builds.

Allow eslint warnings to fail a build

We've grown accustomed to this behaviour from create-react-app, which fails builds in CI if there are any warnings, and have even started using eslint --max-warnings 0 in our CI builds. How do you feel about adding something like a maxWarnings option to this plugin?

eslint warning or error information not clear when save the file and trigger recompile

hello, I got a minor question and I think it is not the problem from vite, so I wanna to talk about this.

I write some code that can cause several error message, if I fix part of it and save file, the project reload and the remain error message overlay the old thing. Up to now it seems ok, but when I fix all of it, I expected all eslint error message can get clear but it still show the previous error message in terminal screen. It looks a bit of weired.

phenomenon

image

image

vite config

import checker from 'vite-plugin-checker';

// ...

return defineConfig({
    plugins: [
      reactRefresh(),
      checker({
        typescript: true,
        eslint: {
          files: ['./src', './config'],
          extensions: ['.ts', '.tsx', '.js', '.jsx'],
        },
      }),
    ],
  });

ESLint failures aren't stopping the build

Neither --max-warnings or actual eslint errors are failing the build as expected

Here's a run with an error-level issue in eslint:

$ vite build
vite v2.8.4 building for production...
transforming...
✓ 643 modules transformed.

[REDACTED]/Films.tsx
   9:3   warning  Unexpected console statement              no-console
  13:9   warning  'wut' is assigned a value but never used  @typescript-eslint/no-unused-vars
  13:16  error    Expected property shorthand               object-shorthand

✖ 3 problems (1 error, 2 warnings)
  1 error and 0 warnings potentially fixable with the `--fix` option.

rendering chunks...
...
Done in 6.74s.                                                                                                                                  

mike at vscode-remote in [REDACTED] on vite*
$ echo $?
0

And a warning with --max-warnings:

$ vite build
vite v2.8.4 building for production...
transforming...
✓ 643 modules transformed.

[REDACTED]/Films.tsx
  9:3  warning  Unexpected console statement  no-console

✖ 1 problem (0 errors, 1 warning)

ESLint found too many warnings (maximum: 0).
rendering chunks...
...
Done in 6.61s.                                                        
                                                                          
mike at vscode-remote in [REDACTED] on vite*
$ echo $?
0

And to confirm, when running eslint manually it exits with an error as expected in both scenarios:

$ eslint Films.tsx

Films.tsx
   9:3   warning  Unexpected console statement              no-console
  13:9   warning  'wut' is assigned a value but never used  @typescript-eslint/no-unused-vars
  13:16  error    Expected property shorthand               object-shorthand

✖ 3 problems (1 error, 2 warnings)
  1 error and 0 warnings potentially fixable with the `--fix` option.

error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

mike at vscode-remote in [REDACTED] on vite*
$ echo $?
1
$ eslint --max-warnings=0 Films.tsx

Films.tsx
  9:3  warning  Unexpected console statement  no-console

✖ 1 problem (0 errors, 1 warning)

ESLint found too many warnings (maximum: 0).
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

mike at vscode-remote in [REDACTED] on vite*
$ echo $?
1

config.eslint configFile, maxWarnings giving errors

Hi,

When trying to configure the eslint parameters configFile or maxWarnings I get errors. Thoughts?
The parameters files and extensions seem to be working fine.

I am using:

"eslint": "^7.32.0",
"vite-plugin-checker": "^0.3.4"

See the screenshots below.

image

image

Many thanks for looking into this.

TypeError on config run (ESM Support)

I have my Vite config set up like so:

import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import checker from "vite-plugin-checker";

export default defineConfig({
	plugins: [
		vue(),
		checker({
			typescript: true,
			vueTsc: true,
		}),
	],
});

I'm using this in a Vue 3 project, and my aim is to set up proper type checks separate from VSCode's since Vite does not intend to support this, even at build time.

After adding the vite-plugin-checker import and calling checker, running vite or vue-tsc results in an error:

failed to load config from /[...]/vite.config.js
error when starting dev server:
TypeError: checker is not a function

As far as I can tell, I've imported vite-plugin-checker correctly according to the README documentation. Either I'm missing some obvious thing here, or the export structure is not the same at runtime as its declared type.

Potential CPU usage issues with typescript/eslint

I've noticed that since after I enabled this plugin, the CPU usage of the node process went up to 100% and my fans started to go crazy.

The node CPU usage starts to increase after a few compilation/checks.

// vite.config.js
import reactRefresh from '@vitejs/plugin-react-refresh';
import { defineConfig } from 'vite';
import checker from 'vite-plugin-checker';

export default defineConfig({
    build: {
        outDir: 'build',
    },
    server: {
        open: true,
        proxy: {
            '/api': {
                target: 'http://localhost:5000',
                changeOrigin: true,
            },
        },
    },
    plugins: [
        reactRefresh(),
        checker({
            typescript: true,
            eslint: {
                files: ['./src'],
                extensions: ['.ts', '.tsx'],
            },
        }),
    ],
});
  System:
    OS: macOS 11.5.2
    CPU: (12) x64 Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
    Memory: 2.05 GB / 32.00 GB
    Shell: 5.8 - /bin/zsh
  Binaries:
    Node: 14.16.1 - /usr/local/bin/node
    npm: 6.14.14 - /usr/local/bin/npm
  Browsers:
    Chrome: 92.0.4515.159
    Firefox: 90.0.2
    Safari: 14.1.2
  npmPackages:
    vite-plugin-checker: ^0.3.4 => 0.3.4

I have problems to identify the issue any further. This is the behaviour if I have this plugin enabled. So I'm afraid I cant put any more details to it. I'm mostly creating this issue to see if there's anyone else experiencing the same issue?

Release 0.3.3

Would it be possible to release a new version with the ESLint fixes? 🙂

Add support for Vite `server.hmr.path` configuration.

In Vite, you are able to configure customer settings for the websocket connection between the frontend application and the backend Vite dev server:

https://vitejs.dev/config/#server-hmr

As mentioned in the Vite documentation, this is useful when you are using an SSL proxy in front of Vite dev server. This is exactly what I am doing, using NGINX as an SSL proxy, passing HTTPS/SSLtraffic on port443 to the Vite dev server running on (by default) port 3000.

However, because of how one uses NGINX as a websocket proxy, I need to proxy websocket (wss://) traffic over a different path. Vite supports this via the server.hmr.path configuration option:

vite.config.js

defineConfig({
  // ...
  server: {
    hmr: {
      clientPort: 443,
      path: '/hmr'
    },
    host: 'x.y.z',
    port: 3000,
    strictPort: true
  }

This all works perfectly with Vite. However, vite-plugin-checker does not allow the same configuration options, so it tries to establish a websocket connection to:

const socketProtocol = null || (location.protocol === 'https:' ? 'wss' : 'ws')
const socketHost = `${location.hostname}:${location.port}`
const socket = new WebSocket(`${socketProtocol}://${socketHost}`, 'vite-hmr')

Whereas the HMR traffic, from Vite's perspective, is being sent on ${socketProtocol}://${socketHost}/${vite.server.hmr.path}

As, such, I get the following error in the console when the page loads:

WebSocket connection to 'wss://x.y.z/' failed: Error during WebSocket handshake: Unexpected response code: 404 
@vite-plugin-checker-runtime:1347

What I am looking for is a configuration option that lets me specify the path that the vite-plugin-checker websocket code should connect to. That is, connect to wss://x.y.z/${path} as opposed to wss://x.y.z/.

Here is pertinent code in vite:

https://github.com/vitejs/vite/blob/76bbcd09985f85f7786b7e2e2d5ce177ee7d1916/packages/vite/src/client/client.ts#L25

In my example example, the __HMR_xxx__ values are injected as:

__HMR_PROTOCOL__ = 'wss';
__HMR_HOSTNAME__ = 'x.y.z:443/hmr'

Exception when running dev

(node:15198) UnhandledPromiseRejectionWarning: TypeError: _chalk.constructor is not a constructor
    at getChalk (/myapp/node_modules/@babel/highlight/lib/index.js:102:31)
    at Object.codeFrameColumns (/myapp/node_modules/@babel/code-frame/lib/index.js:92:41)
    at createFrame (/myapp/node_modules/vite-plugin-checker/lib/logger.js:76:32)
    at /myapp/node_modules/vite-plugin-checker/lib/logger.js:225:27
    at Array.map (<anonymous>)
    at Object.normalizeEslintDiagnostic (/myapp/node_modules/vite-plugin-checker/lib/logger.js:201:10)
    at /myapp/node_modules/vite-plugin-checker/lib/checkers/eslint/main.js:56:72
    at Array.map (<anonymous>)
    at Object.<anonymous> (/myapp/node_modules/vite-plugin-checker/lib/checkers/eslint/main.js:56:52)
    at Generator.next (<anonymous>)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:15198) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:15198) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

events.js:292
      throw er; // Unhandled 'error' event
      ^
TypeError [Error]: _chalk.constructor is not a constructor
    at getChalk (/myapp/node_modules/@babel/highlight/lib/index.js:102:31)
    at Object.codeFrameColumns (/myapp/node_modules/@babel/code-frame/lib/index.js:92:41)
    at createFrame (/myapp/node_modules/vite-plugin-checker/lib/logger.js:76:32)
    at Object.normalizeTsDiagnostic (/myapp/node_modules/vite-plugin-checker/lib/logger.js:109:21)
    at reportDiagnostic (/myapp/node_modules/vite-plugin-checker/lib/checkers/typescript/main.js:41:55)
    at Array.forEach (<anonymous>)
    at emitFilesAndReportErrors (/myapp/node_modules/typescript/lib/typescript.js:115397:21)
    at Object.result.afterProgramCreate (/myapp/node_modules/typescript/lib/typescript.js:115574:13)
    at synchronizeProgram (/myapp/node_modules/typescript/lib/typescript.js:115864:22)
    at Object.createWatchProgram (/myapp/node_modules/typescript/lib/typescript.js:115788:9)
Emitted 'error' event on process instance at:
    at emitUnhandledRejectionOrErr (internal/event_target.js:545:11)
    at MessagePort.[nodejs.internal.kHybridDispatch] (internal/event_target.js:358:9)
    at MessagePort.exports.emitMessage (internal/per_context/messageport.js:18:26)
    at Worker.[kOnExit] (internal/worker.js:233:5)
    at Worker.<computed>.onexit (internal/worker.js:174:20)

Process finished with exit code 1

Let me know what kind of information would be helpful here.

Stylelint support

Fantastic work on this so far! 🎉

Another handy tool to support could be stylelint. I think they're pretty much the universal CSS/SCSS linter. They have a Node API.

Cannot find module '' or its corresponding type declarations. when using alias @

I'm getting a ton of these errors
Cannot find module '@/components/Navigation/MainMenu/MainMenu.vue' or its corresponding type declarations.

I'm not getting these errors elsewhere (when developing in vs code or when running vue-tsc).

tsconfig

       ...
        "paths": {
            "@/*": ["src/*"],
        },
        ...

vite.config.js and tsconfig.json is in the same folder, so the setup is pretty ordinary.

Also worth to mention that I'm using volar with typescript takeover mode.

Let me know if you need me to test anything to hunt this bug down :)

"No issues found" message if no checks return any errors/warnings

If I have an ESLint error or two, then fix them, I see nothing in the console that indicates that I have done so.

On top of that, the Typescript checker currently seems to emit its own message ("Found X errors. Watching for file changes"). However it's not clear that it's coming from TS.

Instead of the above, I propose this:

  • If all checkers run and there are no issues with any of them, print a pretty "No issues found, waiting for file changes..." message (maybe in green or something cool, maybe with a checkmark, idk)
  • Mute TypeScripts own message

OR

  • If a checker runs and there are no issues, print a pretty "[ESLint] No issues found, waiting for file changes..." message (so one for each checker)
  • Mute TypeScripts own message

The first solution is preferred I think, but if everything is running async the latter might be better.
In short, it should be clear when the checker(s) run and there were no issues, just to clarify that if there were previously issues, there are none anymore.

No way to customize VLS settings

Unless I'm missing something, it doesn't appear there's a way to customize the settings passed to VLS.

I want to perform type checking on my <script lang=ts>, but not on my templates. It seems these settings are hardcoded in initParams and there's no way to override them. Is there something I'm missing?

ESLint output is always about the first error found

Seems like this code incorrectly only looks at the firstMessage rather than the current one in the iteration (d):

return diagnostic.messages
.map((d) => {
let level = DiagnosticLevel.Error
switch (firstMessage.severity) {
case 0: // off, ignore
level = DiagnosticLevel.Error
return null
case 1: // warn
level = DiagnosticLevel.Warning
break
case 2: // error
level = DiagnosticLevel.Error
break
}
const loc: SourceLocation = {
start: {
line: firstMessage.line,
column: firstMessage.column,
},
end: {
line: firstMessage.endLine || 0,
column: firstMessage.endColumn,
},
}
const codeFrame = createFrame({
source: diagnostic.source ?? '',
location: loc,
})
return {
message: firstMessage.message,
conclusion: '',
codeFrame,
stripedCodeFrame: codeFrame && strip(codeFrame),
id: diagnostic.filePath,
checker: 'ESLint',
loc,
level,
} as any as NormalizedDiagnostic
})

ES Module Support

Would like the package to also support ESM. Current build config is CJS. When using Vite in an ES module, this will throw:

failed to load config from C:\Projects\test-bench\vite-plugin-checker\vite.config.ts
error when starting dev server:
TypeError: checker is not a function
at file:///C:/Projects/test-bench/vite-plugin-checker/vite.config.ts.js?t=1643740226049:8:5
at ModuleJob.run (internal/modules/esm/module_job.js:170:25)
at async Loader.import (internal/modules/esm/loader.js:178:24)
at async loadConfigFromFile (C:\Projects\test-bench\vite-plugin-checker\node_modules\vite\dist\node\chunks\dep-f5552faa.js:75080:31)
at async resolveConfig (C:\Projects\test-bench\vite-plugin-checker\node_modules\vite\dist\node\chunks\dep-f5552faa.js:74656:28)
at async createServer (C:\Projects\test-bench\vite-plugin-checker\node_modules\vite\dist\node\chunks\dep-f5552faa.js:60326:20)
at async CAC. (C:\Projects\test-bench\vite-plugin-checker\node_modules\vite\dist\node\cli.js:688:24)

Reproduction Repo: https://github.com/buckeyez/vite-plugin-checker (steps are in README.md)

Warnings are being displayed as errors

Hi,

I have a rule as a warning and yet, it triggers a blocking popup box, that seems to be an error rather than a warning. Is there a way to avoid displaying warnings?

Thanks.

image

Please consider deploying improved 'watch' usage to 0.3.x stable

Hi @fi3ework !

I am using root of vite config and 'eslint' option in vite-plugin-checker.
But I got an error when I edit a watched file.
(like this https://stackblitz.com/edit/vite-yasinn?file=rootA%2Fmain.js)

As a result, it was necessary to apply the root path to the cwd option of chokidar.
and The code has already been fixed and seems to have been released in 0.4.0 beta2.

// watch lint
const watcher = chokidar.watch([], {
cwd: root,
ignored: (path: string) => path.includes('node_modules'),
})

this beta version looks raising another error yet and is having difficulties because it is not synchronized with the documentation.
so Could you please release this commit as the 0.3 stable version?

ps. Thanks for making a awesome project 😆

How to slient the ignored file warning

Because of my program using auto-generated .d.ts, which is incompatible with my custom eslint rules, I had to ignore these files.

This issue is caused by eslint 'ignore_file' like:

❯ pnpm eslint "./src/auto-imports.d.ts"

/root/Programs/*****/auto-imports.d.ts
  0:0  warning  File ignored because of a matching ignore pattern. Use "--no-ignore" to override

✖ 1 problem (0 errors, 1 warning)

attachment 1:
emmm, is eslint.dev.eslint defined in vite.config.js? THX

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.