Cannot start react module - reactjs

Getting the following exception when starting the npm.
Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
- configuration.module has an unknown property 'loaders'. These properties are valid:
object { exprContextCritical?, exprContextRecursive?, exprContextRegExp?, exprContextRequest?, noParse?, rules?, defaultRules?, unknownContextCritical?, unknownContextRecursive?, unknownContextRegExp?, unknownContextRequest?, unsafeCache?, wrappedContextCritical?, wrappedContextRecursive?, wrappedContextRegExp?, strictExportPresence?, strictThisContextOnImports? }
-> Options affecting the normal modules (NormalModuleFactory).
var path= require('path');
module.exports = {
entry : './script.jsx',
output : {
path : path.resolve(__dirname,''),
filename: 'transpiled.js'
},
module : {
loaders: [
{
test:/\.jsx?$/,
loaders:'babel-loader',
exclude : /node_modules/,
query : {
presets : ['es2015','react']
}
}
]
}
}
After the updations the code is running but react components are not getting rendered on the screen.
//Update
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test title</title>
</head>
<body>
<div id ="content">
<h1>This is the demo of your web page</h1>
</div>
<script src ="transpiled.js"></script>
</body>
</html>
//webpack config
var path= require('path');
module.exports = {
entry : './script.jsx',
output : {
path : path.resolve(__dirname,'react/index.html'),
filename: 'transpiled.js'
},
module : {
rules: [ // rules rules
{
test: /\.jsx?$/,
loaders: 'babel-loader',
//use:'babel-loader', // use here
exclude : /node_modules/,
query : {
presets : ['es2015','react']
}
}
]
}
}
//script.jsx
import React from 'react';
import ReactDOM from 'react-dom';
class MyComponent extends React.Component {
render() {
return (
<h2>Hello World !!!</h2>
);
}
}
ReactDom.render(
<MyComponent/>,document.getElementById('content')
);
//package.json
{
"name": "reactjs",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"it": "webpack-dev-server --hot"
},
"author": "chetan",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.4",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"webpack": "^4.5.0",
"webpack-cli": "^2.0.14",
"webpack-dev-middleware": "^3.1.2",
"webpack-dev-server": "^3.1.3",
"webpack-hot-middleware": "^2.21.2"
},
"dependencies": {
"react": "^16.3.1",
"react-dom": "^16.3.1",
"webpack-sources": "^1.1.0"
}
}

You need to replace keyword loaders to keyword rules. And in each rules object replace loaders to keyword use.
module.exports = {
entry : './script.jsx',
output : {
path : path.resolve(__dirname,''),
filename: 'transpiled.js'
},
module : {
rules: [ // rules rules
{
test:/\.jsx?$/,
use:'babel-loader', // use here
exclude : /node_modules/,
query : {
presets : ['es2015','react']
}
}
]
}
}
Edit
Now your component not rendered on the screen because output.path in webpack config incorrect. It should be like this:
output : {
path : path.resolve(__dirname),
filename: 'transpiled.js'
}
Because script tag in your html reference in root of the project:
<script src="transpiled.js"></script>

Your webpack.config file is in the wrong format
var path = require('path');
module.exports = {
entry: './script.jsx',
output: {
path: path.resolve(__dirname, ''),
filename: 'transpiled.js'
},
module: {
rules: [
{
test: /\.jsx?$/,
loaders: 'babel-loader',
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
presets: [
'#babel/preset-env',
// your preset
]
}
}
]
}
]
}
}
See more here

Related

ReactJS: Importing symlinked components error: Module parse failed: Unexpected token: You may need an appropriate loader to handle this file type

I'm writing a React component library which I want to use in other projects without much overhead ( bit, create-react-library, generact, etc. ) and without publishing. I want to use npm install ../shared_lib to add it to my project as a symlink in /node_modules. This command adds the symlink to project node_modules. In my shared_lib I just have a test to export default a <div></div>:
import React from 'react';
const TryTest = function() {
return (
<div>
TryTest
</div>
)
}
export default TryTest;
The problem I'm facing is the following error when I import the component into my working project:
import TryTest from 'shared_lib';
Error:
ERROR in ../shared_lib/src/index.js 6:4
Module parse failed: Unexpected token (6:4)
You may need an appropriate loader to handle this file type.
| const TryTest = function() {
| return (
> <div>
| TryTest
| </div>
# ./src/App.js 27:0-33 28:12-19
# ./src/index.js
# multi babel-polyfill ./src/index.js
If I import anything from shared_lib other than a file with jsx - for example, a string or a function, etc. - it works fine.
EDIT: the application webpack has resolve object's symlinks prop set to false:
resolve: {
symlinks: false
},
EDIT: After applying the solution in the answer below (https://stackoverflow.com/a/60980492/3006493), I later changed symlinks prop back to true. I didn't need to set it to false for the solution to work and render shared_lib components.
My app's loader:
{
test: /\.jsx?$/,
include: [
path.join( __dirname, 'src'), // app/src
fs.realpathSync(__dirname + '/node_modules/shared_lib'), // app/node_modules/shared_lib/dist/shared_lib.js
],
exclude: /node_modules/,
use: [ 'babel-loader' ]
}
EDIT: When I applied the solution in the answer below, the loader now looks like this:
{
test: /\.jsx?$/,
include: [
path.join( __dirname, 'src'), // app/src
fs.realpathSync(__dirname + '/node_modules/shared_lib'), // app/node_modules/shared_lib/dist/shared_lib.js
],
exclude: /node_modules/,
use: [ {
loader: 'babel-loader',
options: require("./package.json").babel
}
]
}
App's current .babelrc settings (I also tried removing .babelrc and including the presets in package.json with same result):
{
"presets": [ "#babel/preset-react", "#babel/preset-env"]
}
**EDIT: After applying the solution in the answer below, I ended up putting babel presets back into package.json.
"babel": {
"presets": [
"#babel/preset-react",
"#babel/preset-env"
]
},
I researched for a while to find a solution to this and apparently webpack has issues bundling symlinked react components? I am not using create-react-app.
So, I tried to bundle the shared_lib before importing it into the project, just to see what would happen. Here's the final webpack config (I tried other configurations as well):
const pkg = require('./package.json');
const path = require('path');
const buildPath = path.join( __dirname, 'dist' );
const clientPath = path.join( __dirname, 'src');
const depsPath = path.join( __dirname, 'node_modules');
const libraryName = pkg.name;
module.exports = [
'cheap-module-source-map'
].map( devtool => ({
bail: true,
mode: 'development',
entry: {
lib : [ 'babel-polyfill', path.join( clientPath, 'index.js' ) ]
},
output: {
path: buildPath,
filename: 'shared_lib.js',
libraryTarget: 'umd',
publicPath: '/dist/',
library: libraryName,
umdNamedDefine: true
},
// to avoid bundling react
externals: {
'react': {
commonjs: 'react',
commonjs2: 'react',
amd: 'React',
root: 'React'
}
},
module: {
rules: [
{
test: /\.jsx?$/,
include: [
clientPath
],
exclude: /node_modules/,
use: [ 'babel-loader' ],
},
]
},
devtool,
optimization: {
splitChunks: {
chunks: 'all',
},
}
}));
And the package.json for the shared_lib
{
"name": "shared_lib",
"version": "1.0.0",
"description": "",
"main": "dist/shared_lib.js",
"scripts": {
"clean": "rm -rf dist/",
"build": "$(npm bin)/webpack --config ./webpack.config.js",
"prepublish": "npm run clean && npm run build"
},
"author": "",
"license": "ISC",
"peerDependencies": {
"react": "^16.8.6"
},
"devDependencies": {
"react": "^16.8.6",
"#babel/core": "^7.9.0",
"#babel/preset-env": "^7.9.0",
"#babel/preset-react": "^7.9.4",
"babel-loader": "^8.1.0",
"babel-polyfill": "^6.26.0",
"webpack": "^4.42.1",
"webpack-cli": "^3.3.11"
},
"babel": {
"presets": [
"#babel/preset-react",
"#babel/preset-env"
]
}
}
The package is bundled without errors:
When I try to import the component in the same way:
import TryTest from 'shared_lib';
The console.log returns undefined.
The path to the library file in my app is fine, because if I erase everything in shared_lib/dist/shared_lib.js and just write export default 1 the console.log(TryTest) in my App.js will return 1.
I tried changing libraryTarget property in shared_lib/webpack.config to libraryTarget: 'commonjs'. The result of console.log(TryTest) becomes {shared_lib: undefined}.
Has anyone ever run into this?
I found what finally worked for me and rendered the symlinked shared_lib to the app.
This answer: https://github.com/webpack/webpack/issues/1643#issuecomment-552767686
Worked well rendering symlinked shared_lib components. I haven't discovered any drawbacks from using this solution, but it's the only one that worked so far.

Module parse failed using Webpack

Hi I am student developer. I facing an error like this
ERROR in ./src/index.js 5:16 Module parse failed: Unexpected token
(5:16) 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 App from
'../src/components/App' |
ReactDOM.render(,document.getElementById("app")); i 「wdm」: Failed to compile.
I am starting to learn webpack what it is but I do not have enough information about solving this. Could you help me at this issue to solve ?
package.json Dev Part :
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^8.0.6",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"html-webpack-plugin": "^3.2.0",
"webpack": "^4.42.0",
"webpack-cli": "^3.3.11",
"webpack-dev-server": "^3.10.3"
}
My webconfig :
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.export = {
entry : './src/index.js',
output : {
path:path.join(__dirname,'/dist') ,
filename:'index_bundle.js'
},
module:{
rules : [{
test : /\.js$/,
exclude: /node_modules/,
use : {
loader : 'babel-loader'
}
}]
},
plugins: [
new HtmlWebpackPlugin({
template:'./src/index.html'
})
]
}
index.js
import React from 'react';
import ReactDOM from 'react-dom'
import App from '../src/components/App'
// Error is he
ReactDOM.render(<App />,document.getElementById("app"));
App.js:
import React, { Component } from 'react';
class App extends Component {
render() {
return (
<div>
<h1>Hello</h1>
</div>
);
}
}
export default App;
There are two mistakes in your webpack configuration, which is causing this issue.
There is a typo error. Change module.export to module.exports (This one drive me crazy man :P)
As #Muhammad mentioned, you need to mention webpack to compile the react. So, I have added '#babel/react' as presets for the babel-loader.
Below is the webpack that is working for me:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
entry : './src/index.js',
output : {
path:path.join(__dirname,'/dist') ,
filename:'index_bundle.js'
},
module:{
rules : [{
test : /\.js$/,
exclude: /node_modules/,
loader: "babel-loader",
options: {
presets: [
'#babel/react',
]
}
}]
},
plugins: [
new HtmlWebpackPlugin({
template:'./src/index.html'
})
]
}
Hope it helps :)
You need to tell webpack that you are compiling react. You need to update your rule as:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
entry : './src/index.js',
output : {
path:path.join(__dirname,'/dist') ,
filename:'index_bundle.js'
},
module:{
rules : [{
test: /\.js?$/,
exclude: /node_modules/,
loader: "babel-loader",
query: {
presets: ["react"]
}
}]
},
plugins: [
new HtmlWebpackPlugin({
template:'./src/index.html'
})
]
}

bundle.js still contains arrow function and default parameters after using babel pollyfill

I have added many settings given by Babel or others from stack overflow but the new features of ES6 such as arrow function and default parameter are still in my bundle.js
The bundle.js has content like below:
var nn = function(e={}) {
const {baseClasses: t, newClasses: n, Component: r} = e;
if (!n)
return t;
const a = At()({}, t);
return Object.keys(n).forEach(e=>{
n[e] && (a[e] = `${t[e]} ${n[e]}`)
}
),
a
};
As a result, when I open my page in IE11, the error missing ')' happened which point to function(e={}).
Here is my webpack.config.js:
const entries = require("./config/pages").reduce(function(map, page) {
map[page] = `./src/${page}/index.js`;
return map;
}, {});
module.exports = {
mode: 'development',
entry: ["#babel/polyfill",...entries],
output: {
path: path.resolve(__dirname,'dist'),
publicPath: '/',
filename: 'myapp/static/js/[name]/bundle.js'
},
devtool: 'source-map',
module: require("./config/loaders"),
devServer:{
open: true,
publicPath: '/',
historyApiFallback: true,
disableHostCheck: true
},
plugins: [
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css"
}),
new webpack.ProvidePlugin({
fetch: "isomorphic-fetch",
})
]
};
and ./config/loaders for module
module.exports = {
rules: [
{
test: /\.(js|jsx)$/,
// exclude: /node_modules/,
loader: 'babel-loader',
},
{
test: /\.(css|less)$/,
use: ["style-loader", "css-loader", "less-loader"]
},
{
test: /\.(png|jpg|gif)$/,
use: [
{
loader: 'url-loader',
options: {
limit: 500, //small than 500 use url, otherwise use base64
outputPath:'inquiry/static/img/'
}
}
]
},
{
test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
use: [{
loader: 'file-loader',
options: {
outputPath: 'myapp/static/fonts/'
}
}]
}
]
};
the .babelrc:
{
"presets": [
// ["#babel/env",
// {
// "targets": {
// "browsers": "ie 11"
// },
// "useBuiltIns": "usage",
// "corejs": "3.0.1",
// }
// ],
["#babel/preset-env",
{
"useBuiltIns": "entry",
"corejs": "3.0.1",
}],
"#babel/react"
],
"plugins": [
["#babel/transform-runtime"],
["#babel/plugin-transform-parameters"],
["#babel/plugin-transform-arrow-functions"],
[
"#babel/plugin-proposal-decorators",
{
"legacy": true
}
],
[
"#babel/plugin-proposal-class-properties",
{
"loose": true
}
],
]
}
Also, I have imported '#babel/polyfill' in my index.js
PS: I have noticed that the code contains ES6 features is from Meterial UI lib in node_modules, so I deleted exclude: /node_modules/, in babel loader rule but it still does not work.
I am using webpack 5, and setting target to es5 in webpack.config.js solved the problem for me.
module.exports = {
target: 'es5',
...
}
We are targeting specific browsers in the #babel/preset-env plugin, defined in the babel.config.js (which is a another way of declaring the babel configuration).
presets: [
[
'#babel/preset-env',
{
modules: 'commonjs',
useBuiltIns: 'entry',
targets: {
chrome: '58',
firefox: '54',
ie: '11',
safari: '10',
opera: '44',
edge: '16'
}
}
],
[
'#babel/preset-react'
]
],
plugins: [
'#babel/plugin-syntax-dynamic-import',
'#babel/plugin-proposal-class-properties'
]
Please try the target declaration like I posted above.
We use babel/preset-env 7.3.1 and it's corejs is not a top-level config option.
Update
I was able to make it work with a test project of which I tried to match your setup as best as possible. You can use this to slowly add complexity and modules that you use in your project to isolate the problem. This basic setup matches yours and works well. You can use this as a starting point.
package.json
{
"name": "babel-transprile-error",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"dependencies": {
"#babel/core": "^7.4.3",
"#babel/plugin-proposal-class-properties": "^7.4.0",
"#babel/plugin-proposal-decorators": "^7.4.0",
"#babel/plugin-transform-arrow-functions": "^7.2.0",
"#babel/plugin-transform-parameters": "^7.4.3",
"#babel/plugin-transform-runtime": "^7.4.3",
"#babel/polyfill": "^7.4.3",
"#babel/preset-env": "^7.4.3",
"#babel/preset-react": "^7.0.0",
"#babel/runtime": "^7.4.3",
"babel-loader": "^8.0.5",
"mini-css-extract-plugin": "^0.6.0",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"webpack": "^4.30.0",
"webpack-cli": "^3.3.1"
}
}
webpack.config.js
const path = require('path');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const webpack = require('webpack');
module.exports = {
mode: 'development',
entry: ["#babel/polyfill", './src/page/index.js'],
output: {
path: path.resolve(__dirname,'dist'),
publicPath: '/',
filename: 'myapp/static/js/[name]/bundle.js'
},
devtool: 'source-map',
module: require("./config/loaders.js"),
devServer:{
open: true,
publicPath: '/',
historyApiFallback: true,
disableHostCheck: true
},
plugins: [
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css"
}),
new webpack.ProvidePlugin({
fetch: "isomorphic-fetch",
})
]
};
.babelrc
{
"presets": [
// ["#babel/env",
// {
// "targets": {
// "browsers": "ie 11"
// },
// "useBuiltIns": "usage",
// "corejs": "3.0.1",
// }
// ],
["#babel/preset-env",
{
"useBuiltIns": "entry",
"corejs": "3.0.1",
}],
"#babel/react"
],
"plugins": [
["#babel/transform-runtime"],
["#babel/plugin-transform-parameters"],
["#babel/plugin-transform-arrow-functions"],
[
"#babel/plugin-proposal-decorators",
{
"legacy": true
}
],
[
"#babel/plugin-proposal-class-properties",
{
"loose": true
}
],
]
}
src/page/index.js
import React, { Component } from 'react';
class someComponent extends React.Component {
constructor(props) {
super(props);
}
method(e = {}) {
console.log(e);
var nn = function(e={}) {
const {baseClasses: t, newClasses: n, Component: r} = e;
if (!n)
return t;
const a = At()({}, t);
return Object.keys(n).forEach(e=>{
n[e] && (a[e] = `${t[e]} ${n[e]}`)
}
), a
};
}
render() {
return (
<div onClick={ e => { this.method(e) }}/>
)
}
}
export default someComponent;
config/loaders.js
module.exports = {
rules: [
{
test: /\.(js|jsx)$/,
// exclude: /node_modules/,
loader: 'babel-loader',
},
{
test: /\.(css|less)$/,
use: ["style-loader", "css-loader", "less-loader"]
},
{
test: /\.(png|jpg|gif)$/,
use: [
{
loader: 'url-loader',
options: {
limit: 500, //small than 500 use url, otherwise use base64
outputPath:'inquiry/static/img/'
}
}
]
},
{
test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
use: [{
loader: 'file-loader',
options: {
outputPath: 'myapp/static/fonts/'
}
}]
}
]
};
In my case, it caused by some packages that contains default parameters. So I fixed that by include node_modules in babel-loader:
{
test: /\.(jsx?)$/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/env', '#babel/react'],
plugins: [
'#babel/plugin-transform-runtime',
[
'#babel/plugin-proposal-class-properties',
{
loose: true
}
],
['#babel/plugin-proposal-export-default-from'],
'#babel/plugin-transform-parameters'
]
}
}
/** Include the node_modules folder to fix !! **/
// exclude: /node_modules/ // <== Here is the magic works !
},

Configuring next.config file

I am using Next.js and want to add the react-semantic-ui, to use one of their login components.
On the front-end I am getting this error:
Failed to compile
./node_modules/semantic-ui-css/semantic.min.css
ModuleParseError: Module parse failed: Unexpected character '' (1:0)
You may need an appropriate loader to handle this file type.
(Source code omitted for this binary file)
This is the login component:
import React from 'react'
import { Button, Form, Grid, Header, Image, Message, Segment } from 'semantic-ui-react'
const Login = () => (
/* login JSX markup */
)
export default Login
This is my next.config.js
module.exports = {
webpack: (config, { dev }) => {
config.module.rules.push(
{
test: /\.css$/,
loader: 'style-loader!css-loader'
},
{
test: /\.s[a|c]ss$/,
loader: 'sass-loader!style-loader!css-loader'
},
{
test: /\.(png|svg|eot|otf|ttf|woff|woff2)$/,
use: {
loader: "url-loader",
options: {
limit: 100000,
publicPath: "./",
outputPath: "static/",
name: "[name].[ext]"
}
}
},
{
test: [/\.eot$/, /\.ttf$/, /\.svg$/, /\.woff$/, /\.woff2$/],
loader: require.resolve('file-loader'),
options: {
name: '/static/media/[name].[hash:8].[ext]'
}
}
)
return config
}
}
const withCSS = require('#zeit/next-css')
module.exports = withCSS()
This is my package.js
{
"name": "create-next-example-app",
"scripts": {
"dev": "nodemon server/index.js",
"build": "next build",
"start": "NODE_ENV=production node server/index.js"
},
"dependencies": {
"#zeit/next-css": "^1.0.1",
"body-parser": "^1.18.3",
"cors": "^2.8.5",
"express": "^4.16.4",
"mongoose": "^5.4.19",
"morgan": "^1.9.1",
"next": "^8.0.3",
"react": "^16.8.4",
"react-dom": "^16.8.4",
"semantic-ui-css": "^2.4.1",
"semantic-ui-react": "^0.86.0"
},
"devDependencies": {
"css-loader": "^2.1.1",
"file-loader": "^3.0.1",
"node-sass": "^4.11.0",
"nodemon": "^1.18.10",
"sass-loader": "^7.1.0",
"url-loader": "^1.1.2"
}
}
I read somewhere you have to include a _document.js in the pages directory.
// _document is only rendered on the server side and not on the client side
// Event handlers like onClick can't be added to this file
// ./pages/_document.js
import Document, { Html, Head, Main, NextScript } from 'next/document';
class MyDocument extends Document {
static async getInitialProps(ctx) {
const initialProps = await Document.getInitialProps(ctx);
return { ...initialProps };
}
render() {
return (
<Html>
<Head>
<link rel='stylesheet'
href='//cdn.jsdelivr.net/npm/semantic-ui#2.4.2/dist/semantic.min.css'
/>
</Head>
<body className="custom_class">
<Main />
<NextScript />
</body>
</Html>
);
}
}
export default MyDocument;
Is this really this hard?
Update
There is an alternate way of getting this to work.
When you start up your Next app you get a components folder which includes a head.js and a nav.js file.
The head.js file ultimately is analogous to a <head></head> tag in HTML. Or I should say that's what the head.js compiles to. ANYWAY, you can just add this in there:
<link
rel="stylesheet"
href="//cdn.jsdelivr.net/npm/semantic-ui#2.4.2/dist/semantic.min.css"
/>
and that will work.
But like I said you still can't import the modules like so:
import 'semantic-ui-css/semantic.min.css'
In case someone uses next-compose-plugins and getting the above error, here's a fix:
const withCSS = require('#zeit/next-css');
const withImages = require('next-images');
const withPlugins = require('next-compose-plugins');
// fix: prevents error when .css files are required by node
if (typeof require !== 'undefined') {
require.extensions['.css'] = (file) => {};
}
const nextConfig = {
target: 'server',
webpack: (config, { dev }) => {
config.module.rules.push({
test: /\.(raw)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
use: 'raw-loader'
});
return config;
}
};
module.exports = withPlugins([withImages, withCSS({target: 'serverless',
webpack (config) {
config.module.rules.push({
test: /\.(png|svg|eot|otf|ttf|woff|woff2)$/,
use: {
loader: 'url-loader',
options: {
limit: 8192,
publicPath: '/_next/static/',
outputPath: 'static/',
name: '[name].[ext]'
}
}
})
return config
}})], nextConfig);
So it looks like I had to do the following to get this to work:
Changing my next.config.js file to:
const withCSS = require('#zeit/next-css')
module.exports = withCSS({
webpack: function (config) {
config.module.rules.push({
test: /\.(eot|woff|woff2|ttf|svg|png|jpg|gif)$/,
use: {
loader: 'url-loader',
options: {
limit: 100000,
name: '[name].[ext]'
}
}
})
return config
}
})
And doing an npm i css-loader file-loader url-loader -D did the trick.
However I'm baffled as to why css-loader file-loader are needed? I'm used to webpack configs where you are explicitly adding the loaders (Like we are adding the url-loader above)... I didn't have to here!

Missing Loader, Webpack and React

I am building an application using Reactstrap and Webpack. I am struggling with Webpack and React. I am tring to run my react-dev server but I am running into this error in my terminal:
ericpark-macbookpro3:mvp ericpark$ npm run react-dev
> github-fetcher-fullstack-v2#1.0.0 react-dev /Users/ericpark/Desktop/mvp
> webpack -d --watch
Webpack is watching the files…
Hash: d1e3cad44a718dd4af71
Version: webpack 2.7.0
Time: 64ms
Asset Size Chunks Chunk Names
bundle.js 3.35 kB 0 [emitted] main
[0] ./react-client/src/index.jsx 298 bytes {0} [built] [failed] [1 error]
ERROR in ./react-client/src/index.jsx
Module parse failed: /Users/ericpark/Desktop/mvp/react-client/src/index.jsx Unexpected token (61:6)
You may need an appropriate loader to handle this file type.
| render() {
| return (
| <div className="App">
| <Navbar></Navbar>
| <Container>
It looks like I am missing a loader. Here is my webpack.config.js
var path = require('path');
var SRC_DIR = path.join(__dirname, '/react-client/src');
var DIST_DIR = path.join(__dirname, '/react-client/dist');
module.exports = {
entry: `${SRC_DIR}/index.jsx`,
output: {
filename: 'bundle.js',
path: DIST_DIR
},
module : {
rules: [
{
test: /\.css$/,
use: [ 'style-loader', 'css-loader' ]
}
],
loaders : [
{
test : /\.jsx?/,
include : SRC_DIR,
loader : 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['env', 'react', 'es2015', 'stage-0']
}
}
]
}
};
Here is my starting file index.jsx as well:
import React, { Component } from 'react';
import Navbar from './components/Navbar.jsx';
import Login from './components/Login.jsx';
import SignUp from './components/SignUp.jsx';
import Search from './components/Search.jsx';
import ProductList from './components/ProductList.jsx';
import FavoriteList from './components/FavoriteList.jsx';
import { Route, Switch } from 'react-router-dom';
import {Container} from 'reactstrap';
import axios from 'axios';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import './App.css';
class App extends Component {
constructor() {
super();
this.state = {
query : '',
products : [
{
name: 'Samsung - Galaxy J3 with 16GB Memory Cell Phone - Silver (AT&T)',
url: 'https://api.bestbuy.com/click/-/5887123/pdp',
price: 179.99,
image: 'https://img.bbystatic.com/BestBuy_US/images/products/5887/5887123_sd.jpg',
description: 'Android 7.0 Nougat4G LTE5" HD touch screenBluetooth'
},
{
name: 'Samsung - Book Cover for Samsung Galaxy Tab S2 8 - Black',
url: 'https://api.bestbuy.com/click/-/4346001/pdp',
price: 59.99,
image: 'https://img.bbystatic.com/BestBuy_US/images/products/4346/4346001_sd.jpg',
description: 'Compatible with Samsung Galaxy Tab S2 8; polyurethane material; auto on/off function; 3 viewing angles'
},
{
name: 'Samsung - Case for Samsung Galaxy S8 - Blue/clear',
url: 'https://api.bestbuy.com/click/-/5851701/pdp',
price: 19.99,
image: 'https://img.bbystatic.com/BestBuy_US/images/products/5851/5851701_sb.jpg',
description: 'Compatible with Samsung Galaxy S8'
}
],
favorites : []
}
}
handleQuery (event) {
event.preventDefault;
this.setState({
query : event.target.value
});
console.log(event.target.value);
//POST request for searching products
// axios.post('/search', {query : this.state.query}).then(function(response){
// this.setState = {products : response};
// })
}
render() {
return (
<div className="App">
<Navbar></Navbar>
<Container>
<Switch>
<Route path='/login' component={Login}/>
<Route path='/signup' component={SignUp}/>
<Route path='/' render = {(props) =>
<div>
<Search handleQuery = {this.handleQuery.bind(this)}></Search>
<ProductList products = {this.state.products}></ProductList>
</div>
}/>
<Route path='/favorites' render = {(props) =>
<FavoriteList favorites = {this.state.favorites}></FavoriteList>
}/>
</Switch>
</Container>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('app'));
Any help would be greatly appreciated
package.json
{
"name": "github-fetcher-fullstack-v2",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"react-dev": "webpack -d --watch",
"server-dev": "nodemon server/index.js"
},
"author": "Beth Johnson",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.4.5",
"babel-loader": "^6.2.1",
"babel-preset-es2015": "^6.3.13",
"babel-preset-react": "^6.23.0",
"css-loader": "^0.28.11",
"react-hot-loader": "^4.1.2",
"webpack": "^2.7.0"
},
"dependencies": {
"angular": "^1.6.3",
"body-parser": "^1.17.2",
"bootstrap": "^4.1.0",
"express": "^4.15.0",
"jquery": "^3.1.1",
"mongoose": "^4.8.6",
"mysql": "^2.13.0",
"react": "^15.4.2",
"react-dom": "^15.4.2",
"reactstrap": "^5.0.0"
}
}
Seems like Webpack config has a small problem and jsx files are not matched with appropriate loaders.
Try test: /\.jsx?$/, and see if it works.
You can easily fix by updating your config to process both .js and .jsx files:
module: {
loaders: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loader: "babel-loader"
}
]
}
You can add the following snippet to the webpack configuration object.
resolve: { extensions: [".jsx", ".js"] }
In your case, you might need to use js file that I recommend this config.
module:{
rules:[{
loader: 'babel-loader',
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
test: /\.jsx?$/,
exclude: /node_modules/,
}, {
test: /\.s?css$/,
use: [
'style-loader',
'css-loader',
'sass-loader'
]
}]
}
The config includes all loader for any file you might need, eg: js jsx css scss.

Resources