Different prettier's check results - github-actions

I have script "lint:prettier": "prettier --check --ignore-unknown \"**/*.*\"",. Then I run it, I get successful result but in github actions I getting erorrs
Github action lint-action workflow:
- name: Run linters
run: npm run lint:prettier
.prettierrc.js:
module.exports = {
semi: true,
trailingComma: 'all',
singleQuote: true,
printWidth: 120,
tabWidth: 2,
endOfLine: 'auto',
};
.eslintrc.js:
module.exports = {
parser: '#typescript-eslint/parser', // Specifies the ESLint parser
extends: [
'plugin:react/recommended', // Uses the recommended rules from #eslint-plugin-react
'plugin:#typescript-eslint/recommended', // Uses the recommended rules from the #typescript-eslint/eslint-plugin
'plugin:prettier/recommended', // Enables eslint-plugin-prettier and displays prettier errors as ESLint errors. Make sure this is always the last configuration in the extends array.
],
parserOptions: {
ecmaVersion: 2018, // Allows for the parsing of modern ECMAScript features
sourceType: 'module', // Allows for the use of imports
ecmaFeatures: {
jsx: true, // Allows for the parsing of JSX
},
},
rules: {
'react/prop-types': [2, { ignore: ['children'] }],
},
settings: {
react: {
version: 'detect', // Tells eslint-plugin-react to automatically detect the version of React to use
},
},
};
How can I fix it?

Related

Webpack Pug/HTML loaders converts capital letters to lowercase on production mode

I am using both vue single-file components and separating of markup and logic to .pug and .ts files respectively. If you interesting why I don't unify is please see the comments section.
Problem
import template from "#UI_Framework/Components/Controls/InputFields/InputField.vue.pug";
import { Component, Vue } from "vue-property-decorator";
console.log(template);
#Component({
template,
components: {
CompoundControlBase
}
})
export default class InputField extends Vue {
// ...
}
In development building mode exported template is correct (I beautified it for readability):
<CompoundControlBase
:required="required"
:displayInputIsRequiredBadge="displayInputIsRequiredBadge"
<TextareaAutosize
v-if="multiline"
:value="value"
/><TextareaAutosize>
</CompoundControlBase>
In production mode, my markup has been lowercased. So, the console.log(template) outputs:
<compoundcontrolbase
:required=required
:displayinputisrequiredbadge=displayInputIsRequiredBadge
<textareaautosize
v-if=multiline
:value=value
></textareaautosize>
</compoundcontrolbase>
Off course, I got broken view.
Webpack config
const WebpackConfig = {
// ...
optimization: {
noEmitOnErrors: !isDevelopmentBuildingMode,
minimize: !isDevelopmentBuildingMode
},
module: {
rules: [
{
test: /\.vue$/u,
loader: "vue-loader"
},
{
test: /\.pug$/u,
oneOf: [
// for ".vue" files
{
resourceQuery: /^\?vue/u,
use: [ "pug-plain-loader" ]
},
// for ".pug" files
{
use: [ "html-loader", "pug-html-loader" ]
}
]
},
// ...
]
}
}
Comments
To be honest, I don't know why we need ? in resourceQuery: /^\?vue/u, (explanations are welcome).
However, in development building mode above config works property for both xxxx.vue and xxxx.vue.pug files.
I am using below files naming convention:
xxx.pug: pug file which will not be used as vue component template.
xxx.vue.pug: pug file which will be used as vue component template.
xxx.vue: single-file vue component.
xxx.vue.ts: the logic of vue component. Required exported template from xxx.vue.pug as in InputField case.
Why I need xxx.vue.ts? Because of this:
declare module "*.vue" {
import Vue from "vue";
export default Vue;
}
Neither public methods/fields nor non-default methods are visible for TypeScrpt xxx.vue files. For the common (non-applied) components, I can't accept it.
Repro
🌎 GitHub
Step 1: Install dependencies
npm i
Step 2: Let's check the development building first
npm run DevelopmentBuild
In line 156 of DevelopmentBuild\EntryPoint.js, you can check that below pug template:
Alpha
Bravo OK
has been compiled properly:
Step 3: Problem on production build
npm run ProuductionBuild
You can find the lowercased tags in the column 13:
You can also open index.html in your browser and check the console.log() output with compiled TestComponent.
The problem is the "html-loader". It has the option minimize set to true in production mode (html-loader/#minimize).
I had a similar problem in angular and had to unset some options like (see for reference html-minifier-terser#options-quick-reference).
// webpack.config.js
{
test: /\.pug$/u,
oneOf: [
// for ".vue" files
{
resourceQuery: /^\?vue/u,
use: [ "pug-plain-loader" ]
},
// for ".pug" files
{
use: [ "html-loader", "pug-html-loader" ]
}
],
options: {
minimize: { // <----
caseSensitive: false // <----
} // <----
}
},

Karma runner with Coverage - preprocessor not working on Javascript ES6 code

I just recently started working with Karma runner in our UI5 app. Wrote some unit tests, ran them... all worked fine so far.
However, now I´ve decided to track the code coverage. To measure it, I need to run preprocessor on my source code. And this is where I stumbled upon a problems - I am currently trying to make it work and both have some kind of problems
npm package karma-coverage as a preprocessor - after installing it, I set it up in karma.conf.js like this
preprocessors: {
"webapp/helpers/**/*.js": ['coverage'],
"webapp/controller/**/*.js": ['coverage'],
},
This works fine on helpers folder since it contains only one file with simple javascript. However, when it tries to process controller folder which has files with some ES6 code, each file fails with errors such as these
Unexpected token function
Unexpected token ...
As a second option, I tried to use karma-babel-preprocessor which should be able to handle also ES6 code. This is how my karma.conf.js file looks like
preprocessors: {
"webapp/helpers//.js": ['babel'],
"webapp/controller//.js": ['babel'],
},
babelPreprocessor: {
options: {
presets: ['#babel/preset-env'],
sourceMap: 'inline'
} ,
filename: function (file) {
return file.originalPath.replace(/\.js$/, '.es5.js');
},
sourceFileName: function (file) {
return file.originalPath;
}
},
However, this one is not even able to find the js file (even though the address is the same as in the case of coverage preprocesor) and returns this error.
Error: failed to load 'sbn/portal/helpers/formatter.js' from .webapp/helpers/formatter.js: 404 - Not Found
at https://openui5.hana.ondemand.com/resources/sap-ui-core.js:86:37
Does someone have an idea how I can get the coverage data while using these packages or any other ones? There is a lots of conflicting info on the web, most of it several years old while various karma-related npm packages keep popping up each month so I am really not sure which one would be the best to use.
Thank a lot
We had the same problem and we managed to fix it integrating babel in a ui5-building-tool step.
This is how our package.json looks like:
{
"devDependencies": {
"babel-core": "6.26.3",
"babel-plugin-fast-async": "6.1.2",
"babel-preset-env": "1.7.0",
"karma": "^4.0.1",
"karma-chrome-launcher": "^2.2.0",
"karma-coverage": "^1.1.2",
"karma-ui5": "^1.0.0",
"karma-junit-reporter": "1.2.0",
"rimraf": "^2.6.2",
"start-server-and-test": "^1.4.1",
"#ui5/cli": "^1.5.5",
"#ui5/logger": "^1.0.0",
}
"scripts": {
"start": "ui5 serve -o index.html",
"lint": "eslint webapp",
"test": "karma start",
"build": "npm run test && rimraf dist && ui5 build --a --include-task=generateManifestBundle"
}
}
This is how the ui5.yaml is looking like
specVersion: '1.0'
metadata:
name: app-name
type: application
builder:
customTasks:
- name: transpile
afterTask: replaceVersion
---
specVersion: "1.0"
kind: extension
type: task
metadata:
name: transpile
task:
path: lib/transpile.js
This is how the transpile.js is looking like:
Be aware that this file should be placed in the root-dir/lib folder. root-dir is the folder where ui5.yaml is residing.
const path = require("path");
const babel = require("babel-core");
const log = require("#ui5/logger").getLogger("builder:customtask:transpile");
/**
* Task to transpiles ES6 code into ES5 code.
*
* #param {Object} parameters Parameters
* #param {DuplexCollection} parameters.workspace DuplexCollection to read and write files
* #param {AbstractReader} parameters.dependencies Reader or Collection to read dependency files
* #param {Object} parameters.options Options
* #param {string} parameters.options.projectName Project name
* #param {string} [parameters.options.configuration] Task configuration if given in ui5.yaml
* #returns {Promise<undefined>} Promise resolving with undefined once data has been written
*/
module.exports = function ({
workspace,
dependencies,
options
}) {
return workspace.byGlob("/**/*.js").then((resources) => {
return Promise.all(resources.map((resource) => {
return resource.getString().then((value) => {
log.info("Transpiling file " + resource.getPath());
return babel.transform(value, {
sourceMap: false,
presets: [
[
"env",
{
exclude: ["babel-plugin-transform-async-to-generator", "babel-plugin-transform-regenerator"]
}
]
],
plugins: [
[
"fast-async",
{
spec: true,
compiler: {
"promises": true,
"generators": false
}
}
]
]
});
}).then((result) => {
resource.setString(result.code);
workspace.write(resource);
});
}));
});
};
And finally this is the karma.conf.js setup:
module.exports = function (config) {
var ui5ResourcePath = "https:" + "//sapui5.hana.ondemand.com/resources/";
config.set({
// the time that karma waits for a response form the browser before closing it
browserNoActivityTimeout: 100000,
frameworks: ["ui5"],
// list of files / patterns to exclude
exclude: [],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
"root_to_to_files/**/*.js": ["coverage"],
},
// test results reporter to use
// possible values: "dots", "progress"
// available reporters: https://npmjs.org/browse/keyword/karma-reportery
reporters: ["progress", "coverage"],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: false,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ["Chrome"],
// Continuous Integration modey
// if true, Karma captures browsers, runs the tests and exits
singleRun: true,
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity,
// generates the coverage report
coverageReporter: {
type: "lcov", // the type of the coverage report
dir: "reports", // the path to the output directory where the coverage report is saved
subdir: "./coverage" // the name of the subdirectory in which the coverage report is saved
},
browserConsoleLogOptions: {
level: "error"
}
});
};
In our project this setup works fine with ES6 code and prints the coverage.
Hope this you help you. Please give me a feedback how this works.

Rest-spread not being transpiled when targeting edge with NextJS

I am trying to transpile my ES6 code via Babel, I am using the next/babel preset along with preset-env and I'm using the browsers: defaults target.
The NextJS preset comes with #babel/plugin-proposal-object-rest-spread in its plugins array, I'm wondering why I am getting an error when testing on edge that says Expected identifier, string or number, and when looking in the compiled JS for the error, I see it happens when {...t} occurs.
Here is my babel.config.js:
module.exports = {
presets: [
[
'next/babel',
{
'#babel/preset-env': {
targets: {
browsers: 'defaults'
},
useBuiltIns: 'usage'
}
}
]
],
plugins: [
'#babel/plugin-proposal-optional-chaining',
'#babel/plugin-proposal-nullish-coalescing-operator',
['styled-components', { ssr: true, displayName: true, preprocess: false }],
[
'module-resolver',
{
root: ['.', './src']
}
]
],
env: {
development: {
compact: false
}
}
};
Any help on this would be greatly appreciated!
In the end my problem was related to a package that was not being transpiled by babel. My solution was to use NextJS' next-transpile-modules plugin to get babel to transpile the package code into something that would work on the browsers I need.
Here's an example of my NextJS webpack config with the package I need transpiled specified:
const withTM = require('next-transpile-modules');
module.exports = withTM({
transpileModules: ['swipe-listener']
});
SCRIPT1028: Expected identifier, string or number error can occur in 2 situations.
(1) This error get trigger if you are using trailing comma after your last property in a JavaScript object.
Example:
var message = {
title: 'Login Unsuccessful',
};
(2) This error get trigger if you are using a JavaScript reserved word as a property name.
Example:
var message = {
class: 'error'
};
solution is to pass the class property value as a string. You will need to use bracket notation, however, to call the property in your script.
Reference:
ERROR : SCRIPT1028: Expected identifier, string or number

Using a simple vue.js/webpack setup, how does one configure the dev server to proxy everything EXCEPT a few .js and .vue files?

So some quick background on the site's current setup:
My company's site currently runs off of a CMS. All pages are generated and routed via the CMS, so there are no .html files anywhere. It's all generated via razor (.cshtml), the CMS as a backend/data-store, and routing is handled through the CMS.
If it were up to me I'd rewrite the entire thing, but I don't have that luxury. I'm doing my best to rewrite the site with a Vue.js + webpack front-end wherever possible and slowly rebuild this site over time using more modern techniques than are currently implemented.
However, I'm running into a problem setting up Webpack's dev server with our current configuration.
I think I know what the problem is, however I'm having difficulty understanding the http-proxy-middleware's configuration settings.
I believe the way I currently have everything setup, the dev server is proxying everything - therefore not picking up any changes I make to the .vue/.js files I modify (via hot reloading).
Unfortunately I HAVE to proxy the majority of the site (pages [.cshtml files], legacy scripts, various APIs, etc.), however I don't want to proxy MY .js files and .vue files (you can assume anything of mine is in /dist/ or /src/. Everything else is the old site and must be proxied via "my.server".
Additionally, I set this up as a quick test via vue cli's webpack-simple configuation - however I can also set it up via the non-simple variation if needed. I started with "-simple" to "K.I.S.S" (Keep it simple stupid) and slowly layer on the complexity as desired.
Here's my webpack.config.js file as it currently stands:
var path = require('path')
var webpack = require('webpack')
module.exports = {
entry: './src/main.js',
output: {
path: path.resolve(__dirname, './dist'),
publicPath: '/dist/',
filename: 'build.js'
},
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
// Since sass-loader (weirdly) has SCSS as its default parse mode, we map
// the "scss" and "sass" values for the lang attribute to the right configs here.
// other preprocessors should work out of the box, no loader config like this nessessary.
'scss': 'vue-style-loader!css-loader!sass-loader',
'sass': 'vue-style-loader!css-loader!sass-loader?indentedSyntax'
}
// other vue-loader options go here
}
},
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.(png|jpg|gif|svg)$/,
loader: 'file-loader',
options: {
name: '[name].[ext]?[hash]'
}
}
]
},
resolve: {
alias: {
'vue$': 'vue/dist/vue.common.js'
}
},
devServer: {
historyApiFallback: true,
noInfo: true,
proxy: {
'/': {
target: {
"host": "my.server",
"protocol": 'http:',
"port": 80
},
ignorePath: false,
changeOrigin: true,
secure: false
}
}
},
performance: {
hints: false
},
devtool: '#eval-source-map'
}
if (process.env.NODE_ENV === 'production') {
module.exports.devtool = '#source-map'
// http://vue-loader.vuejs.org/en/workflow/production.html
module.exports.plugins = (module.exports.plugins || []).concat([
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"'
}
}),
new webpack.optimize.UglifyJsPlugin({
sourceMap: true,
compress: {
warnings: false
}
}),
new webpack.LoaderOptionsPlugin({
minimize: true
})
])
}
As far as I can tell the issue lies in the proxy:
proxy: {
'/': {
target: {
"host": "my.server",
"protocol": 'http:',
"port": 80
},
ignorePath: false,
changeOrigin: true,
secure: false
}
}
Obviously the '/' is targeting everything, but while I can find plenty of examples of how to proxy specific sections and not anything else, I need the opposite. I need to proxy everything EXCEPT /dist/ and /src/. Any help would be greatly appreciated - and who knows, I may be way off here and this isn't even my problem.
Ultimately, though, the issue is when I run the dev server, if I setup proxying, everything on the site runs except my .vue files - if I don't proxy the server, nothing runs except my .vue files. Therefore it stands to reason the proxying simply needs to be applied to the legacy portions only and not the vue portions - but if I'm way off base, that's the ultimate issue and I'm open to solutions of any kind.
Thanks in advance for any insight anyone can provide!
webpack-dev-server allows you to configure multiple proxy configurations.
Using this style of configuring the proxy will give access to more advanced context filtering via the context option.
You can use globbing:
proxy: [{
context: ['**', '!/src/**', '!/dist/**', '!**/*.vue'],
target: {
"host": "my.server",
"protocol": 'http:',
"port": 80
},
ignorePath: false,
changeOrigin: true,
secure: false
}]
Or you can write your own filtering logic.
proxy: [{
context: function(pathname, req) {
// exclude /src/ and /dist/
return !pathname.match("^/(src|dist)/");
},
target: {
"host": "my.server",
"protocol": 'http:',
"port": 80
},
ignorePath: false,
changeOrigin: true,
secure: false
}]
sources:
https://github.com/chimurai/http-proxy-middleware#context-matching
https://github.com/webpack/webpack-dev-server/issues/562#issuecomment-241736936
https://github.com/webpack/webpack-dev-server/blob/ee9181ca3ae40d35f8e419123423df51f2f40700/examples/proxy-hot-reload/webpack.config.js#L4

Electron & ES6 how to implement require remote/ipc when using gulp and ES6 modules

i am using ES6 js files that are then compiled by gulp (browserify/babel), example of a ES6 file is:
I have a normal App.js that is used to set up the main window etc.. Then the html pages will use a main.min.js file that is basically made up with all my ES6 classes compiled into one file:
loader.es6 file
import Main from './pages/Main.es6'
new Main()
Main.es6 file
import Vue from 'vue';
export default class Main extends Vue{
constructor() {...}
.....
}
When compiled and run this all works fine and all is good... But as i thought if i want to implement the 'IPC', 'Remote' modules, i am having issues with compiling as they cannot find those modules, either through the require() or import.. methods within my classes.
so doing the following fails:
import Remote from 'remote'
import Main from './pages/Main.es6'
new Main()
or
var Remote = require('remote')
import Main from './pages/Main.es6'
new Main()
Is this possible to do or achieve, or nope needs more thought and going back to normal js please.
Any ideas / advice would be great thanks
EDIT: add the error details
An example file in question Main.es6
see the added var var Remote = require('remote')at the top this causes the following error.
even using import Remote from 'remote'
{ [Error: Cannot find module 'remote' from '/Volumes/DAVIES/ElectronApps/electron-vuejs-starter/resources/js/pages']
stream:
{ _readableState:
{ highWaterMark: 16,
buffer: [],
length: 0,
pipes: [Object],
pipesCount: 1,
flowing: true,
ended: false,
endEmitted: false,
reading: true,
sync: false,
needReadable: true,
emittedReadable: false,
readableListening: false,
objectMode: true,
defaultEncoding: 'utf8',
ranOut: false,
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null,
resumeScheduled: false },
readable: true,
domain: null,
_events:
{ end: [Object],
error: [Object],
data: [Function: ondata],
_mutate: [Object] },
_maxListeners: undefined,
_writableState:
{ highWaterMark: 16,
objectMode: true,
needDrain: false,
ending: true,
ended: true,
finished: true,
decodeStrings: true,
defaultEncoding: 'utf8',
length: 0,
writing: false,
corked: 0,
sync: false,
bufferProcessing: false,
onwrite: [Function],
writecb: null,
writelen: 0,
buffer: [],
pendingcb: 0,
prefinished: true,
errorEmitted: false },
writable: true,
allowHalfOpen: true,
_options: { objectMode: true },
_wrapOptions: { objectMode: true },
_streams: [ [Object] ],
length: 1,
label: 'deps' } }
In my case, I'm using browserify with babelify, if I tried:
var remote = require('remote')
I would got error:
Error: Cannot find module 'remote' from xxx
But if I tried
var remote = window.require('remote')
It works.
import remote from 'remote' doesn't work, seems like browserify can't find those native modules not defined in package.json.
Well been playing and I have managed to get this to work in a way:
Basically i set the remote and ipc modules within the html page, then pass in those, into my class for that page.
main.html
<script>
var remote = require('remote');
var ipc = require('ipc');
new Main(ipc);
</script>
Main.js - Class File
export default class Main extends Vue{
constructor(ipc) {
....
ipc.send('listener here','message here');
.....
The files can be viewed within this Branch:
Honestly, the easiest way to solve this is to not minify your binaries or use browserify. Electron already has require in the global scope - all you need to do is run your files through Babel to ES6 => ES5 compile them (electron-compile makes this trivially easy too). Your import statement will get translated to a require, which Electron will automatically handle out of the box.
In general, a lot of optimization strategies that you're used to on the web like minification or concatenation are unnecessary or don't make sense in Electron, you can mostly just not do them!