Related
I want to make a eslint config works globally, so that I don't need to init it in each project.
then I installed eslint and some config extension globally.
npm install -g eslint eslint-config-airbnb eslint-plugin-import eslint-plugin-jsx-a11y eslint-plugin-react eslint-plugin-react-hooks
And this is my eslint config file ~/.eslintrc.json
{
"env": {
"browser": true,
"es6": true,
"node": true
},
"extends": [
"airbnb-base"
],
"rules": {
}
}
But I got error when I lint my js file
ESLint couldn't find the config "airbnb-base" to extend from. Please check that the name of the config is correct.
The config "airbnb-base" was referenced from the config file in "/home/molly/.eslintrc.json".
This is my global installed packages, airbnb is there.
Did I miss something ? I don't want to install eslint-plugin** in each of project
Probably a bit late for you but I don't think you can install eslint plugins globally.
The way around that worked for me is to create a directory where all my projects go and inside that directory create a package.json (npm init -y) and install all the plugins in that directory npm i -D eslint-config-airbnb eslint-plugin-import eslint-plugin-jsx-a11y eslint-plugin-react eslint-plugin-react-hooks
Bring your global .eslintrc file in that directory which will act like a root eslint config for all your projects that's inside that directory now.
Essentially, your directory tree should like the following now:
projects/
package.json
.eslintrc
node_modules/
...
my_cool_project/
...
my_cool_project2/
...
...
For a library written in ES6/7, I want to compile (to ES5) the library to a dist/ folder. I also want to run the tests (written in ES6/7) for this lib.
My dev dependencies look like this (package.json):
"devDependencies": {
"#babel/cli": "^7.4.4",
"#babel/core": "^7.4.5",
"#babel/preset-env": "^7.4.5",
"#babel/register": "^7.4.4",
"chai": "^4.2.0",
"mocha": "^6.1.4",
"sinon": "^7.3.2"
},
My build and test scripts looks like this (package.json):
"scripts": {
"test": "mocha --require #babel/register",
"build": "babel src -d dist --presets=#babel/preset-env"
},
Running npm run build works well. The dist/ folder gets populated with transpiled files.
Running npm run test does not seem to work - this is my problem.
> mocha --require #babel/register
/Users/dro/Repos/lib/node_modules/yargs/yargs.js:1163
else throw err
^
ReferenceError: regeneratorRuntime is not defined
Initially I got an import error, which was resolved by adding .babelrc file.
Below is my .babelrc file content.
{
"presets": ["#babel/preset-env"]
}
I was reading about regeneratorRuntime and it got me to this link about babel-polyfill where they explain I shouldn't need that polyfill.
This will emulate a full ES2015+ environment (no < Stage 4 proposals) and is intended to be used in an application rather than a library/tool.
What is needed to set this up properly?
I am not using webpack.
Testing in ES6 with Mocha and Babel 7. Look here: https://dev.to/bnorbertjs/my-nodejs-setup-mocha--chai-babel7-es6-43ei or http://jamesknelson.com/testing-in-es6-with-mocha-and-babel-6/
npm install --save #babel/runtime
npm install --save-dev #babel/plugin-transform-runtime
And, in .babelrc, add:
{
"presets": ["#babel/preset-env"],
"plugins": [
["#babel/transform-runtime"]
]
}
Look at the project documentation:
npm install --save-dev babel-register
In your package.json file make the following changes:
{
"scripts": {
"test": "mocha --require babel-register"
}
}
Some features will require a polyfill:
npm install --save-dev babel-polyfill
{
"scripts": {
"test": "mocha --require babel-polyfill --require babel-register"
}
}
Below steps are for applying Babel transformations & core-js polyfills for your tests file:
💡 All transformations are only done per current environment, so only what is needed to be transpiled/polyfilled, will be. Target environments may be defined from a .browserslist file or as a property in package.json file. (read more here)
Step 1: Install packages:
#babel/core (read why)
#babel/preset-env (read why)
#babel/register (read why)
core-js (read why)
Note that #babel/polyfill exists and uses core-js under the hood. However, it was deprecated in favor of using core-js directly.
Step 2: Create a Babel configuration file babel.config.js
(used to be .babelrc.js or a .json file).
Create this file at the root-level of your code.
The most basic configuration (for just testing and not bundling) would look like this:
module.exports = {
presets: [
['#babel/preset-env', {
"corejs": "3.26",
"useBuiltIns": "usage"
}],
};
corejs - This is the polyfills library and should be specified with the minor version, otherwise x.0 will be used.
It is needed when testing code on rather "old" Node versions, which do not support all of the language methods. This ofc depends on your own usage of such javascript methods. (for example String.prototype.replaceAll).
useBuiltIns - must be set in order for the corejs polyfills to be applied. Read about it in the official docs.
By default, #babel/preset-env will compile your code for the current environment, but you can specify a different environment by setting the "targets" option in the configuration.
Ofc, you can add more presets like #babel/preset-react for example, if your code it written in React, or any other plugins which are specifically needed for your code.
Step 3: Connect mocha to the babel configuration:
In your package.json file
Under the scripts section, simply write something like this:
"test": "mocha \"src/**/*.test.js\""
Create a .mocharc.json file with this content:
{
"exit": true,
"color": true,
"require": ["#babel/register"],
"ignore": "node_modules"
}
This will apply Babel transformations to all of your test files.
If you need need to apply some special global javascript before/to all of your tests, you can add another file to the require setting, for example, fixtures.cjs:
"require": ["#babel/register", "fixtures.cjs"],
fixtures.cjs:
Below example applies a chai (popular alongside Mocha) plugin for testing DOM-related code:
var chai = require('chai'),
chaiDOM = require('chai-dom');
// https://stackoverflow.com/questions/62255953/chai-usechaihttp-once-or-in-every-test-file
// https://mochajs.org/#global-teardown-fixtures
exports.mochaGlobalSetup = function () {
chai.use(chaiDOM);
}
Interesting reads:
Babel vs babel-core vs babel-runtime
How does mocha / babel transpile my test code on the fly?
I'm not sure if there's a bug with something I'm using or whether I've just set something up wrong here, but I'm getting this error from eslint when running eslint src --fix about "eslint-plugin-#typescript-eslint"
I've specified the plugin as listed in the #TypeScript-eslint docs but I'm getting this weird error where eslint is trying to add 'eslint-plugin-' to the start of the plugin name (the package name is #typescript-eslint/eslint-plugin)
I'm using Gatsby and the accompanying TypeScript plugin.
Error
$ eslint src --fix
Oops! Something went wrong! :(
ESLint: 4.19.1.
ESLint couldn't find the plugin "eslint-plugin-#typescript-eslint". This can happen for a couple different reasons:
1. If ESLint is installed globally, then make sure eslint-plugin-#typescript-eslint is also installed globally. A globally-installed ESLint cannot find a locally-installed plugin.
2. If ESLint is installed locally, then it's likely that the plugin isn't installed correctly. Try reinstalling by running the following:
npm i eslint-plugin-#typescript-eslint#latest --save-dev
.eslintrc.js:
module.exports = {
parser: '#typescript-eslint/parser',
parserOptions: {
ecmaFeatures: {
jsx: true,
},
ecmaVersion: 2018,
sourceType: 'module',
},
env: {
browser: true,
node: true,
es6: true,
'jest/globals': true,
},
plugins: ['#typescript-eslint', 'react', 'jest'],
extends: [
'standard',
'plugin:react/recommended',
'plugin:#typescript-eslint/recommended',
'plugin:jest/recommended',
'plugin:prettier/recommended',
// 'eslint-config-prettier', // must be last
'prettier/#typescript-eslint',
],
rules: {
'react/prop-types': 0,
'jsx-quotes': ['error', 'prefer-single'],
'react/no-unescaped-entities': 0,
},
settings: {
react: {
version: 'detect',
},
linkComponents: [
// Components used as alternatives to <a> for linking, eg. <Link to={ url } />
'Hyperlink',
{ name: 'Link', linkAttribute: 'to' },
],
},
}
package.json
{
"name": "jmulholland.com",
"description": "My personal website",
"license": "MIT",
"scripts": {
"dev": "gatsby develop",
"build": "gatsby build",
"serve": "gatsby serve",
"lint": "eslint src --fix",
"prettier": "prettier \"**/*.+(js|jsx|ts|tsx|json|css|md|mdx|graphql)\"",
"format": "yarn prettier --write",
"type-check": "tsc --noEmit",
"validate": "yarn lint && yarn prettier --list-different"
},
"dependencies": {
"gatsby": "^2.1.4",
"gatsby-plugin-react-helmet": "^3.0.6",
"gatsby-plugin-styled-components": "^3.0.5",
"gatsby-plugin-typescript": "^2.0.10",
"gatsby-plugin-typography": "^2.2.7",
"gatsby-remark-prismjs": "^3.2.4",
"gatsby-source-contentful": "^2.0.29",
"gatsby-transformer-remark": "^2.3.0",
"prismjs": "^1.15.0",
"prop-types": "^15.7.2",
"react": "^16.8.2",
"react-dom": "^16.8.2",
"react-helmet": "^5.2.0",
"react-typography": "^0.16.18",
"styled-components": "^4.1.3",
"typography": "^0.16.18"
},
"devDependencies": {
"#typescript-eslint/eslint-plugin": "^1.4.2",
"#typescript-eslint/parser": "^1.4.2",
"babel-jest": "^24.1.0",
"babel-plugin-styled-components": "^1.10.0",
"babel-preset-gatsby": "^0.1.8",
"dotenv": "^6.0.0",
"eslint": "^4.19.1",
"eslint-config-prettier": "^4.1.0",
"eslint-config-standard": "^12.0.0",
"eslint-plugin-import": "^2.16.0",
"eslint-plugin-jest": "^22.3.0",
"eslint-plugin-jsx-a11y": "^6.2.1",
"eslint-plugin-node": "^8.0.1",
"eslint-plugin-prettier": "^3.0.1",
"eslint-plugin-promise": "^4.0.1",
"eslint-plugin-react": "^7.11.1",
"eslint-plugin-standard": "^4.0.0",
"faker": "^4.1.0",
"husky": "^1.3.1",
"jest": "^24.1.0",
"lint-staged": "^8.1.5",
"prettier": "^1.16.4",
"typescript": "^3.3.3333"
},
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
}
}
Solution was simply to upgrade to the latest version of eslint
Not sure if it's still not resolved. But adding "root": true to my .eslintrc.json helped me.
For any future readers who might be facing this issue, in my case I was working with a multi-stage Docker build based on the node:alpine image. The multi-stage build was meant to create a separation between the app's dependencies and the devDependencies (in package.json).
At some point in creating my Dockerfile, which underwent quite a few modifications over several hours, I added the following line towards the beginning of my Dockerfile:
ENV NODE_ENV production
This causes npm to ignore the devDependencies packages, which in turn causes ESLint to fail (because it isn't installed).
I moved the environment variable declaration to my final (release) build stage, where I originally wanted it, and then npm installed all required packages and ESLint ran successfully.
Hopefully this saves someone some precious time.
I just faced this issue on a large monorepo, found two solutions that fixed it for us:
{
"scripts": {
"lint": "eslint src --resolve-plugins-relative-to ."
}
}
If you use yarn workspace, yarn run could also do the trick:
{
"scripts": {
"lint": "yarn run eslint src"
}
}
my solution on Mac was like
go to global node_modules cd /usr/local/lib/node_modules/
delete global eslint rm -rf eslint
run the command once again eslint index.js app storybook test --fix --ext .js,.ts,.tsx
profit
Issues can cause this:
Outdated ESLint.
ESLint installed globally and locally at the same time. Solution.
Missing .eslintrc config file from the project folder. Solution: npx eslint --init
Additional node_modules folder in the project-parent folder outside your project.
Additional .eslintrc in the project-parent folder outside your project.
Wrong package config. Read more.
Another reason that could cause this issue is not having ESLint configured.
In my case, adding a .eslintrc.json file to the root directory (with proper configuration) fixed the issue.
Since i faced same issue with eslint now, i'm posting here about the root cause of the issue in my case.
I installed this eslint-nullish-coalescing plugin which is a fork of eslint to nullish coalescing. This plugin changed the content of node_module\.bin\eslint.cmd file.
from
#IF EXIST "%~dp0\node.exe" (
"%~dp0\node.exe" "%~dp0\..\eslint\bin\eslint.js" %*
) ELSE (
#SETLOCAL
#SET PATHEXT=%PATHEXT:;.JS;=;%
node "%~dp0\..\eslint\bin\eslint.js" %*
)
to
#IF EXIST "%~dp0\node.exe" (
"%~dp0\node.exe" "%~dp0\..\eslint-nullish-coalescing\bin\eslint.js" %*
) ELSE (
#SETLOCAL
#SET PATHEXT=%PATHEXT:;.JS;=;%
node "%~dp0\..\eslint-nullish-coalescing\bin\eslint.js" %*
)
Because of this, eslint could not find the right plugins for its work, hence the error 😰.
Though OP is not using eslint-nullish-coalescing package, but i would suggest to verify the content of the node_modules\.bin\eslint.cmd file if anyone who are facing this issue now.
In my case one of the parent directories had another node_modules folder.
Moving the package directory into a path with no other node_modules folder in the parent tree removed the error.
Recently I met the same problem when I am trying to use ESLint and Prettier in my project which is created in 2017 and using Angular 9. After googled a lot, I just solved it by upgrading ESLint to version 8+. Version 6+ also works but version 7+ may cause another error. That's really weird.
Then I added a new script like:
./node_modules/eslint/bin/eslint.js ./ --ext .ts,.tsx --config .eslintrc.js --fix
And ESLint just works fine. And you can add some configs in .eslintrc.js (on) file to let ESLint know which files are supposed to be linted and formatted.
I started working a lot with vue and started to use it in all the projects in the company where I work. And with that, I ended up creating some components, in general autocomplete, I know that there are many, I have already used some, but none have supplied all my needs. However, whenever I go to work on a new project and use the same component, either I recreates it, or I copy and paste it.
So I came to doubt How to create my component, upload to npmjs for whenever I use it, just give a npm install -save ..., and also be able to contribute a bit with the community.
update
With the release of vue-loader 15.x this answer will no longer work. Please use this instead https://medium.freecodecamp.org/how-to-create-a-vue-js-app-using-single-file-components-without-the-cli-7e73e5b8244f
Here is one way you can create/publish a Vuejs library/component from scratch.
As I am going to write down every step and command, make sure to follow the entire guide and you will be able to create and publish your own Vuejs component on NPM.
After you publish it, like most libraries you can install it using ex:
npm install --save your-component
And then import the component inside your app using
import something from 'your-component'
To start creating our first component, first create a folder called vuejs-hello-app (or any other name) and inside it, run:
npm init
Just hit enter until the interactive question ends and then npm will generate a file named package.json in that folder containing the following code.
(Note: I changed the description and version from 1.0.0 to 0.1.0 here is the result.)
{
"name": "vuejs-hello-app",
"version": "0.1.0",
"description": "vuejs library demo",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
After this, we'll need to install the dependencies for our library.
These dependencies are divided into two types: dependency and devDependency
dependency:
is the external library or libraries that our own component runs on. When someone installs your component, npm will make sure this dependency exists or gets installed first. Since we are creating a component for vue, we need to make sure vue is required. So, install it using:
npm install --save vue
devDependency:
is a bunch of libraries that we need only for development purposes. These libraries will help us build and/or transpile.
We install dev dependencies using the method above by adding the the suffix -dev to --save
Now, let us install the minimum dev dependencies we need for our component:
npm install --save-dev babel-core
npm install --save-dev babel-loader
npm install --save-dev babel-preset-env
npm install --save-dev cross-env
npm install --save-dev css-loader
npm install --save-dev file-loader
npm install --save-dev node-sass
npm install --save-dev sass-loader
npm install --save-dev vue-loader
npm install --save-dev vue-template-compiler
npm install --save-dev webpack
npm install --save-dev webpack-dev-server
At this point the libraries will be installed and the package.json will be updated to look like following.
{
"name": "vuejs-hello-app",
"version": "0.1.0",
"description": "vuejs library demo",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack -p"
},
"author": "",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-env": "^1.6.1",
"cross-env": "^5.1.1",
"css-loader": "^0.28.7",
"file-loader": "^1.1.5",
"node-sass": "^4.7.2",
"sass-loader": "^6.0.6",
"vue-loader": "^13.5.0",
"vue-template-compiler": "^2.5.9",
"webpack": "^3.10.0",
"webpack-dev-server": "^2.9.7"
},
"dependencies": {
"vue": "^2.5.9"
}
}
(note: I have added "build": "webpack -p" to build our lib with webpack)
Now, since our code needs to be built and transpiled, we need a folder to store the build version. Go ahead and create a folder inside our root folder and call it: dist and in the same place a configuration file for webpack and name it webpack.config.js
All of the files we have so far created are for configuring and stuff. For the actual app that people are going to use, we need to create at least two files inside our src/ directory.
A main.js and VuejsHelloApp.vue put them as:
./src/main.js and ./src/components/VuejsHelloApp.vue
I have mine structured like this:
dist
node_modules
src
main.js
components
VuejsHelloApp.vue
.babelrc
.eslintignore
.gitignore
.npmignore
.travis.yml
CONTRIBUTING
LICENSE
package.json
README.md
webpack.config.js
I will just go through the files listed and describe what each file does in-case anyone is curious:
/dist is where a build (transpiled), minified, non-ES6 version of your code will be stores
node_modules I think we know this already, let's ignore it
src/ this is root dir of your library.
.babelrc is where your babel options are kept, so add this to disable presets on modules
{
"presets": [
[
"env",
{
"modules": false
}
]
]
}
.eslintignore This is where you tell ESLINT to ignore linting so put this inside:
build/*.js
.gitignore
add files you want to ignore (from git)
.npmignore same as .gitignore for NPM
.travis.yml if you need CI check examples from travis and configure it
CONTRIBUTING not required
LICENSE not required
package.json ignore for now
README.md not required
webpack.config.js This is the important file that let's you create a build, browser compatible version of your code.
So, according to our app, here is a minimal example of what it should look like:
var path = require('path')
var webpack = require('webpack')
module.exports = {
entry: './src/main.js',
module: {
rules: [
// use babel-loader for js files
{ test: /\.js$/, use: 'babel-loader' },
// use vue-loader for .vue files
{ test: /\.vue$/, use: 'vue-loader' }
]
},
// default for pretty much every project
context: __dirname,
// specify your entry/main file
output: {
// specify your output directory...
path: path.resolve(__dirname, './dist'),
// and filename
filename: 'vuejs-hello-app.js'
}
}
if (process.env.NODE_ENV === 'production') {
module.exports.devtool = '#source-map'
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
})
])
}
Note that the important directives here are entry and output. You can check webpack docs to learn more if you want to fully customize your app.
But basically, we're telling webpack to get the ./src/main.js (our app) and output it as ./dist/vuejs-hello-app.js
Now, we are almost finished setting up everything except the actual app.
Go to /src/components/VuejsHelloApp.vue and dump this simple app, which will move a button right or left when you hover on it
<template>
<div>
<button #mouseover='move($event)'> I'm alive </button>
</div>
</template>
<script>
export default {
data () {
return {}
},
methods: {
move (event) {
let pos = event.target.style.float;
if(pos === 'left'){
event.target.style.float = 'right'
}else{
event.target.style.float = 'left'
}
}
}
}
</script>
<style scoped>
</style>
And not but not least, got to ./src/main.js and export your app like:
import VuejsHelloApp from './components/VuejsHelloApp.vue'
export default VuejsHelloApp
Now go to your package.json file replace the "main: "index.js", with "main": "src/main.js",
After this, simply run these commands to build and publish your app:
npm run build
git add .
git commit -m "initial commit"
git push -u origin master
npm login
npm publish
Importing and using the library.
If everything went smoothly, then simply install your app like this:
npm install --save vuejs-hello-app
And use it in vue like this:
<template>
<div>
<VuejsHelloApp> </VuejsHelloApp>
</div>
</template>
<script>
import VuejsHelloApp from 'vuejs-hello-app'
export default {
name: 'HelloWorld',
components: { VuejsHelloApp }
}
</script>
I made this app https://github.com/samayo/vuejs-hello-app while writing the answer, it might help to better understand the code
I'm new to react js and I'm trying to set up the environment for it and I followed the steps mentioned in https://www.tutorialspoint.com/reactjs/reactjs_environment_setup.htm.
But after doing all the things mentioned there I'm getting this error:
'webpack-dev-server' is not recognized as an internal or external command, operable program or batch file
If you want to develop an application using babel, webpack, etc. You need to follow following steps. No doubt there are much better tutorial available over the internet but it will give you some idea.
1.Webpack:
In browsers you can not require or import modules as you usually do while writing node.js code. With the help of a module bundler, maybe Webpack, you can write code that uses require/import in the same way that you would use it in node environment. I am assuming you will use webpack considering its popularity.
2. Install dependencies (es6)
These are minimal dependencies you need in your project (package.json) to get it working. You can directly copy paste the following text into a new file named "package.json". run the following set of commands in you EMPTY project directory:
install the node package manager
npm init [follow the command prompt to fill in meta data of your project like name, author,etc.]
install global packages
npm install -g babel babel-cli
[this will install transpiler(babel) into your global environment]
install module bundler
npm install webpack webpack-dev-server --save
install babel plugins
npm install babel-core babel-loader babel-preset-react babel-preset-es2015
After this command set, your package.json will start looking like as following:
{
"name": "reactjs",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "No Command Written Yet"
},
"author": "",
"license": "ISC",
"dependencies": {
"babel-core": "^6.25.0",
"babel-loader": "^7.1.1",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"react": "^15.6.1",
"react-dom": "^15.6.1",
"webpack": "^3.4.1",
"webpack-dev-server": "^2.6.1"
},
"devDependencies": {
"babel-core": "^6.25.0",
"babel-loader": "^7.1.1",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1"
}
}
3.Write your webpack-config.js file
A sample webpack config file should like this. Don't ask me about each bit of it but rather have a look on webpack tutorial because I can not explain everything here. Just remember the fact that
Webpack is a module bundler that bundles javascript and other assets for the browser.
var config = {
entry: './main.js',
output: {
path:'/',
filename: 'index.js',
},
devServer: {
inline: true,
port: 8080
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
}
}
]
}
}
module.exports = config;
4.Set up entry point for your application
src->index.js
index.js
import React from 'react';
import ReactDOM from 'react-dom';
ReactDOM.render(
<App />
, document.querySelector('.init')
);
5.Setup index.html in your project root
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Welcome to ReactJs</title>
</head>
<body>
<div class="init"></div>
</body>
<script src="./public/bundle.js"></script>
</html>
6.Running
A slight change is needed in your package.json
replace:
"scripts": {
"test": "No Command Written Yet"
},
with
"scripts": {
"dev": "webpack-dev-server --hot"
},
[this will change the script you will run to execute the app bundled by webpack]
Now, whenever you want to run the project, just be in the project root directory and call:
npm run dev
DONE, Have Fun!
Run:
npm install webpack-dev-server --save-dev
And try again. You got the error because webpack-dev-server couldn't be found in your devDependencies inside of your package.json file
This is happening because you don't have webpack-dev-server installed as a global package, that's why you can execute directly.
The recommended way is installing it locally, in this way you'll avoid this problem.
Here you can find the steps to make it run.
Good luck