Jest arrow syntax causes error - javascript

I'm setting up Jest for a webpack 2 project that isn't a React project.
I have installed jest-cli and babel-jest.
I'm getting this error:
.babel-rc:
{
"presets": [
"es2015"
],
"plugins": [
"syntax-jsx",
["transform-react-jsx", {"pragma": "html"}]
]
}
webpack.config.js:
var path = require('path')
var webpack = require('webpack')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
module.exports = {
devtool: 'source-map',
entry: [
'webpack-dev-server/client?http://localhost:3000',
'./src/index'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
use: {
loader: 'babel-loader'
}
},
{
test: /\.css$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
modules: true,
localIdentName: '[name]__[local]___[hash:base64:5]'
}
}
]
},
{
test: /\.styl$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
modules: true,
localIdentName: '[name]__[local]___[hash:base64:5]'
}
},
'stylus-loader'
],
}
]
},
resolve: {
extensions: ['.js'],
modules: [
path.join(__dirname, 'src'),
'node_modules'
]
},
plugins: [
new ExtractTextPlugin({ filename: 'style.css', allChunks: true }),
],
jest: {
moduleNameMapper: {
'\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$': '<rootDir>/__mocks__/fileMock.js',
'\\.(css|less)$': '<rootDir>/__mocks__/styleMock.js'
}
},
'env': {
'test': {
'plugins': ['transform-es2015-modules-commonjs']
}
}
}
package.json:
{
"name": "test",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"start": "node server.js",
"test": "jest"
},
"babel": {
"presets": [
"es2015",
"react",
"stage-0"
]
},
"devDependencies": {
"babel-core": "^6.23.1",
"babel-jest": "^19.0.0",
"babel-loader": "^6.3.2",
"babel-plugin-transform-object-assign": "^6.22.0",
"babel-preset-es2015": "^6.22.0",
"babel-preset-react": "^6.23.0",
"babel-preset-stage-0": "^6.22.0",
"css-loader": "^0.26.2",
"eslint": "^3.17.0",
"extract-text-webpack-plugin": "^2.0.0",
"identity-obj-proxy": "^3.0.0",
"jest": "^19.0.2",
"jest-cli": "^19.0.2",
"regenerator-runtime": "^0.10.3",
"style-loader": "^0.13.2",
"stylus": "^0.54.5",
"stylus-loader": "^2.5.0",
"webpack": "^2.2.1",
"webpack-dev-server": "^2.4.1"
},
"dependencies": {
"#cycle/dom": "^16.0.0",
"#cycle/run": "^3.0.0",
"babel-plugin-transform-react-jsx": "^6.23.0",
"bulma": "^0.3.2",
"css-modules-require-hook": "^4.0.5",
"eslint-plugin-jsx": "^0.0.2",
"snabbdom-jsx": "^0.3.1",
"xstream": "^10.3.0"
}
}
How can I get rid of the error?

Using arrow function without parameters still requires the parentheses.
The following code should work:
test('adds a and b together', () => {
expect(sum(1, 2)).toBe(3)
})
Note that the only case the parentheses are not needed is when there is only one parameter.
You can read documentation here.

Related

SassError: Expected newline. #charset "UTF-8"; when building a Vue app with Sass as sass-loader on Webpack 4

I'm trying to build my Vue app on Node 13 and Webpack 4. For this I'm using this webpack.config.js
const { VueLoaderPlugin } = require("vue-loader");
const htmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const autoprefixer = require("autoprefixer");
const path = require("path");
const devMode = process.env.NODE_ENV !== 'production'
module.exports = {
mode: 'development',
entry: {
main: "./src/main.js",
},
output: {
filename: "[name].[contenthash:12].js",
path: path.resolve(__dirname, "dist"),
chunkFilename: "[name].[contenthash:12].js",
},
module: {
rules: [
{
test : /\.(jsx?)$/,
exclude: /node_modules/,
loader: "babel-loader",
},
{
test: /\.vue$/,
loader: "vue-loader",
},
{
test: /\.(eot|ttf|woff|woff2|txt)(\?\S*)?$/,
loader: "file-loader",
options: {
name: "[name][contenthash:8].[ext]",
},
},
{
test: /\.(png|jpe?g|gif|webm|mp4|svg|ico)$/,
loader: "file-loader",
options: {
name: "[name][contenthash:8].[ext]",
outputPath: "assets/img",
esModule: false,
},
},
{
test: /\.(css)$/,
use: [
"vue-style-loader",
"style-loader",
"css-loader",
{
loader: "postcss-loader",
options: {
postcssOptions: {
plugins: () => [autoprefixer()],
},
},
},
],
},
{
test: /\.(s(c|a)ss)$/,
use: [
"vue-style-loader",
"style-loader",
"css-loader",
{
loader: "postcss-loader",
options: {
sourceMap: true,
importLoaders: 2,
postcssOptions: {
plugins: () => [autoprefixer()],
},
},
},
"sass-loader",
{
loader: "sass-loader",
options: {
sourceMap: true,
implementation: require("sass"),
sassOptions: {
//fiber: require("fibers"),
prependData: `#import "app/javascript/manager/styles/main.scss"`,
//indentedSyntax: true
}
}
},
],
},
],
},
plugins: [
new VueLoaderPlugin(),
new CleanWebpackPlugin(),
new MiniCssExtractPlugin({
filename: "[name].[contenthash:8].css",
chunkFilename: "[name].[contenthash:8].css",
}),
new htmlWebpackPlugin({
template: path.resolve(__dirname, "public", "index.html"),
favicon: path.resolve(__dirname, "public", "favicon.ico"),
}),
],
resolve: {
alias: {
vue$: "vue/dist/vue.runtime.esm.js",
},
extensions: ["*", ".js", ".jsx", ".css", ".scss", ".vue"],
modules: [
"node_modules",
]
},
optimization: {
moduleIds: "hashed",
runtimeChunk: "single",
splitChunks: {
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: "vendors",
priority: -10,
chunks: "all",
},
},
},
},
devServer: {
historyApiFallback: true,
},
}
And this is my package.json
{
"name": "my-app-frontend",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
},
"dependencies": {
"#vue/compiler-sfc": "^3.1.4",
"axios": "^0.21.1",
"clean-webpack-plugin": "^4.0.0-alpha.0",
"core-js": "^3.6.5",
"sass-loader": "10.1.1",
"style-loader": "^2.0.0",
"vue": "^2.6.11",
"vue-axios": "^3.2.4",
"vue-router": "^3.5.2",
"vuetify": "^2.5.6",
"webpack-war-plugin": "^1.0.0-beta.3"
},
"devDependencies": {
"#babel/core": "^7.14.6",
"#babel/preset-env": "^7.14.7",
"#vue/cli-plugin-babel": "~4.5.0",
"#vue/cli-plugin-eslint": "~4.5.0",
"#vue/cli-service": "~4.5.0",
"babel-eslint": "^10.1.0",
"babel-loader": "^8.2.2",
"clean-webpack-plugin": "^4.0.0-alpha.0",
"eslint": "^6.7.2",
"eslint-plugin-vue": "^6.2.2",
"postcss": "^8.2.1",
"postcss-loader": "^4.2.0",
"sass": "1.32.13",
"sass-loader": "10.1.1",
"style-loader": "^2.0.0",
"vue-cli-plugin-vuetify": "~2.4.1",
"vue-loader": "^16.3.0",
"vue-template-compiler": "^2.6.14",
"vuetify": "^2.5.6",
"vuetify-loader": "^1.7.0",
"webpack": "^4.42.0",
"webpack-cli": "^4.7.2",
"webpack-dev-server": "^3.11.2"
},
"eslintConfig": {
"root": true,
"env": {
"node": true
},
"extends": [
"plugin:vue/essential",
"eslint:recommended"
],
"parserOptions": {
"parser": "babel-eslint"
},
"rules": {}
},
"browserslist": [
"> 1%",
"last 2 versions",
"not dead"
]
}
After struggling with the sass-loader I reduced the list of errors, but this one is significant and I haven't found a way to remove it:
ERROR in ./node_modules/vuetify/src/styles/main.sass (./node_modules/css-loader/dist/cjs.js!./node_modules/postcss-loader/dist/cjs.js??ref--5-3!./node_modules/sass-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js??ref--5-5!./node_modules/vuetify/src/styles/main.sass)
Module build failed (from ./node_modules/sass-loader/dist/cjs.js):
SassError: Expected newline.
╷
1 │ #charset "UTF-8";
│ ^
╵
No sass-node, just sass was used. Uncommenting indentedSyntax: true will simply drop another error saying that semicolons are not allowed. Upgrading versions will return other set of error. Fibers is out of scope (it just improves processing of certain async calls to my knowledge). Upgrading to Webpack5 adds a pletora of new problems as the json structure is quite different.
I'm totally stack at this point. There must be something else to work on the sass loader nut I'm not an expert on webpack so it's taking simply too long. Any help would be greatly appreciated at this point. I cannot believe none is having the same issue. I see many related answers but everyone seem to be doing fine just adding indentation. Thanks!

Postcss-loader not minifying css output

I'm using webpack and postcss-loader to autoprefix and minify my CSS, before loading it into css-loader to use css-modules. I'm having trouble with minifying CSS. Examining the emitted .js file by webpack shows the CSS isn't minified with cssnano (because I can still see whitespace characters). What am I doing wrong?
Some relevant configuration files:
webpack.config.js:
const path = require('path');
const webpack = require('webpack');
var postCompileScript = require('./postCompile');
module.exports = {
entry: './src/popup.js',
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.css$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
modules: true,
localIdentName: '[local]__[hash:base64:6]',
importLoaders: 1,
minimize: true
}
},
{
loader: 'postcss-loader',
options: {
ident: 'postcss',
plugins: [
require('autoprefixer')({})
],
minimize: true
}
}
]
},
{
test: /\.(png|jpg|gif)$/i,
use: [
{
loader: 'url-loader',
options: {
limit: 8192
}
}
]
}
]
},
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist')
},
mode: 'production',
resolve: {
alias: {
"react": "preact-compat",
"react-dom": "preact-compat"
},
extensions: ['.js', '.jsx']
}
};
postcss.config.js:
module.exports = {
parser: 'sugarss',
plugins: {
'postcss-import': {},
'postcss-preset-env': {},
'cssnano': {}
}
}
package.json
{
"name": "REDACTED",
"version": "1.0.0",
"description": "",
"private": true,
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack --config ./webpack.config.js",
"deploy": "node ftp"
},
"author": "",
"license": "ISC",
"devDependencies": {
"autoprefixer": "^9.1.2",
"babel-core": "^6.26.3",
"babel-loader": "^7.1.5",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"css-loader": "^1.0.0",
"cssnano": "^4.1.0",
"ftp": "^0.3.10",
"post-compile-webpack-plugin": "^0.1.2",
"postcss-loader": "^3.0.0",
"prepend-file": "^1.3.1",
"style-loader": "^0.22.1",
"uglifyjs-webpack-plugin": "^1.3.0",
"url-loader": "^1.1.1",
"webpack": "^4.16.5",
"webpack-bundle-analyzer": "^2.13.1",
"webpack-cli": "^3.1.0"
},
"dependencies": {
"iframe-resizer": "^3.6.1",
"js-cookie": "^2.2.0",
"npm": "^6.4.0",
"preact": "^8.3.1",
"preact-compat": "^3.18.3",
"react": "^16.4.2",
"react-dom": "^16.4.2",
"react-iframe-resizer-super": "^0.2.0"
}
}
Thanks in advance.
For any future readers: I solved my problem by just adding the cssnano plugin to the postcss-loader in the config. Thus the css rule is as follows (webpack.config.js):
{
test: /\.css$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
modules: true,
localIdentName: '[local]__[hash:base64:6]',
importLoaders: 1,
minimize: true
}
},
{
loader: 'postcss-loader',
options: {
ident: 'postcss',
plugins: [
require('autoprefixer')({}),
require('cssnano')({ preset: 'default' })
],
minimize: true
}
}
]
}

Webpack, Gulp, and React loading errors

My setup is below. If I run gulp in the directory with these files, then I get a boatload of errors that look like the following. They all have a similar signature but are failing to find a different part of react-bootstrap, react-dom, or the like.
Module not found: Error: Can't resolve 'react-bootstrap/lib/Input' in '...a/scripts/components'
# ./a/scripts/components/SearchBar.js 7:12-48
# ./a/scripts/pages/HomePage.js
# ./a/scripts/routes.js
# ./a/scripts/index.js
# multi webpack-dev-server/client?http://localhost:8083 webpack/hot/only-dev-server ./a/scripts/index
This makes me think it's to do with the loader. And in fact, if I run npm install, then after verifying that everything is installed and making a bundle.js, this error occurs:
ERROR in ./a/scripts/index.js
Module parse failed: Unexpected token (19:15)
You may need an appropriate loader to handle this file type.
|
| Router.run(routes, Router.HistoryLocation, function(Handler) {
| React.render(<Handler />, document.getElementById('entry'));
| });
|
# multi ./a/scripts/index
Which also suggests it's with the loader. I've since spent a lot of time trying to figure out why the loader wouldn't be working and am coming up blank. Help would be greatly appreciated.
package.json
{
"version": "1.0.0",
"main": "index.js",
"engines": {
"node": "0.12.7",
"npm": "2.7.5"
},
"scripts": {
"postinstall": "gulp build"
},
"author": "",
"license": "none",
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-env": "^1.6.1",
"css-loader": "^0.28.8",
"del": "^3.0.0",
"file-loader": "^1.1.6",
"gulp": "^3.9.1",
"gulp-autoprefixer": "^4.1.0",
"gulp-cache": "^1.0.2",
"gulp-clean-css": "^3.9.2",
"gulp-concat": "^2.5.2",
"gulp-imagemin": "^4.1.0",
"gulp-jshint": "^2.1.0",
"gulp-livereload": "^3.8.0",
"gulp-notify": "^3.1.0",
"gulp-rename": "^1.2.0",
"gulp-ruby-sass": "^3.0.0",
"gulp-uglify": "^3.0.0",
"jsx": "^0.9.89",
"jsx-loader": "^0.13.2",
"lodash": "^4.17.4",
"moment": "^2.9.0",
"node-sass": "^4.7.2",
"plugin-error": "^0.1.2",
"react": "^16.2.0",
"react-bootstrap": "^0.32.0",
"react-hot-loader": "^3.1.3",
"react-router": "^4.2.0",
"react-script-loader": "^0.0.1",
"run-sequence": "^2.2.1",
"sass-loader": "^6.0.6",
"sass-material-colors": "0.0.5",
"style-loader": "^0.19.1",
"superagent": "^3.8.2",
"underscore": "^1.8.3",
"url-loader": "^0.6.2",
"webpack": "^3.10.0",
"webpack-dev-server": "2.10.1"
},
"dependencies": {
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-2": "^6.24.1"
},
}
.babelrc
{
"presets": ["env", "react"]
}
gulpfile.babel.js
var gulp = require('gulp'),
sass = require('gulp-ruby-sass'),
autoprefixer = require('gulp-autoprefixer'),
cleanCSS = require('gulp-clean-css'),
rename = require('gulp-rename');
var log = require('fancy-log');
var PluginError = require('plugin-error');
var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
var webpackConfig = require("./webpack.config.js");
var runSequence = require('run-sequence');
var path = require('path');
var del = require('del');
var watch = true;
var verbose = true;
// Default to Dev Server
gulp.task('default', ["js-dev-server"]);
// Clean output directory
gulp.task('clean', () => del(['a/static/js/build/*', 'a/static/css/*'], {dot:true}))
gulp.task('styles', function() {
return sass('a/static/scss/styles.scss', { style: 'expanded' })
.pipe(autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1'))
.pipe(gulp.dest('a/static/css'))
.pipe(rename({suffix: '.min'}))
.pipe(cleanCSS())
.pipe(gulp.dest('a/static/css'));
});
gulp.task('watch', function() {
gulp.watch('a/static/scss/**/*.scss', ['styles']);
});
gulp.task('bundle', function() {
function bundle(err, stats) {
if (err) {
throw new PluginError("build", err);
}
console.log(stats.toString({
colors: true,
hash: verbose,
version: verbose,
timings: verbose,
chunks: verbose,
chunkModules: verbose,
cached: verbose,
cachedAssets: verbose
}));
}
webpack(webpackConfig).run(bundle)
});
gulp.task('build', ['clean'], cb => { runSequence(['styles', 'bundle']); });
gulp.task("js-dev-server", function(callback){
// modify some webpack config options
var myConfig = Object.create(webpackConfig);
myConfig.devtool = "eval-source-map";
myConfig.entry = [
'webpack-dev-server/client?http://localhost:8083',
'webpack/hot/only-dev-server',
'./a/scripts/index'
];
myConfig.plugins = [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
new webpack.LoaderOptionsPlugin({debug: true})
];
myConfig.output['publicPath'] = "http://localhost:8083/static/js/build/"
myConfig.module = {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loaders: ['react-hot-loader/webpack', 'jsx-loader?harmony', 'babel-loader']
},
{ test: /\.woff(\?v=\d+\.\d+\.\d+)?$/,
loader: "url-loader?limit=10000&minetype=a/font-woff" },
{ test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/,
loader: "url-loader?limit=10000&minetype=a/font-woff" },
{ test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
loader: "url-loader?limit=10000&minetype=a/octet-stream" },
{ test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
loader: "file-loader" },
{ test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
loader: "url-loader?limit=10000&minetype=image/svg+xml" },
{ test: /\.scss$/, loader: "style-loader!css-loader!sass-loader?includePaths[]=" +
path.resolve(__dirname, "./a/static/scss/")
}
]
};
// Start a webpack-dev-server
new WebpackDevServer(webpack(myConfig), {
publicPath: "http://localhost:8083/static/js/build/",
stats: {
colors: true
},
inline: true,
hot: true,
historyApiFallback: true,
contentBase: 'http://localhost:5000/'
}).listen(8083, "localhost", function(err) {
if(err) throw new PluginError("webpack-dev-server", err);
log("[webpack-dev-server]",
"http://localhost:8083/webpack-dev-server/index.html");
});
});
webpack.config.js
var webpack = require('webpack');
var path = require('path');
var DEBUG = true;
module.exports = {
entry: [
__dirname + '/a/scripts/index'
],
output: {
path: __dirname + '/a/static/js/build',
filename: 'bundle.js',
},
plugins: [
new webpack.NoEmitOnErrorsPlugin(),
new webpack.optimize.UglifyJsPlugin({sourceMap: false,
output: {comments: false}}),
],
resolve: {
extensions: ['.js', '.jsx'],
modules: ['node_modules', 'web_modules', 'scripts', 'lib'],
},
module: {
rules: [
{
test: /\*.js.x?$/,
exclude: /node_modules/,
loaders: (DEBUG ? ['react-hot-loader/webpack'] : []).concat(['babel-loader'])
},
{ test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, loader: "url-loader?limit=10000&minetype=application/font-woff" },
{ test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/, loader: "url-loader?limit=10000&minetype=application/font-woff" },
{ test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: "url-loader?limit=10000&minetype=application/octet-stream" },
{ test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: "file-loader" },
{ test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: "url-loader?limit=10000&minetype=image/svg+xml" },
{ test: /\.scss$/, loader: "style-loader!css-loader!sass-loader?includePaths[]=" +
path.resolve(__dirname, "./a/static/scss/")
}
]
},
externals: {
"jquery": "jQuery"
}
};
index.js
'use strict';
var React = require('react'),
Router = require('react-router'),
routes = require('routes');
// set up in order to receive actions
var NotificationStore = require('stores/NotificationStore');
require('csrf'); // injects CSRF token into all $.ajax calls
require('../static/scss/playground.scss'); // loads stylesheet into JS
Router.run(routes, Router.HistoryLocation, function(Handler) {
React.render(<Handler />, document.getElementById('entry'));
});
This issue is due to your babel setup. You need to install babel-plugin-transform-react-jsx and adjust your .babelrc file. Like this:
{
"presets": ["env", "es2015", "react"],
"plugins": ["transform-react-jsx", "transform-object-rest-spread"]
}
example webpack.config.js:
const path = require('path')
const config = {
entry: {
app: ['whatwg-fetch','./src/index.js'],
},
devtool: 'inline-source-map',
devServer: {
contentBase: './public'
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'eslint-loader'
},
{
test: /\.css/,
exclude: /node_modules/,
use: ['style-loader', 'css-loader'],
},
{
test: /.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015', 'react']
}
},
]
},
output: {
filename: 'app.bundle.js',
path: path.resolve(__dirname, 'public')
}
}
module.exports = config
example package.json:
{
"name": "react-news-app",
"version": "1.0.0",
"description": "get news and sentiment from headline articles",
"main": "index.js",
"scripts": {
"test": "jest --watch",
"start": "webpack-dev-server --port 3000"
},
"keywords": [
"api",
"react"
],
"author": "Stephen Collins",
"license": "MIT",
"dependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"react": "^16.2.0",
"react-dom": "^16.2.0",
"whatwg-fetch": "^2.0.3"
},
"devDependencies": {
"babel-jest": "^22.0.4",
"babel-plugin-transform-object-rest-spread": "^6.26.0",
"babel-plugin-transform-react-jsx": "^6.24.1",
"babel-preset-env": "^1.6.1",
"chai": "^4.1.2",
"clean-webpack-plugin": "^0.1.17",
"css-loader": "^0.28.8",
"enzyme": "^3.3.0",
"enzyme-adapter-react-16": "^1.1.1",
"eslint": "^4.15.0",
"eslint-loader": "^1.9.0",
"jest": "^22.0.4",
"prop-types": "^15.6.0",
"sinon": "^4.1.3",
"style-loader": "^0.19.1",
"webpack": "^3.10.0",
"webpack-dev-server": "^2.10.0"
}
}

How to remove ESlint error no-unresolved from importing 'react'

no-unresolved https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-unresolved.md
After installing eslint-import-resolver-webpack
My .eslintrc config
{
"extends": "airbnb",
"rules": {
"comma-dangle": ["error", "never"],
"semi": ["error", "always"],
"react/jsx-filename-extension": 0,
"react/prop-types": 0,
"react/no-find-dom-node": 0,
"jsx-a11y/label-has-for": 0
},
"globals": {
"document": true,
"window": true
},
"env": {
"jest": true
},
"settings": {
"import/resolver": "webpack"
}
}
My package.json
{
"name": "coinhover",
"version": "0.0.1",
"main": "index.js",
"author": "Leon Gaban",
"license": "MIT",
"scripts": {
"start": "webpack-dev-server",
"dev": "webpack-dev-server",
"production": "webpack -p",
"build": "webpack -p",
"test": "eslint app && jest",
"test:fix": "eslint --fix app"
},
"now": {
"name": "coinhover",
"engines": {
"node": "7.4.x"
},
"alias": "coinhover.io"
},
"jest": {
"moduleNameMapper": {},
"moduleFileExtensions": [
"js",
"jsx"
],
"moduleDirectories": [
"node_modules"
]
},
"dependencies": {
"axios": "^0.16.1",
"babel-runtime": "6.11.6",
"jsonwebtoken": "^7.4.1",
"prop-types": "^15.5.10",
"ramda": "^0.24.1",
"react": "^15.5.4",
"react-dom": "^15.5.4",
"react-hot-loader": "next",
"react-redux": "^5.0.5",
"react-router": "^4.1.1",
"react-router-dom": "^4.1.1",
"redux": "^3.6.0",
"redux-thunk": "^2.2.0"
},
"devDependencies": {
"babel-core": "^6.24.1",
"babel-loader": "^7.0.0",
"babel-plugin-transform-es2015-modules-commonjs": "^6.24.1",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-polyfill": "^6.23.0",
"babel-preset-env": "^1.5.1",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"babel-preset-react-hmre": "^1.1.1",
"babel-preset-stage-0": "^6.24.1",
"copy-webpack-plugin": "^4.0.1",
"css-loader": "^0.28.4",
"enzyme": "^2.8.2",
"enzyme-to-json": "^1.5.1",
"eslint": "^4.3.0",
"eslint-config-airbnb": "^15.1.0",
"eslint-import-resolver-webpack": "^0.8.3",
"eslint-plugin-import": "^2.7.0",
"eslint-plugin-jsx-a11y": "^5.1.1",
"eslint-plugin-react": "^7.1.0",
"extract-text-webpack-plugin": "^2.1.0",
"html-webpack-plugin": "^2.28.0",
"jest": "^20.0.4",
"node-sass": "^4.5.3",
"react-addons-test-utils": "15.0.0-rc.2",
"react-test-renderer": "^15.5.4",
"sass-loader": "^6.0.5",
"style-loader": "^0.18.1",
"webpack": "^2.6.1",
"webpack-dev-server": "^2.4.5"
}
}
Webpack
import fs from 'fs'
import webpack from 'webpack'
import HtmlWebpackPlugin from 'html-webpack-plugin'
import ExtractTextPlugin from 'extract-text-webpack-plugin'
import CopyWebpackPlugin from 'copy-webpack-plugin'
import path from 'path'
import chalk from 'chalk'
const coinhover = path.resolve(__dirname, "coinhover")
const src = path.resolve(__dirname, "public/src")
const log = console.log
// https://gist.github.com/leongaban/dc92204454b3513e511645af98107775
const HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
template: __dirname + '/public/src/index.html',
filename: 'index.html',
inject: 'body'
})
const ExtractTextPluginConfig = new ExtractTextPlugin({
filename: "coinhover.css",
disable: false,
allChunks: true
})
const CopyWebpackPluginConfig = new CopyWebpackPlugin([{ from: "public/src/static", to: "static" }])
const PATHS = {
app: src,
build: coinhover,
}
const LAUNCH_COMMAND = process.env.npm_lifecycle_event
const isProduction = LAUNCH_COMMAND === 'production'
process.env.BABEL_ENV = LAUNCH_COMMAND
const productionPlugin = new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production')
}
})
const base = {
entry: [
PATHS.app
],
output: {
path: PATHS.build,
filename: 'index_bundle.js'
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: ["babel-loader"]
},
{
test: /\.scss$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: ["css-loader", "sass-loader"],
publicPath: coinhover
})
}
],
loaders: [
{ test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' },
{ test: /\.css$/, loader: 'style-loader!css-loader' }
]
},
resolve: {
modules: ['node_modules', path.resolve(__dirname, 'public/src')]
}
}
const developmentConfig = {
devServer: {
publicPath: "",
contentBase: path.join(__dirname, "dist"),
// hot: false,
quiet: true,
inline: true,
compress: true,
stats: "errors-only",
open: true
},
devtool: 'cheap-module-inline-source-map',
plugins: [
CopyWebpackPluginConfig,
ExtractTextPluginConfig,
HtmlWebpackPluginConfig,
// new webpack.HotModuleReplacementPlugin()
]
}
const productionConfig = {
devtool: 'cheap-module-source-map',
plugins: [
CopyWebpackPluginConfig,
ExtractTextPluginConfig,
HtmlWebpackPluginConfig,
productionPlugin
]
}
log(`${chalk.magenta('🤖 ')} ${chalk.italic.green('npm run:')} ${chalk.red(LAUNCH_COMMAND)}`)
export default Object.assign({}, base,
isProduction === true ? productionConfig : developmentConfig
)
You can add an option to ignore case:
"rules": {
"import/no-unresolved": [
2,
{ "caseSensitive": false }
]
}
This thread at github also describes how the linter was checking case for parts of the path which come before the folder containing package.json. If you for example have the path:
C:/Workspace/app and you navigate to it using cd C:/workspace/app (lowercase workspace), the linter would also give an error on the imports. Looks like it should now be fixed, but perhaps you are still using an older version.
Try installing eslint-import-resolver-webpack and adding this to your .eslintrc:
"settings": {
"import/resolver": "webpack"
}
Try
resolve: {
modules: [path.resolve(__dirname, 'public/src'), 'node_modules', path.resolve('node_modules')],
}
it helped me
If you would like to enable this rule, then:
Enable the rule within your config: 'import/no-unresolved': 'error'
Install and configure the TypeScript import resolver: eslint-import-resolver-typescript
The problem is that your webpack config is written in ES6 format, which doesn't play well with eslint-import-resolver-webpack.
So, you either refactor your webpack.config.js using ES5 syntax, or you get rid of eslint-import-resolver-webpack.
See here for the full solution: eslint plugin docs

Why the 'Error: Couldn't find preset "react-hot" relative to directory..." in ReactJS for React Hot Loader?

I am trying to get React Hot Reloader to work for my ReactJS project, but I am getting an error Error: Couldn't find preset "react-hot" relative to directory...
I did set up preset "react-hot" in .babelrc but what may be the issue? I have the following set up:
In my package.json:
{
"name": "practicing_client",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node ./node_modules/webpack-dev-server/bin/webpack-dev-server.js"
},
"author": "John Bana",
"license": "ISC",
"dependencies": {
"axios": "^0.14.0",
"react": "^15.3.1",
"react-cookie": "^0.4.8",
"react-dom": "^15.3.1",
"react-redux": "^4.4.5",
"react-router": "^2.7.0",
"redux": "^3.6.0",
"redux-form": "^6.0.0-rc.3",
"redux-thunk": "^2.1.0"
},
"devDependencies": {
"babel-core": "^6.14.0",
"babel-loader": "^6.2.5",
"babel-preset-es2015": "^6.14.0",
"babel-preset-react": "^6.11.1",
"babel-preset-stage-0": "^6.5.0",
"css-loader": "^0.25.0",
"extract-text-webpack-plugin": "^1.0.1",
"node-sass": "^3.9.3",
"react-hot-loader": "^3.0.0-beta.3",
"sass-loader": "^4.0.1",
"style-loader": "^0.13.1",
"webpack": "^1.13.2",
"webpack-dev-server": "^1.15.1"
}
}
In my webpack.config.js
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const config = {
context: __dirname,
entry: './src/index.js',
output: {
path: __dirname,
filename: 'bundle.js'
},
module: {
loaders: [{
exclude: /node_modules/,
test: /\.(js|jsx)$/,
loader: 'babel'
},
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract('css!sass')
}]
},
devServer: {
historyApiFallback: true,
contentBase: './'
},
plugins: [
new webpack.DefinePlugin({ 'process.env':{ 'NODE_ENV': JSON.stringify('production') } }),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.optimize.UglifyJsPlugin({
compress: { warnings: false },
output: {comments: false },
mangle: false,
sourcemap: false,
minimize: true,
mangle: { except: ['$super', '$', 'exports', 'require', '$q', '$ocLazyLoad'] }
}),
]
};
module.exports = config;
In my .babelrc:
{
"presets": ["react-hot", "react", "es2015", "stage-0"]
}
react-hot-loader isn't used by Babel, it's used by Webpack.
Remove react-hot from your Babel presets, then add the loader to your Webpack configuration file:
loaders: [{
exclude: /node_modules/,
test: /\.(js|jsx)$/,
loaders: ['react-hot', 'babel']
},

Categories

Resources