Nuxt.js: importing `vuex` emits eslint(import/no-extraneous-dependencies) error - eslint

Nuxt.js is shipped with vuex as dependency so importing it doesn't require me to specify it in package.json.
But as vuex is not in package.json, whenever I try to import vuex, eslint emits import/no-extraneous-dependencies error.
In this case, how can I tell eslint to vuex is already included in nuxt module? Or is there any workaround to ignore some modules, ie. vuex, vue...
Below is my current eslint rules.
// .eslintrc.js
const path = require('path')
module.exports = {
env: {
browser: true,
es6: true,
jest: true
},
extends: [
'airbnb-base',
'plugin:vue/recommended',
'plugin:vue-types/strongly-recommended',
'plugin:prettier/recommended',
'#vue/prettier'
],
globals: {
Atomics: 'readonly',
SharedArrayBuffer: 'readonly'
},
parserOptions: {
ecmaVersion: 2018,
sourceType: 'module'
},
plugins: ['prettier', 'vue'],
rules: {
'prettier/prettier': 'error',
'no-console': 0,
'import/prefer-default-export': 0,
'import/no-unresolved': 0,
'vue/max-attributes-per-line': 0
}
}

You can specify vuex as core-modules.
reference
// .eslintrc.js
settings: {
'import/core-modules': ['vue', 'vuex'] // these modules are included in nuxt.js
}

You can ignore these modules as following:
'node/no-extraneous-import': [
'error',
{
allowModules: ['vue', 'vuex']
}
]

Related

How to override the rollup output.format setting in vite?

I'm trying to solve the Vite build error I get:
RollupError: Invalid value "iife" for option "output.format" - UMD and IIFE output formats are not supported for code-splitting builds.
The file name reported with this error points to
my web worker code, so I assumed that this setting belongs to the worker section in vite.config.ts:
import { defineConfig } from "vite";
import preact from "#preact/preset-vite";
import basicSsl from "#vitejs/plugin-basic-ssl";
import { NodeGlobalsPolyfillPlugin } from "#esbuild-plugins/node-globals-polyfill";
import { NodeModulesPolyfillPlugin } from "#esbuild-plugins/node-modules-polyfill";
import rollupNodePolyFill from "rollup-plugin-node-polyfills";
export default defineConfig({
plugins: [
preact(),
basicSsl(),
],
server: {
port: 3001,
https: true,
},
optimizeDeps: {
esbuildOptions: {
// Node.js global to browser globalThis
define: {
global: "globalThis",
},
// Enable esbuild polyfill plugins
plugins: [
NodeGlobalsPolyfillPlugin({
process: true,
buffer: true,
}),
NodeModulesPolyfillPlugin(),
],
},
},
worker: {
rollupOptions: {
output: {
format: "esm",
},
},
},
build: {
rollupOptions: {
plugins: [
// Enable rollup polyfills plugin
// used during production bundling
rollupNodePolyFill(),
],
output: {
format: "esm",
},
},
},
});
Additionally, I set the output format in the build rollup options. However, neither of the two settings are applied and I still get the said error.
What is the correct way to change the rollup output format setting in Vite?
The worker output format must be specified directly in the worker config key, not its rollup options:
import { defineConfig } from "vite";
import preact from "#preact/preset-vite";
import basicSsl from "#vitejs/plugin-basic-ssl";
import { NodeGlobalsPolyfillPlugin } from "#esbuild-plugins/node-globals-polyfill";
import { NodeModulesPolyfillPlugin } from "#esbuild-plugins/node-modules-polyfill";
import rollupNodePolyFill from "rollup-plugin-node-polyfills";
export default defineConfig({
plugins: [
preact(),
basicSsl(),
],
server: {
port: 3001,
https: true,
},
optimizeDeps: {
esbuildOptions: {
// Node.js global to browser globalThis
define: {
global: "globalThis",
},
// Enable esbuild polyfill plugins
plugins: [
NodeGlobalsPolyfillPlugin({
process: true,
buffer: true,
}),
NodeModulesPolyfillPlugin(),
],
},
},
worker: {
format: "es",
},
build: {
rollupOptions: {
plugins: [
// Enable rollup polyfills plugin
// used during production bundling
rollupNodePolyFill(),
],
output: {
format: "esm",
},
},
},
});

How to transpile npm module with "optional chaining" code to earlier version of node?

Currently I am running node v16.13.1 and I wrote small npm package I would like to publish to npm and then install globally and run as executable.
Application works fine when built with current version but because I am using "optional chaining" (object?.something) it does not work with node 12.
I do not want to change code, but I would like to transpile it so it runs it in all node versions between 12 and 16+.
My webpack look like this:
const path = require("path");
const webpack = require("webpack");
module.exports = (env, argv) => {
console.log('Log::', env, argv);
const config = {
entry: './src/index.js',
devtool: (argv.mode === 'development') ? 'cheap-module-source-map' : undefined,
output: {
path: path.resolve(__dirname, './dist'),
filename: 'bundle.js',
},
experiments: {
outputModule: true,
},
plugins: [
//empty pluggins array
new webpack.BannerPlugin({ banner: "#!/usr/bin/env node", raw: true }),
],
module: {
// https://webpack.js.org/loaders/babel-loader/#root
rules: [
{
test: /.m?js$/,
loader: 'babel-loader',
exclude: /node_modules/,
}
],
},
resolve: {
fallback: {
"fs": false,
"path": false,
"os": false,
assert: require.resolve('assert'),
path: require.resolve('path-browserify'),
util: require.resolve('util'),
},
},
target: "node12.22"
};
console.log('Log::', config);
return config;
}
and this is .babelrc
{
"presets": [
[
"#babel/preset-env",
{
"targets": {
"esmodules": true
}
}
]
]
}
running npm build with target: "node" gives following error:
Error: For the selected environment is no default ESM chunk format available:
ESM exports can be chosen when 'import()' is available.
running it with target: "node12.22" does not give any errors but when I try to run I get:
SyntaxError: Cannot use import statement outside a module
←[90m at Object.compileFunction (node:vm:352:18)←[39m
If I remove target:"node" all together I am getting following error when run:
TypeError: s.existsSync is not a function
If I run it without fallback: { "fs": false then I get compile errors:
Module not found: Error: Can't resolve 'fs' in
Try adding the following to your Webpack config to have the optimizer output code that's compatible with ECMA 6, which does not include optional chaining:
optimization: {
minimizer: [
new TerserPlugin({
terserOptions: {
ecma: 6,
mangle: false,
// compress: false, // NOTE: Not certain you can just pass false here, but I think probably
},
}),
],
},
And be sure to install the TerserJS Plugin and require it in your config, const TerserPlugin = require('terser-webpack-plugin');

Jest Modules Do Not Import Correctly

Dealing with modules in Jest has been a nightmare.
Aside from all the other issues encountered, there is one I have yet to be able to work through.
It looks as certain imports are getting imported incorrectly.
Consider the following trivial example
import * as jp from 'jsonpath'
console.log('paths: ' + jp.paths)
when running my app code in the browser, this prints
paths: function(obj, string, count) {
assert.ok(obj instanceof Object, "obj needs to be an object");
assert.ok(string, "we need a path");
var results = this.nodes(obj, string, count)
.map(function(r) { return r.path });
return results;
}
when running the same code from a Jest test, I get:
console.log
paths: undefined
upon debugging the test and inspecting the jp object in the debugger, I see:
Needless to say this does not look correct. When running console.log(jp) from the browser, I see
It seems like Jest is screwing up the module prototype somehow.
My jest.config.js:
const esModules = ['quasar/lang', 'lodash-es'].join('|');
/* eslint-env node */
module.exports = {
globals: {
__DEV__: true,
// TODO: Remove if resolved natively https://github.com/vuejs/vue-jest/issues/175
'vue-jest': {
pug: { doctype: 'html' },
},
},
setupFilesAfterEnv: ['<rootDir>/test/jest/jest.setup.ts'],
// noStackTrace: true,
// bail: true,
// cache: false,
// verbose: true,
// watch: true,
collectCoverage: false,
coverageDirectory: '<rootDir>/test/jest/coverage',
collectCoverageFrom: [
'<rootDir>/src/**/*.vue',
'<rootDir>/src/**/*.js',
'<rootDir>/src/**/*.ts',
'<rootDir>/src/**/*.jsx',
'<rootDir>/src/**/*.tsx',
],
coveragePathIgnorePatterns: ['/node_modules/', '.d.ts$'],
coverageThreshold: {
global: {
// branches: 50,
// functions: 50,
// lines: 50,
// statements: 50
},
},
testMatch: [
// Matches tests in any subfolder of 'src' or into 'test/jest/__tests__'
// Matches all files with extension 'js', 'jsx', 'ts' and 'tsx'
'<rootDir>/test/jest/__tests__/**/*.(spec|test).+(ts|js)?(x)',
'<rootDir>/src/**/*.jest.(spec|test).+(ts|js)?(x)',
],
// Extension-less imports of components are resolved to .ts files by TS,
// grating correct type-checking in test files.
// Being 'vue' the first moduleFileExtension option, the very same imports
// will be resolved to .vue files by Jest, if both .vue and .ts files are
// in the same folder.
// This guarantee a great dev experience both for testing and type-checking.
// See https://github.com/vuejs/vue-jest/issues/188#issuecomment-620750728
moduleFileExtensions: ['vue', 'js', 'jsx', 'json', 'ts', 'tsx'],
moduleNameMapper: {
'^quasar$': 'quasar/dist/quasar.common.js',
'^~/(.*)$': '<rootDir>/$1',
'^src/(.*)$': '<rootDir>/src/$1',
'^app/(.*)$': '<rootDir>/$1',
'^components/(.*)$': '<rootDir>/src/components/$1',
'^layouts/(.*)$': '<rootDir>/src/layouts/$1',
'^pages/(.*)$': '<rootDir>/src/pages/$1',
'^assets/(.*)$': '<rootDir>/src/assets/$1',
'^boot/(.*)$': '<rootDir>/src/boot/$1',
'.*css$': '#quasar/quasar-app-extension-testing-unit-jest/stub.css',
},
transform: {
// See https://jestjs.io/docs/en/configuration.html#transformignorepatterns-array-string
[`^(${esModules}).+\\.js$`]: 'babel-jest',
'^.+\\.(ts|js|html)$': 'ts-jest',
// vue-jest uses find-babel-file, which searches by this order:
// (async) .babelrc, .babelrc.js, package.json, babel.config.js
// (sync) .babelrc, .babelrc.js, babel.config.js, package.json
// https://github.com/tleunen/find-babel-config/issues/33
'.*\\.vue$': 'vue-jest',
'.+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$':
'jest-transform-stub',
},
transformIgnorePatterns: [`node_modules/(?!(${esModules}))`],
snapshotSerializers: ['<rootDir>/node_modules/jest-serializer-vue'],
testEnvironment: 'jsdom'
};
Any suggestions on how to resolve this?
Thank you.

How do I disable There should be no space after '{'.eslintobject-curly-spacing in .eslintrc.js

I am using prettier and I initialized my project with firebase init with the eslint option. But when I save my files, the prettier extension adds spacing in the object curly braces like this:
export { basicHTTP } from './http';
which eslint gives me an error: is there anyway to disable this?
This is my .eslintrc.js file that comes with firebase init:
module.exports = {
root: true,
env: {
es6: true,
node: true,
},
extends: [
'eslint:recommended',
'plugin:import/errors',
'plugin:import/warnings',
'plugin:import/typescript',
'google',
],
parser: '#typescript-eslint/parser',
parserOptions: {
project: ['tsconfig.json', 'tsconfig.dev.json'],
tsconfigRootDir: __dirname,
sourceType: 'module',
},
ignorePatterns: [
'/lib/**/*', // Ignore built files.
],
plugins: ['#typescript-eslint', 'import'],
rules: {
quotes: ['error'],
},
};
Modify your rules to look like this:
rules: {
'object-curly-spacing': ['error', 'always'],
'quotes': ['error'],
},
After this change you probably have to fix all js files to use same syntax, but that's just a good practice.
See: https://eslint.org/docs/rules/quotes
You can disable adding space in vscode when formatting code.
Open settings.json and add the following line
"typescript.format.insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces": false,
"javascript.format.insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces": false,
This will fix it on both javascript and typescript

How do I use Node Typescript types with Karma-Webpack

I have Webpack configured for transpiling my TS files in Karma. I have also included Node and CoreJS types. However, when I try to run my tests I get...
ERROR in ./test/karma/test.bundle.ts
(18,30): error TS2339: Property 'context' does not exist on type 'NodeRequire'.
I tried adding webpack-env using npm install --save-dev #types/webpack-env, but that gives me even more errors.
ERROR in /.../node_modules/#types/webpack-env/index.d.ts
(183,13): error TS2403: Subsequent variable declarations must have the same type. Variable 'require' must be of type 'NodeRequire', but here has type 'RequireFunction'.
ERROR in /.../node_modules/#types/webpack-env/index.d.ts
(232,13): error TS2403: Subsequent variable declarations must have the same type. Variable 'module' must be of type 'NodeModule', but here has type 'Module'.
ERROR in ./test/karma/test.bundle.ts
(18,30): error TS2339: Property 'context' does not exist on type 'NodeRequire'.
My Karma config looks like this...
var webpack = require("webpack");
module.exports = function(config) {
var webpackConfig = require("../../webpack.config");
// TODO: Can we get rid on this?
// We need to remove entry points and plugins
webpackConfig.plugins = [
// IMPORTANT!!!! Without this source maps fail to show up.
new webpack.SourceMapDevToolPlugin({
filename: null, // if no value is provided the sourcemap is inlined
test: /\.(ts|js)($|\?)/i // process .js and .ts files only
})
];
//This is used to remap can access (Based on https://github.com/sshev/karma-remap-coverage)
webpackConfig.ts = {
compilerOptions: {
inlineSourceMap: true,
sourceMap: false
}
};
webpackConfig.module.postLoaders = [
{
test: /^((?!\.spec\.ts).)*.ts$/,
exclude: /(node_modules|bower_components)/,
loader: 'istanbul-instrumenter'
}
];
webpackConfig.entry = {};
var configuration = {
autoWatch: true,
basePath: "",
browsers: ["Chrome"],
colors: true,
concurrency: Infinity,
coverageReporter: {
type: 'in-memory'
},
exclude: [
"node_modules"
],
files: [
{ pattern: "./test.bundle.ts", watched: true },
],
frameworks: ["jasmine"],
htmlReporter: {
outputFile: "../../reports/units.html"
},
logLevel: config.LOG_INFO,
port: 9876,
preprocessors: {
"./test.bundle.ts": ["webpack", "sourcemap" ],
},
remapCoverageReporter: {
"text-summary": null,
html: "./reports/coverage/html"
},
reporters: ["progress", "coverage", "remap-coverage", "html"],
singleRun: false,
webpack: webpackConfig,
webpackMiddleware: { stats: "errors-only"}
};
config.set(configuration);
};
Versions
webpack 1.14.0, node v6.9.2, Typescript 2.1.4

Resources