"You may need an appropriate loader" in React and Webpack - node.js

I've been trying to use react js with webpack, but when doing "npm run build" I get the following:
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| import ReactDOM from 'react-dom';
| const Index = () => {
> return <div>Welcome to React!</div>;
| };
| ReactDOM.render(<Index />, document.getElementById('app'));
# multi ./src/index.js ./src/scss/main.scss main[0]
I don't know what happens, when I start the application with "npm start" if the text comes out. Then I leave my webpack configuration file and the .babelrc.
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
},
}
]
},
My code react:
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
const Index = () => {
return <div>Welcome to React!</div>;
};
ReactDOM.render(<Index />, document.getElementById('app'));

From the chat, you have in your webpack.config.js:
module.exports = {
//...
// cargadores, los que transpilan tal formato en otro aceptable por los navegadores
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
},
}
]
},
module: {
rules: [
{
test: /\.(sa|sc|c)ss$/,
use: [production ? MiniCSSExtractPlugin.loader : 'style-loader', 'css-loader', 'sass-loader'],
},
{
test: /\.(png|jpg|gif)$/,
use: [
{
loader: 'file-loader',
options: {
name: 'images/[name].[ext]',
publicPath: '../'
}
}
]
},
{
test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
use: [
{
loader: 'file-loader',
options: {
name: 'fonts/[name].[ext]',
outputPath: '../'
}
}
]
},
]
}
};
//...
You have duplicate module fields and should combine them into
module.exports = {
// cargadores, los que transpilan tal formato en otro aceptable por los navegadores
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
},
},
{
test: /\.(sa|sc|c)ss$/,
use: [production ? MiniCSSExtractPlugin.loader : 'style-loader', 'css-loader', 'sass-loader'],
},
{
test: /\.(png|jpg|gif)$/,
use: [
{
loader: 'file-loader',
options: {
name: 'images/[name].[ext]',
publicPath: '../'
}
}
]
},
{
test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
use: [
{
loader: 'file-loader',
options: {
name: 'fonts/[name].[ext]',
outputPath: '../'
}
}
]
},
]
}
};

I don't know how your babel config file looks like but, you probably should try this:
webpack.config.js
module: {
rules: [
{
test: /\.jsx$|\.js$/,
exclude: /node_modules/,
loader: "babel-loader",
options: {
presets: ["#babel/preset-env", "#babel/preset-react"]
}
}
]
}
.babelrc
{
"presets": ["#babel/env", "#babel/react"]
}
This should work fine.

Related

FLUSH CHUNKS warning occurs with TSX, but not with JS

I get this warning:
[FLUSH CHUNKS]: Unable to find styles/localhost-theme-css in Webpack chunks. Please check usage of Babel plugin.
Following code causes the warning (for the setup of react-universal-component, which does server side rendering with code-splitting which reads only necessary CSS file for the page and domain being read by the user):
export default (props) => {
if (props.site !== undefined) {
import(`../styles/${props.site}/theme.css`);
}
Above code is in Routes.tsx, whole file looks like:
import React from "react"
import universal from "react-universal-component"
import { Switch } from "react-router"
const determineHowToLoad = ({ page }) => {
if (typeof page !== 'string') {
return page();
} else {
return import(`./${page}`);
}
}
const UniversalComponent = universal(determineHowToLoad, {
loadingTransition: false
})
export default (props) => {
if (props.site !== undefined) {
import(`../styles/${props.site}/theme.css`);
}
return (
<div>
Test
</div>
)
}
However, this happens only if when the filename is Routes.tsx. If I change to Routes.js, no warning occurs. Even with the warning and filename being Routes.tsx, all the things looks working well but only warning occurs in console terminal.
My webpack setting:
1. webpack.dev-client.js:
optimization: {
splitChunks: {
chunks: "initial",
cacheGroups: {
vendors: {
test: /[\\/]node_modules[\\/]/,
name: "vendor"
}
}
}
},
devtool: "source-map",
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: [
{
loader: "babel-loader"
}
]
},
{
test: /\.(ts|tsx)$/,
exclude: /node_modules/,
use: [
{
loader: "ts-loader"
}
]
},
{
test: /\.(js|jsx)$/,
use: 'react-hot-loader/webpack',
include: /node_modules/
},
{
test: /\.css$/,
use: [
ExtractCssChunks.loader, "css-loader",
]
},
....
resolve: {
extensions: [".ts", ".tsx", ".js", ".css"]
},
2. webpack.dev-server.js:
devtool: "inline-source-map",
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: [
{
loader: "babel-loader"
}
]
},
{
test: /\.(ts|tsx)$/,
exclude: /node_modules/,
use: [
{
loader: "ts-loader"
}
]
},
{
test: /\.css$/,
use: [
ExtractCssChunks.loader, "css-loader"
]
},
....
resolve: {
extensions: [".ts", ".tsx", ".js", ".css"]
},
How can I solve it so that I can use tsx without FLUSH CHUNKS warning?
Try setting the module to "EsNext" in tsconfig.json, I had the similar issue changing to "EsNext" solved it for me.

hot reload pug with webpack

I created a web application and i'm generating my index.html with a pug file.
The pug template needs to get data from a json file, and so far I managed to inject the data with both pug-loader and pug-html-loader.
The problem comes when I run the application with hot-reloading (using webpack-hot-middleware). the application dosen't reload when I change the json file, which is really annoying because any other file change triggers a reload, and I don't want to restart the application manually everytime I change the json file.
this is my webpack configuration:
{
context: '/src',
entry: 'index.js',
output: {
filename: 'index.js',
path: '/dist'
},
resolve: {
extensions: ['.js', '.vue', '.scss', 'json'],
alias: {
'vue$': 'vue/dist/vue.esm.js',
'#': config.pwd,
}
},
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
scss: [
'style-loader',
'css-loader',
'sass-loader',
{
loader: 'sass-resources-loader',
options: {
resources: ['./src/variables.scss', './src/mixins.scss']
}
}
]
}
}
},
{
test: /\.scss$/,
use: [
'style-loader',
'css-loader',
'sass-loader',
{
loader: 'sass-resources-loader',
options: {
resources: ['./src/variables.scss', './src/mixins.scss']
}
}
]
},
{
test: /\.pug$/,
use: [
{
loader: 'pug-loader',
options: {}
}
]
}
]
},
{
[
new HtmlWebpackPlugin({
template: 'index.pug',
inject: true,
data: require('./pug.json')
})
]
}
}
does any one know how i can make a change in pug.json trigger a hot reload?

Webpack semantic-ui-less Module build failed

I have been following various tutorials on importing semantic-ui-less into a webpack project.
However, whenever I have completed the different tutorials I am getting the same error:
Module build failed:
module.exports = __webpack_public_path__ + "static/media/reset.b0bc6c14.less";
^
Unrecognised input
in /Users/benflowers/Projects/candidate/candidate-ui-cra/node_modules/semantic-ui-less/definitions/globals/reset.less (line 1, column 15)
Is this an issue with my webpack config - I have an ejected create-react-app webpack config with some additional loaders:
{
test: /\.less$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
{ loader: 'css-loader' },
{ loader: 'less-loader' }
]
}),
exclude: [/[\/\\]node_modules[\/\\]semantic-ui-less[\/\\]/]
},
// for semantic-ui-less files:
{
test: /\.less$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
{ loader: 'css-loader' },
{
loader: 'semantic-ui-less-module-loader',
// you can also add specific options:
options: { siteFolder: path.join(__dirname, 'src/site') }
}
]
}),
include: [/[\/\\]node_modules[\/\\]semantic-ui-less[\/\\]/]
},
// loader for static assets
{
test: /\.(png|jpg|jpeg|gif|svg)$/,
use: {
loader: 'url-loader',
options: {
limit: 10240,
absolute: true,
name: 'images/[path][name]-[hash:7].[ext]'
}
},
include: [path.join(__dirname, 'src'), /[\/\\]node_modules[\/\\]semantic-ui-less[\/\\]/]
}
as per https://github.com/gadyonysh/semantic-ui-less-module-loader
I had the similar issue.
I just added to webpack config
ALIAS
resolve: {
...
alias : {
'../../theme.config$': path.join( __dirname, '../src/assets/theme/theme.config' )
}
},
LESS LOADER
{
test: /\.less$/,
use : ExtractTextPlugin.extract( {
fallback: [ {
loader: 'style-loader',
} ],
use : [ 'css-loader', 'resolve-url-loader', 'less-loader', 'postcss-loader' ]
} )
},
and exclude
{
exclude: [
/\.(config|overrides|variables)$/,
/\.html$/,
/\.(js|jsx)$/,
/\.css$/,
/\.json$/,
/\.bmp$/,
/\.gif$/,
/\.jpe?g$/,
/\.png$/,
/\.scss$/,
],
loader: require.resolve( 'file-loader' ),
options: {
name: 'static/media/[name].[hash:8].[ext]',
},
},
please pay attention to line
/.(config|overrides|variables)$/,
Adding this to your less exclude should do the trick :
exclude: [/\.(js|jsx|mjs)$/, /\.html$/, /\.json$/, /\.(less|config|variables|overrides)$/],

Webpack suppress eslint warnings on browser console

I`ve finished configuring my eslint rules and refactoring project files according to my rules. Thing is that I have some warnings that I may want to leave there for a while. But my problem is that warnings are being shown on browser console, what makes development impossible.
Below, my webpack config:
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const context = path.resolve('.');
module.exports = {
context: context,
entry: './src/client.js',
output: {
path: path.join(context, 'build/client'),
publicPath: '/static/',
filename: '[name]-[hash].js'
},
module: {
preLoaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'eslint-loader'
},
],
loaders: [{
test: /(?:node_modules).+\.css$/,
loader: 'style!css'
}, {
test: /\.scss$/,
loader: ExtractTextPlugin.extract([
'css-loader',
'postcss-loader',
'sass-loader',
'sass-resources'
])
}, {
test: /\.js$/,
loader: 'babel',
exclude: /(node_modules)/
}, {
test: /\.woff(\?v=\d+\.\d+\.\d+)?$/,
loader: "url?limit=10000&mimetype=application/font-woff"
}, {
test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/,
loader: "url?limit=10000&mimetype=application/font-woff"
}, {
test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
loader: "url?limit=10000&mimetype=application/octet-stream"
}, {
test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
loader: "file"
}, {
test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
loader: "url?limit=10000&mimetype=image/svg+xml"
}, {
test: /\.json$/,
loader: 'json'
}]
},
postcss: function() {
return [
require('autoprefixer')
];
},
sassResources: [
path.resolve(__dirname, '../src/stylesheets/base/_variables.scss'),
path.resolve(__dirname, '../src/stylesheets/base/_mixins.scss')
],
devServer: {
watchOptions: {
aggregateTimeout: 1000
}
},
plugins: [
new ExtractTextPlugin("[name]-[hash].css"),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'local')
})
],
devtool: "cheap-module-source-map"
};
I have no problem with errors being displayed on browser console, but is there a way to suppress warnings ONLY on browser console and not on the node terminal?
https://devhub.io/repos/coryhouse-eslint-loader
In my webpack.config.js I have options setup:
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules)/,
use: [
{
loader: 'babel-loader',
options: {
presets: [
['es2015', {modules: false}],
'react'
],
plugins: [ 'react-hot-loader/babel' ]
}
}, {
loader: 'eslint-loader',
options: {
quiet: true
}
}
]
}
]
}
The last line is quiet: true, which is how it suppresses the warnings.
Use
clientLogLevel: "none"
in the devServer config
Doc: https://webpack.js.org/configuration/dev-server/#devserverclientloglevel
devServer.clientLogLevel
string: 'none' | 'info' | 'error' | 'warning'
When using inline mode, the console in your DevTools will show you messages e.g. before reloading, before an error or when Hot Module Replacement is enabled. Defaults to info.
devServer.clientLogLevel may be too verbose, you can turn logging off by setting it to 'none'.
webpack.config.js
module.exports = {
//...
devServer: {
clientLogLevel: 'none'
}
};
Usage via the CLI
webpack-dev-server --client-log-level none

Why is that I can import one npm package and not the other (Webpack setup)?

I'm importing two libraries in the exact same way (lodash and aframe):
The first one exports successfully:
error no-unused-vars "_" is defined but never used
E:\alex\istaging-viewer\src\components\Pano\PanoList.vue:10:8
import _ from 'lodash'
(Lodash is defined.)
For the second one, Webpack (or npm?) tells me there's no file or directory with that name:
ERROR in ./~/aframe/index.js
Module not found: Error: Cannot resolve 'file' or 'directory' ./package in E:\alex\istaging-viewer\node_modules\aframe
# ./~/aframe/index.js 3:10-30
ERROR in ./~/aframe/~/aframe-core/src/index.js
Module not found: Error: Cannot resolve 'file' or 'directory' ../package in E:\alex\istaging-viewer\node_modules\aframe\node_modules\aframe-core\src
# ./~/aframe/~/aframe-core/src/index.js 16:10-31
ERROR in ./~/aframe/elements/templates/index.html
Module parse failed: E:\alex\istaging-viewer\node_modules\aframe\elements\templates\index.html Line 1: Unexpected token <
You may need an appropriate loader to handle this file type.
| <!doctype html>
| <meta charset="utf-8">
|
# ./~/aframe/elements/index.js 7:0-33
Why is this?
NOTE: This is my Webpack setup:
var path = require('path')
module.exports = {
entry: {
app: './src/main.js'
},
output: {
path: path.resolve(__dirname, '../dist/static'),
publicPath: '/static/',
filename: '[name].js'
},
resolve: {
extensions: ['', '.js', '.vue', 'styl'],
alias: {
'src': path.resolve(__dirname, '../src')
}
},
resolveLoader: {
root: path.join(__dirname, 'node_modules')
},
module: {
preLoaders: [
{
test: /\.vue$/,
loader: 'eslint',
exclude: /node_modules/
},
{
test: /\.js$/,
loader: 'eslint',
exclude: /node_modules/
}
],
loaders: [
{
test: /\.vue$/,
loader: 'vue'
},
{
test: /\.js$/,
loader: 'babel',
exclude: /node_modules/
},
{
test: /\.json$/,
loader: 'json'
},
{
test: /\.(png|jpg|gif|svg)$/,
loader: 'url',
query: {
limit: 10000,
name: '[name].[ext]?[hash:7]'
}
},
{ test: /\.styl$/, loader: 'style-loader!css-loader!stylus-loader' },
{ test: /\.(woff|woff2)$/, loader: "url-loader?limit=10000&mimetype=application/font-woff" },
{ test: /\.ttf$/, loader: "file-loader" },
{ test: /\.eot$/, loader: "file-loader" },
{ test: /\.svg$/, loader: "file-loader" }
]
},
eslint: {
formatter: require('eslint-friendly-formatter')
}
}
According to error message and aframe source code you should specify appropriate loader for html files in your webpack config.
Not shure, but this can be suitable - https://github.com/webpack/html-loader or you can try url-loader
loaders: [
{
test: /\.vue$/,
loader: 'vue'
},
... skipped ...
{
test: /\.html$/,
loader: 'html'
},

Resources