I generated SvelteKit project using npm create svelte#latest and added some .ts files for some library but running eslint . it cant find errors.
I have this default eslint config generate from svelte.
.eslintrc.cjs
module.exports = {
root: true,
parser: '#typescript-eslint/parser',
extends: ['eslint:recommended', 'plugin:#typescript-eslint/recommended', 'prettier'],
plugins: ['svelte3', '#typescript-eslint'],
ignorePatterns: ['*.cjs'],
overrides: [{ files: ['*.svelte'], processor: 'svelte3/svelte3' }],
settings: {
'svelte3/typescript': () => require('typescript')
},
parserOptions: {
sourceType: 'module',
ecmaVersion: 2020
},
env: {
browser: true,
es2017: true,
node: true
}
};
and tsconfig.json
{
"extends": "./.svelte-kit/tsconfig.json",
"compilerOptions": {
"allowJs": true,
"allowSyntheticDefaultImports": true,
"checkJs": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"sourceMap": true,
"strict": true
}
}
I have this lint on package.json
"lint": "prettier --check --plugin-search-dir=. . && eslint .",
Running npm run lint it cant find any errors even there is clearly an error to a .ts file.
It only can detect errors from .svelte files.
Is there something wrong with my eslint or tsconfig or I miss something?
My bad, it is linting the .ts files but some rules is missing from what i used to be and not showing errors so I add some rules instead of using the default one and now it showing errors.
Here is my new config
module.exports = {
root: true,
parser: '#typescript-eslint/parser',
extends: [
'eslint:recommended',
'plugin:node/recommended',
'plugin:#typescript-eslint/recommended',
'plugin:#typescript-eslint/recommended-requiring-type-checking',
'prettier'
],
plugins: ['node', 'prettier', 'svelte3', '#typescript-eslint'],
ignorePatterns: ['*.cjs', 'svelte.config.js', 'vite.config.js'],
overrides: [
{ files: ['*.svelte'], processor: 'svelte3/svelte3' },
{
files: ['*.ts', '*.js', '*.svelte'],
parser: '#typescript-eslint/parser',
extends: ['plugin:#typescript-eslint/recommended'],
rules: {
'node/no-missing-import': 'off',
'node/no-unpublished-import': 'off'
}
}
],
settings: {
'svelte3/typescript': () => require('typescript')
},
parserOptions: {
sourceType: 'module',
ecmaVersion: 2020,
project: ['./tsconfig.json']
},
env: {
browser: true,
es2017: true,
node: true
},
rules: {
'prettier/prettier': 'error',
'block-scoped-var': 'error',
eqeqeq: 'error',
'no-var': 'error',
'prefer-const': 'error',
'eol-last': 'error',
'prefer-arrow-callback': 'error',
'no-trailing-spaces': 'error',
quotes: ['warn', 'single', { avoidEscape: true }],
'no-restricted-properties': [
'error',
{
object: 'describe',
property: 'only'
},
{
object: 'it',
property: 'only'
}
]
}
};
Related
I have got an indent error with prettier in .vue files.
How can I disable prettier's indent check in .vue files?
This is my eslint config
.eslintrc.js
module.exports = {
root: true,
env: {
node: true,
},
plugins: ['prettier'],
extends: [
'plugin:vue/vue3-essential',
'plugin:prettier/recommended',
'prettier',
'eslint:recommended',
],
parserOptions: {
parser: '#babel/eslint-parser',
},
rules: {
'vue/script-indent': 'off',
'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
},
overrides: [
{
files: ['*.vue'],
rules: {
indent: 'off',
},
},
],
};
This is my prettier config
.prettierrc.js
module.exports = {
trailingComma: 'es5',
tabWidth: 2,
singleQuote: true,
semi: true,
};
I found an answer which works for my config.
Just need to add this code to rules of eslint's config.
'prettier/prettier': [
'error',
{
vueIndentScriptAndStyle: false,
},
],
Trying to get Eslint and Prettier to work on Vue projects. Having a couple of issues though.
For example, I have a rule setup is Eslint to add a space before function parens but it won't format:
Another issue is, I get a error about the tab width in the template section (but I've specified I want 4 spaces in Prettier). Any where would this rule be coming from? I haven't put 2 spaces for template section anywhere in the code:
As an FYI, I'm running Lunvarvim, which (not to blow too much smoke) is a great IDE which I'd like to continue to use if I can resolve this few pain points.
Here is my setup:
Eslint
module.exports = {
env: {
browser: true,
es6: true,
amd: true,
jquery: true,
jest: true,
'jest/globals': true,
},
extends: [
'plugin:jest/recommended',
'plugin:cypress/recommended',
'eslint:recommended',
'plugin:prettier/recommended',
'plugin:vue/recommended',
],
globals: {
Atomics: 'readonly',
SharedArrayBuffer: 'readonly',
$: true,
M: true,
Vue: true,
axios: true,
moment: true,
get: true,
process: true,
global: true,
accounting: true,
Qty: true,
Stripe: true,
Chart: true,
_: true,
},
parserOptions: {
parser: 'babel-eslint',
ecmaVersion: 2018,
sourceType: 'module',
},
plugins: ['vue'],
overrides: [
{
files: ['*.spec.js'],
rules: {
'no-unused-expressions': 0,
},
},
],
rules: {
'object-curly-spacing': ['error', 'always', { objectsInObjects: true }],
'space-in-parens': ['error', 'never'],
'array-bracket-spacing': ['error', 'never'],
'space-before-function-paren': ['error', 'always'],
'vue/component-name-in-template-casing': [
'error',
'kebab-case',
{
registeredComponentsOnly: true,
ignores: [],
},
],
'vue/no-unused-properties': [
'error',
{
groups: ['props', 'data', 'computed', 'methods'],
},
],
indent: ['error', 4],
'linebreak-style': 0,
'global-require': 0,
quotes: ['error', 'single'],
semi: ['error', 'always'],
'no-trailing-spaces': ['warn', { skipBlankLines: true }],
'eol-last': ['warn', 'always'],
'vue/html-self-closing': [
'error',
{
html: {
normal: 'any',
},
},
],
'vue/valid-v-slot': [
'error',
{
allowModifiers: true,
},
],
},
};
Prettier
{
"tabWidth": 4,
"singleQuote": true
}
Try to move the Prettier configuration into your package.json and make sure you have installed eslint-config-prettier
I recently updated to Webpack 5 from Webpack 4, earlier I had a function on window object in index.js such that it looked something like
index.js
window.someFunction = function (...arguments) {
// function body
}
when this index.js gets bundled I can find this same function in common.bundle.js file.
and my index.html looks something like this
index.html
<head>
// rest of the head stuff
<script src="./dist/common.bundle.js"></script>
</head>
<body>
<script type="text/javascript">
someFunction(); // calling someFunction from the window object
// Also tried using window.someFunction() still doesn't work
</script>
</body>
In console I get ReferenceError: someFunction is not defined
and I am not able to print the function defination in chrome console when I type window.someFunction which was working in Webpack 4 as expected.
How do I attach my functions to window object in Webpack 5, and how do I go about accessing it?
webpack.config.js
const path = require("path");
const webpack = require("webpack");
module.exports = (env) => {
return {
mode: "development",
devtool: "source-map",
entry: {
common: "./index.js",
},
output: {
pathinfo: true,
path: path.join(__dirname, "dist"),
filename: "[name].bundle.js",
},
plugins: [
new webpack.DefinePlugin({
"process.env.NODE_ENV": JSON.stringify("development"),
}),
],
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: "babel-loader",
options: {
cacheDirectory: true,
babelrc: false,
presets: [
[
"#babel/env",
{
modules: false,
loose: true,
targets: {
browsers: [">0.25%", "not ie 11", "not op_mini all"],
},
},
],
"#babel/react",
],
plugins: [
[
"#babel/plugin-proposal-class-properties",
{
loose: true,
},
],
["#babel/plugin-transform-runtime"],
],
},
},
},
{
test: /\.css$/,
include: /node_modules/,
use: [{ loader: "style-loader" }, { loader: "css-loader" }],
},
],
},
resolve: {
extensions: [".js", ".jsx"],
modules: [path.resolve(__dirname, "node_modules")],
fallback: {
buffer: false,
fs: false,
tls: false,
net: false,
path: false,
zlib: false,
http: false,
https: false,
stream: false,
crypto: false,
},
},
optimization: {
// namedModules: true,
// namedChunks: true,
minimize: false,
// minimizer: [new TerserPlugin()],
runtimeChunk: "single",
moduleIds: "deterministic",
chunkIds: "deterministic",
nodeEnv: "development",
flagIncludedChunks: false,
concatenateModules: false,
splitChunks: {
hidePathInfo: false,
minSize: 20000,
maxAsyncRequests: Infinity,
maxInitialRequests: Infinity,
chunks: "all",
// maxSize: 0,
minChunks: 1,
automaticNameDelimiter: "~",
cacheGroups: {
commons: {
test: /[\\/]node_modules[\\/]/,
name: "other.bundle",
chunks: "all",
minChunks: 2,
},
defaultVendors: {
test: /[\\/]node_modules[\\/]/,
priority: -10,
},
default: {
minChunks: 2,
priority: -20,
reuseExistingChunk: true,
},
},
},
emitOnErrors: true,
checkWasmTypes: false,
removeAvailableModules: false,
},
performance: {
hints: "warning",
},
stats: {
all: false,
assets: true,
builtAt: true,
cachedAssets: false,
cachedModules: true,
chunkGroups: true,
colors: true,
env: true,
errors: true,
hash: true,
logging: "info",
timings: true,
modules: true,
outputPath: true,
performance: true,
errorsCount: true,
warnings: false,
warningsCount: true,
publicPath: true,
reasons: true,
ids: true,
version: true,
},
cache: {
type: "filesystem",
version: "1.0.0",
store: "pack",
name: "AppBuildCache",
maxMemoryGenerations: 1,
idleTimeout: 60000,
idleTimeoutAfterLargeChanges: 1000,
idleTimeoutForInitialStore: 0,
hashAlgorithm: "md4",
cacheLocation: path.resolve(__dirname, ".cache"),
},
externals: [
{
react: "React",
"react-dom": "ReactDOM",
jquery: "jQuery",
},
],
};
};
Try to add node.global: true to your config:
node: {
global: true
}
DoneDel0's comment was the correct solution for me.
node: {
global: true
}
The reasoning behind this is webpack 5 does no longer include a polyfills for node modules, so you have to manually set each.
https://webpack.js.org/configuration/node/#nodeglobal
However its good to note that the docs does suggest using ProvidePlugin instead of global.
Thank you for the answers, the issue turned out exactly to be due to missing polyfills for node core modules.
In my case the I had to provide polyfill for process using ProvidePlugin.
I did the same by adding below to my config
new webpack.ProvidePlugin({
process: "process/browser",
})
I added
node: {
global: true
}
but still the function is undefined in window object.
I'm using prettier and eslint with typescript.
When I write some code and have to leave an empty function for reasons, Eslint and Prettier struggle adding and removing spaces between the empty function's braces.
Prettier is removing the space while Eslint is adding it.
What is expected:
constructor(
#inject('UsersRepository')
private usersRepository: IUsersRepository,
) {}
const example = ({ variable }) => {
console.log(variable)
};
What I get after saving (Eslint fixing on save):
constructor(
#inject('UsersRepository')
private usersRepository: IUsersRepository,
) { }
const example = ({ variable }) => {
console.log(variable)
};
Se the space between the constructor braces? That gives me a Delete `ยท` eslint(prettier/prettier) error.
When I save the file, or Prettier removes the space... then Eslint adds it again.
How can I solve this?
EDIT: I want to keep the destructuring assignment space (eg ({ variable })) but not on empty braces (eg {})
Below, my .eslintrc.json and prettier.config.js
{
"env": {
"es6": true,
"node": true,
"jest": true
},
"extends": [
"airbnb-base",
"plugin:#typescript-eslint/recommended",
"prettier/#typescript-eslint",
"plugin:prettier/recommended"
],
"globals": {
"Atomics": "readonly",
"SharedArrayBuffer": "readonly"
},
"parser": "#typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 2018,
"sourceType": "module"
},
"plugins": [
"#typescript-eslint",
"prettier"
],
"rules": {
"prettier/prettier": "error",
"class-methods-use-this": "off",
"#typescript-eslint/camelcase": "off",
"no-useless-constructor": "off",
"object-curly-spacing": [
"error",
"always"
],
"#typescript-eslint/no-unused-vars": [
"error",
{
"argsIgnorePattern": "_"
}
],
"#typescript-eslint/interface-name-prefix": [
"error",
{
"prefixWithI": "always"
}
],
"import/extensions": [
"error",
"ignorePackages",
{
"ts": "never"
}
]
},
"settings": {
"import/resolver": {
"typescript": {}
}
}
}
module.exports = {
singleQuote: true,
trailingComma: 'all',
arrowParens: 'avoid',
};
I've had very similar error, but in my case default VSCode TypeScript formatter was messing with braces.
In .vscode/settings.json add:
"javascript.format.insertSpaceAfterOpeningAndBeforeClosingEmptyBraces": false,
"typescript.format.insertSpaceAfterOpeningAndBeforeClosingEmptyBraces": false,
You might also find useful option:
"[typescript]": {
"editor.defaultFormatter": "dbaeumer.vscode-eslint"
}
You should use this in the settings file of vscode.
"prettier.bracketSpacing": false
I had the exact same problem, where prettier stopped working all of a sudden. Auto-format on save(vs code settings) adds a space for braces and linters threw an error on the same. Spend a lot of time debugging this and did the below steps to fix my issue
1: Re-install vscode prettier extension.
Go to vscode => cmd + p and type ext install esbenp.prettier-vscode.
2: My vscode settings.json and prettier.js looks somewhat like this
vscode settings.json
{
"editor.codeActionsOnSave": {
"source.organizeImports": true,
"source.fixAll.eslint": true,
"source.fixAll.tslint": true,
"source.fixAll.stylelint": true
},
"css.validate": false,
"files.autoSave": "off",
"typescript.updateImportsOnFileMove.enabled": "always",
"javascript.updateImportsOnFileMove.enabled": "always",
"editor.wordWrap": "on",
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": false,
"[typescriptreact]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
},
"[javascript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
},
"[typescript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
}
}
Prettier.js
module.exports = {
semi: true,
trailingComma: 'none',
singleQuote: true,
printWidth: 80,
tabWidth: 2,
endOfLine: 'auto',
bracketSpacing: true,
proseWrap: 'always'
};
I has a bad experience with prettier thanks to this post I managed to put together a nice settings config so Im sharing it here and hopefully it will ;help someone top.
"gatsbyhub.commands.build.enableTracing": true,
"gatsbyhub.commands.build.graphqlTracing": true,
"gatsbyhub.commands.develop.changeHost": "localhost",
"window.zoomLevel": 0.6,
"js/ts.implicitProjectConfig.checkJs": true,
"js/ts.implicitProjectConfig.experimentalDecorators": true,
"color-highlight.languages": [
"*",
],
"importCost.javascriptExtensions": [
"\\.jsx?$",
],
"html-css-class-completion.JavaScriptLanguages": [
"javascript",
"typescriptreact"
],
"editor.tabSize": 2,
"editor.renderWhitespace": "none",
"editor.gotoLocation.multipleTypeDefinitions": "goto",
"workbench.editor.enablePreviewFromCodeNavigation": true,
"workbench.editor.enablePreviewFromQuickOpen": true,
"debug.allowBreakpointsEverywhere": true,
"debug.toolBarLocation": "docked",
"blade.format.enable": true,
"color-highlight.matchWords": true,
"path-intellisense.showHiddenFiles": true,
"path-intellisense.mappings": {
"${workspaceFolder}": true,
"${workspaceFolder}/gatsby": true,
},
"editor.formatOnSave": false,
"editor.formatOnType": true,
"workbench.colorCustomizations": {},
"material-icon-theme.activeIconPack": "react_redux",
"editor.semanticHighlighting.enabled": false,
"editor.highlightActiveIndentGuide": false,
"workbench.activityBar.visible": false,
"javascript.format.enable": true,
"javascript.autoClosingTags": true,
"javascript.validate.enable": false,
"javascript.format.semicolons": "insert",
"javascript.suggest.jsdoc.generateReturns": true,
"javascript.format.insertSpaceBeforeFunctionParenthesis": true,
"javascript.preferences.quoteStyle": "double",
"javascript.preferences.useAliasesForRenames": true,
"javascript.suggest.autoImports": true,
"javascript.updateImportsOnFileMove.enabled": "always",
"javascript.format.insertSpaceAfterConstructor": true,
"[javascriptreact]": {
"editor.autoIndent": "advanced",
"editor.autoClosingQuotes": "beforeWhitespace",
"breadcrumbs.showVariables": true,
"diffEditor.ignoreTrimWhitespace": true,
"editor.tabSize": 2,
"editor.useTabStops": true,
"editor.formatOnPaste": false,
"editor.formatOnSaveMode": "file"
},
"javascript.suggest.includeCompletionsForImportStatements": true,
"javascript.format.insertSpaceBeforeAndAfterBinaryOperators": true,
"javascript.format.insertSpaceAfterSemicolonInForStatements": true,
"javascript.format.insertSpaceAfterKeywordsInControlFlowStatements": true,
"javascript.format.insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets": true,
"javascript.format.insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces": true,
"javascript.format.insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces": true,
"typescript.validate.enable": true,
"typescript.preferences.importModuleSpecifier": "non-relative",
"typescript.format.insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets": true,
I haven't started coding in typescript yet but when I do lll male a new config :)
Happy coding
I have preact project, it work fine, but webpack is rebuilding the project when I edit file api/index.php and fail when I didn't save the file in emacs because of .#index.php file.
How can I ignore api directory or only process files from app directory? I need to copy file from root directory so I can't use context because webpack don't see files like index.html or .htaccess that's inside root directory.
Here is my webpack config file:
module.exports = {
entry: {
app: path.resolve('./app') + '/app.jsx'
},
output: {
path: path.resolve('./dist'),
filename: "[name].js"
},
plugins: ([
new webpack.optimize.CommonsChunkPlugin({
name: "vendor",
minChunks: isNodeModule
}),
new webpack.DefinePlugin({
PRODUCTION: ENV === 'production'
}),
new CopyWebpackPlugin([
{from: 'index.html'},
{from: '.htaccess'},
{from: 'config.json'},
{from: 'api', to: 'api'}
])
]).concat(ENV==='production' ? [
new webpack.optimize.UglifyJsPlugin({
output: {
comments: false
},
compress: {
unsafe_comps: true,
properties: true,
keep_fargs: false,
pure_getters: true,
collapse_vars: true,
unsafe: true,
warnings: false,
screw_ie8: true,
sequences: true,
dead_code: true,
drop_debugger: true,
comparisons: true,
conditionals: true,
evaluate: true,
booleans: true,
loops: true,
unused: true,
hoist_funs: true,
if_return: true,
join_vars: true,
cascade: true,
drop_console: true
}
})
] : []),
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015']
}
},
{
test: /\.css$/,
loaders: ['style-loader', 'css-loader']
}
]
},
resolve: {
extensions: ['.jsx', '.js', '.json']
},
devServer: {
historyApiFallback: true,
open: true
}
};
EDIT: it seems that this in not related to dev-server because I can't run webpack too, when I have unsaved file in Emacs.