webpack compile error on require(imagePath) - javascript

I'm trying to dymaically load an image in ReactJS. So far, what I've found on the internet has not worked.
My react component looks like this:
class ReadOnlyTableRow extends React.Component {
render() {
let optionImage = require('../assets/option.jpg');
return (
<tr>
<td>
<img src={optionImage} />
{this.props.data.type}
</td>
<td>{this.props.data.symbol}</td>
</tr>
);
}
}
and the webpack error I get is this:
ERROR in ./src/assets/option.jpg Module parse failed:
C:\Java\src\options\web\src\assets\option.jpg Unexpected character '?'
(1:0) You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected character '?' (1:0)
I tried adding a loader to my webpack, but that gave different errors. So I removed it from my webconfig file.
and my webpack.config file
module.exports = {
entry: './src/app.js',
output: {
path: __dirname,
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: { presets: [ 'es2015', 'react' ] }
}
]
}
};
What am I missing? or doing wrong?
Thnx,
Matt
Addendum:
When I include this in my webpack.config
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: { presets: [ 'es2015', 'react' ] }
},
{
test: /\.(png|jpg)$/,
loader: 'url?limit=25000'
}
]
}
I get another error:
WARNING in Loader
C:\Java\src\options\web\node_modules\url\url.js?limit=25000 didn't
return a function
The structure of my project is such:
src
|---Components
---ReadOnlyTableRow
|---assets
---option.jpb
here's the package.config file
{
"name": "engine",
"version": "1.0.0",
"description": "engine UI written in React",
"main": "index.js",
"private": true,
"scripts": {
"start": "webpack-dev-server --progress --inline --port 8112",
"build": "webpack"
},
"keywords": [],
"author": "mpr",
"license": "ISC",
"dependencies": {
"babel-core": "^6.17.0",
"babel-loader": "^6.2.4",
"babel-preset-es2015": "^6.6.0",
"babel-preset-react": "^6.5.0",
"moment": "^2.18.1",
"react": "^0.14.6",
"react-bootstrap": "^0.30.5",
"react-currency-input": "^1.2.6",
"react-date-picker": "^5.3.28",
"react-dom": "^0.14.6",
"webpack": "^1.13.0",
"webpack-dev-server": "^1.16.2"
},
"devDependencies": {
"file-loader": "^1.1.5"
}
}
Thnx, Matt

To solve this problem, I used file-loader, per #Emad suggestion in the comments above. Additionally, I needed to use a different web.config which is different than the directions provided for file-loader. The web.config changes are as follows.
module.exports = {
entry: './src/app.js',
output: {
path: __dirname,
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: { presets: [ 'es2015', 'react' ] }
},
{
test: /\.(png|jpg|gif)$/,
loader: 'file-loader',
exclude: /node_modules/,
options: {}
}
]
}
};
I changed my javascript code to pull in the image via the import statement:
import reloadImage from './../assets/reload-sm.png';
Thnx
Matt

Related

You may need an appropriate loader to handle this file type, currently no loaders are configured import Counter from './components/counter.jsx'

Im trying to setup a new js/typescript environment to practice web dev while using react, yarn, and webpack but I keep getting this error when trying to get it set up. My current configs look like this. I am new to all of this so if you see anything I should change then please let me know.
webpack.config.js
const path = require('path')
module.exports = {
devServer: {
contentBase: path.resolve(__dirname, './public'),
historyApiFallback: true,
},
entry: path.resolve(__dirname, './src/index.js'),
resolve: {
extensions: ['*', '.js', '.jsx'],
},
module: {
rules: [
{
test: /\.jsx?$/,
use: [
{
loader: 'babel-loader',
options: {
presets: ['react'],
},
},
],
test: /\.(scss)$/,
use: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
},
{
loader: 'postcss-loader',
options: {
plugins: function () {
return [require('precss'), require('autoprefixer')]
},
},
},
{
loader: 'saas-loader',
},
],
exclude: /node_modules/,
},
],
},
output: {
filename: 'bundle.js',
},
}
index.js
import React from 'react'
import {render} from 'react-dom'
import 'bootstrap/dist/css/bootstrap.css'
import Counter from './components/counter.jsx'
ReactDOM.render(<Counter />, document.getElementById('app'))
package.json
{
"name": "trend-dot-com",
"version": "1.0.0",
"main": "index.js",
"license": "TBA",
"devDependencies": {
"#babel/core": "^7.10.2",
"#babel/preset-env": "^7.10.2",
"#babel/preset-react": "^7.10.1",
"babel-loader": "^8.1.0",
"webpack": "^4.43.0",
"webpack-cli": "^3.3.11",
"webpack-dev-server": "^3.11.0"
},
"dependencies": {
"bootstrap": "^4.5.0",
"postcss-loader": "^3.0.0",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"sass-loader": "^8.0.2"
},
"scripts": {
"watch": "webpack-dev-server --progress"
}
}
Thanks in advance!
On the first look everything looked Ok. But the problem seems to be in your webpack.config file.
Try below
const path = require('path')
module.exports = {
devServer: {
contentBase: path.resolve(__dirname, './public'),
historyApiFallback: true,
},
entry: path.resolve(__dirname, './src/index.js'),
resolve: {
extensions: ['*', '.js', '.jsx'],
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /(node_modules)/,
use:
{
loader: 'babel-loader',
options: {
presets:["#babel/preset-env","#babel/preset-react" ]
},
},
},
{
test: /\.(scss)$/,
use: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
},
{
loader: 'postcss-loader',
options: {
plugins: function () {
return [require('precss'), require('autoprefixer')]
},
},
},
{
loader: 'saas-loader',
},
],
exclude: /node_modules/,
},
],
},
output: {
filename: 'bundle.js',
},
}
Also after changing this there is a css-loader error which is not installed , so you can install and add that to your package.json. But since you already have Sass packages may be you want to refer the bootstrap sass version in your index.js - upto you. Hope this helps!.

Configuring webpack and babel to transform rest arguments in a node_modules dependancy

I'm using webpack and babel to compile my JavaScript to ES5. It's working nicely on my own code, but my library started throwing errors in Internet Explorer browsers when I added debug as a dependency. The error points to a rest parameter (e.g. function(...t)) as the place parsing failed.
The main file in the debug module is ES6 (and that's not going to change) and unfortunately there doesn't seem to be any guidance there on babel configuration for node_modules dependencies.
The CLI output doesn't seem to include anything revealing. The output files are being created, as expected, and they work on modern browsers. It's just that rest parameter I can't get rid of.
Can anyone point me in the right direction? It looks like #babel/plugin-transform-parameters should fix the issue, but none of the configuration variations I've tried have had any effect on the debug code.
Edit: After a closer look, it seems that the problem may be that babel is doing too much transpiling, rather than not enough. It looks like this bit of code from node_modules/debug/dist/debug.js is being transformed into the problematic rest parameter.
IN:
function log() {
var _console;
// This hackery is required for IE8/9, where
// the `console.log` function doesn't have 'apply'
return (typeof console === "undefined" ? "undefined" : _typeof(console)) === 'object' && console.log && (_console = console).log.apply(_console, arguments);
}
OUT:
function(n){e.log=function(...A){return"object"==typeof console&&console.log&&console.log(...A)}
I've tried including both my source directory and the debug module as an array:
{
loader: 'babel-loader',
test: [path.resolve(__dirname, 'src'), /node_modules\/debug/]
},
I've tried including all .js files, but excluding most node_modules sub-directories...
{
loader: 'babel-loader',
test: /(\.jsx|\.js)$/,
exclude: /node_modules\/(?!debug)/
},
Even splitting into multiple rules:
{
loader: 'babel-loader',
test: /(\.jsx|\.js)$/,
exclude: /node_modules/
},
{
loader: 'babel-loader',
test: /node_modules\/debug/
},
Using a function had the same effect:
const shouldExclude = filename => {
if (/my-project[\\\/]src/.test(filename)) return false;
if (/my-project[\\\/]test/.test(filename)) return false;
if (/my-project[\\\/]node_modules[\\\/]debug/.test(filename)) return false;
return true;
};
...
module: {
rules: [{ test: /\.js$/, exclude: shouldExclude, use: ['babel-loader'] }],
},
Here are the mostly-complete config files, for reference
package.json
{
"name": "my-js-library",
"devDependencies": {
"#babel/cli": "^7.8.4",
"#babel/core": "^7.9.0",
"#babel/plugin-transform-object-assign": "^7.8.3",
"#babel/plugin-transform-parameters": "^7.9.3",
"#babel/plugin-transform-runtime": "^7.9.0",
"#babel/polyfill": "^7.8.7",
"#babel/preset-env": "^7.9.0",
"#babel/register": "^7.9.0",
"#babel/runtime": "^7.9.0",
"babel-eslint": "^10.1.0",
"babel-loader": "^8.1.0",
"babel-plugin-add-module-exports": "^1.0.2",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-preset-env": "^7.0.0-beta.3",
"classlist-polyfill": "^1.2.0",
"debug": "4.1.1",
"eslint": "^6.8.0",
"eslint-loader": "^3.0.3",
"eslint-plugin-html": "^6.0.0",
"uglifyjs-webpack-plugin": "^2.2.0",
"webpack": "^4.42.0",
"webpack-cli": "^3.3.11",
"yargs": "^15.3.1"
},
"dependencies": {}
}
.babelrc
{
"presets": ["#babel/preset-env"],
"plugins": [
"babel-plugin-add-module-exports",
"transform-class-properties",
"#babel/plugin-transform-object-assign",
"#babel/plugin-transform-runtime",
"#babel/plugin-transform-parameters"
]
}
webpack.config.js
const config = {
mode: 'production,
entry: __dirname + '/src/index.js',
devtool: 'source-map',
output: {
path: __dirname + '/lib',
filename: my-js-library.min.js,
library: 'MyJsLibrary',
libraryTarget: 'umd',
},
module: {
rules: [
{
test: /(\.jsx|\.js)$/,
loader: 'babel-loader',
exclude: /node_modules/,
},
{
test: /node_modules\/debug/,
loader: 'babel-loader',
},
{
test: /(\.jsx|\.js)$/,
loader: 'eslint-loader',
exclude: /node_modules/,
},
],
},
stats: 'minimal',
resolve: {
modules: [path.resolve('./node_modules'), path.resolve('./src')],
extensions: ['.json', '.js'],
},
};
module.exports = config;

Webpack4|Redux|React Issue - You may need an appropriate loader to handle this file type

I am trying my hands on Webpack4/Redux/React and getting the following error for my sample application:
./src/index.js] 210 bytes {main} [built] [failed] [1 error]
+ 13 hidden modules
ERROR in ./src/index.js Module parse failed: Unexpected token (3:16)
You may need an appropriate loader to handle this file type. | import
React from 'react'; | | const element = Hello, world; | | #
multi webpack-dev-server/client?http://localhost:3000
webpack/hot/only-dev-server ./src/index i 「wdm」: Failed to compile.
I have tried different ways to resolve this (as is evident from commented out code) without any success. Please let me know what I am missing. My Code files are as follows:
Package.json:
{
"name": "react-redux-example",
"version": "1.0.0",
"description": "using redux architecture",
"main": "node server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git"
},
"keywords": [
"reactjs",
"redux",
"react",
"hot",
"reload",
"live",
"edit",
"webpack"
],
"author": "newbieToReact",
"license": "MIT",
"dependencies": {
"babel": "^6.23.0",
"mkdirp": "^0.5.1",
"react": "^16.4.0",
"react-router": "^4.2.0",
"style-loader": "^0.21.0",
"webpack": "^4.10.2",
"webpack-dev-server": "^3.1.4"
},
"devDependencies": {
"extract-text-webpack-plugin": "^4.0.0-beta.0"
}
}
webpack.config.js
var path = require('path');
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var devFlagPlugin = new webpack.DefinePlugin({
__DEV__: JSON.stringify(JSON.parse(process.env.DEBUG || 'true'))
});
module.exports = {
devtool: 'eval',
entry: [
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server',
'./src/index'
],
mode: "development",
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
//new webpack.NoErrorsPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
devFlagPlugin,
new ExtractTextPlugin('app.css')
],
// module: {
// loaders: [
// {
// test: /\.jsx?$/,
// loaders: ['react-hot', 'babel'],
// include: path.join(__dirname, 'src')
// },
// { test: /\.css$/, loader: ExtractTextPlugin.extract('css-loader?module!cssnext-loader') }
// ]
// },
//module: {
// rules: [
// {
// exclude: '/node_modules/',
//test: /\.jsx?$/,
//test: /\.js$/,
// test: /\.(js|jsx)$/,
// include: path.join(__dirname, 'src'),
// test: /\.css$/,
// use: [
// { loader: "react-hot" },
// { loader: "babel" },
// { loader: "ExtractTextPlugin.extract('css-loader?module!cssnext-loader')"},
// { loader: "style-loader" },
// ]
// }
// ]
// },
module: {
rules: [
{
exclude: '/node_modules/',
test: /\.(js|jsx)$/,
include: path.join(__dirname, 'src'),
test: /\.css$/,
loader: "react-hot",
loader: "babel",
loader: "ExtractTextPlugin.extract('css-loader?module!cssnext-loader')",
loader: "style-loader",
}
]
},
resolve: {
extensions: ['.js', '.json']
}
};
src/index.js
import React from 'react';
const element = <h1>Hello, world</h1>;
Your module/loaders needs another clause in test: this needs to be test: /\.(js|jsx)$/, because you are using a .js file and no .jsx. Also it's a good practice to include this in your config: resolve: { extensions: ['.js'] }, when using .js instead off .jsx. Also uncomment the second loader because i see you're using a .css this needs the css-loader to work.
You will have to add css-loader and babel-loader to your devDependencies aswell.
Also you're using webpack 4 which implies that ExtractTextPlugin has been deprecated so remove this.
Hope this helped, good luck!
In webpack.config.js you should follow scheme described in webpack docs
Here is an example
rules: [{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loader: 'babel-loader',
}, {
test: /\.css$/,
use: [ 'style-loader', 'css-loader' ]
}]

Webpack node sass error

I have the following:
const HtmlWebpackPlugin = require('html-webpack-plugin');
const injectConfig = new HtmlWebpackPlugin({
template: './index.html',
filename: 'index.html',
inject: 'body'
});
module.exports = {
context: __dirname + '/app',
entry: './index.js',
output: {
path: __dirname + '/build',
filename: 'bundle.js'
},
module: {
loaders: [
{ test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ },
{ test: /\.jsx?$/, loader: 'babel-loader', exclude: /node_modules/ },
{ test: /\.scss$/, loaders: ['style-loader', 'css-loader', 'sass-loader'], exclude: /node_modules/ }
]
},
plugins: [injectConfig]
}
and when I run "npm run start" as per my package.json:
{
"name": "react-chart",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server"
},
"author": "Alessandro Santese",
"license": "ISC",
"dependencies": {
"html-webpack-plugin": "^2.30.1",
"node-sass": "^4.6.0",
"react": "^16.0.0",
"react-dom": "^16.0.0",
"react-easy-chart": "^0.3.0",
"recharts": "^1.0.0-beta.0",
"webpack": "^3.8.1",
"webpack-dev-server": "^2.9.4"
},
"devDependencies": {
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-plugin-transform-object-rest-spread": "^6.26.0"
}
}
I get the following error:
Had this error a while ago try the below to things - worked for me:
Run npm rebuild node-sass in your project and try to re-run your webpack build afterwards
If that doesn't help delete your project's node_modules directory in the project and webpack rebuild
I think the first one should already fix your issue, but if not the second one should do the trick.
This helped:
sudo npm cache clean -f
sudo npm install -g n
sudo n 6.0.0

Module Build Failure with Unexpected token error on npm start - react/webpack

I'm attempting to create my first react application, following this tutorial I found online: http://jmfurlott.com/tutorial-setting-up-a-single-page-react-web-app-with-react-router-and-webpack/.
However I've run into a problem after completing it. I keep getting this error when I do an 'npm start' in the command line:
ERROR in ./js/app.js Module build failed: SyntaxError:
/Users/justinkruse/nike-plus-api/js/app.js: Unexpected token (10:6)
app.js:
import React from 'react';
import Router from 'react-router';
import { DefaultRoute, Link, Route, RouteHandler } from 'react-router';
import LoginHandler from './components/Login.js';
var App = React.createClass({
render: function() {
return (
<div className="nav"> //error points here at opening <
<Link to="app">Home</Link>
<Link to="login">Login</Link>
<RouteHandler/>
</div>
);
}
});
var routes = (
<Route name="app" path="/" handler={App}>
<Route name="login" path="/login" handler={LoginHandler}/>
</Route>
);
Router.run(routes, function (Handler) {
React.render(<Handler/>, document.body);
});
package.json:
{
"name": "foobar",
"version": "1.0.0",
"description": "application foobar",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server --hot --progress --colors",
"build": "webpack --progress --colors",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Justin Kruse",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.3.26",
"babel-loader": "^6.2.0",
"babel-preset-es2015": "^6.3.13",
"babel-preset-react": "^6.3.13",
"history": "^1.17.0",
"react": "^0.14.3",
"react-hot-loader": "^1.3.0",
"react-router": "^1.0.3",
"webpack": "^1.12.9",
"webpack-dev-server": "^1.14.0"
},
"dependencies": {
"history": "1.17.0"
}
}
webpack.config.js:
var webpack = require('webpack');
module.exports = {
entry: [
'webpack/hot/only-dev-server',
"./js/app.js"
],
output: {
path: __dirname + '/build',
filename: "bundle.js"
},
module: {
loaders: [
{ test: /\.js?$/, loader: 'babel', exclude: /node_modules/,
query:
{
presets:['react','es2015']
}
},
{ test: /\.js?$/,loaders:['react-hot'], exclude: /node_modules/},
{ test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader'},
{ test: /\.css$/, loader: "style!css" }
]
},
plugins: [
new webpack.NoErrorsPlugin()
]
};
A similar question was asked here, but it seems to be dead.
You are processing all your .js files through babel twice. One using the react presets:
{ test: /\.js?$/, loader: 'babel', exclude: /node_modules/,
query:
{
presets:['react','es2015']
}
},
And the other one without:
{ test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader'},
The latter is the one that is probably giving you the error because this loader is unable to understand JSX. Just remove it.
BTW: I would take a look at react-hot-boilerplate if you want to play with react hot module reloading.
You'll need something like this. But again, check the link above for more detailed configuration.
webpack.config.js
var webpack = require('webpack');
module.exports = {
entry: [
'webpack/hot/only-dev-server',
"./js/app.js"
],
output: {
path: __dirname + '/build',
filename: "bundle.js"
},
module: {
loaders: [
{ test: /\.js?$/,loaders:['react-hot', 'babel'], exclude: /node_modules/},
{ test: /\.css$/, loader: "style!css" }
]
},
plugins: [
new webpack.NoErrorsPlugin()
]
};
.babelrc
{
"presets": ["es2015", "react"]
}
As a side note. Things go fast in JavaScript... Just to inform that react-hot-loader is about to be deprecated in favor of react-transform.

Categories