ReactJS file-loader not working - reactjs

I can't get the file loader module to work. When running this code I get this error:
"You may need an appropriate loader to handle this file type."
I've been googling a lot on this but can't find a solution. Any ideas?
webpack.config.js:
const path = require("path");
const webpack = require("webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
template: "./client/index.html",
filename: "index.html",
inject: "body"
})
module.exports = {
entry: "./client/index.js",
output: {
path: path.resolve("dist"),
filename: "index_bundle.js"
},
module: {
loaders: [
{ test: /\.js$/, loader: "babel-loader", exclude: /node_modules/ },
{
test: /\.(ico|png|gif|jpg|svg)$/i,
loader: "file-loader"
}
]
},
plugins: [
HtmlWebpackPluginConfig
]
}
package.json:
{
"name": "hello-world-react",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"start": "webpack-dev-server --hot",
"build": "webpack -p"
},
"dependencies": {
"html-webpack-plugin": "^2.28.0",
"path": "^0.12.7",
"react": "^15.5.4",
"react-dom": "^15.5.4",
"webpack": "^2.5.0",
"webpack-dev-server": "^2.4.5"
},
"devDependencies": {
"babel-core": "^6.24.1",
"babel-loader": "^7.0.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"file-loader": "^0.11.1"
}
}
App.jsx:
import React from "react";
export default class App extends React.Component {
render() {
return (
<div style={{ textAlign: "center" }}>
<h1>Hello World</h1>
<img src={require("./client/dog1.jpg")}/>
</div>
)
}
}

You have a .jsx source file but you're telling Webpack to only use babel-loader for files ending in.js. Fix the test in your Webpack config:
{ test: /\.jsx?$/, loader: "babel-loader", exclude: /node_modules/ },

Related

How to remove source maps from webpack 5 #React.js #webpack 5

The common solution for removing source maps from a CRA build is to add "GENERATE_SOURCEMAPS=false react-scripts build" in package.json build scripts and/or "GENERATE_SOURCEMAPS=false" in the CRA .env file. However, I do not use Create React App. Therefore, "react-scripts build" is not recognized as an internal command, my .env file has no effect on the bundled code, and simply adding "GENERATE_SOURCEMAPS=false" to my build scripts does nothing. I would like to remove source maps from the webpack bundle. Here is my package.json.
{
"name": "reactboilerplate",
"version": "1.0.0",
"description": "boilerplate code",
"main": "index.js",
"presets":
[
"#babel/preset-env",
"#babel/preset-react"
],
"scripts":
{
"build": "cross-env GENERATE_SOURCEMAP=false webpack --watch",
"start": "webpack serve",
"build-prod": "weback -p",
"winBuild": "set \"GENERATE_SOURCEMAP=false\" && build"
},
"keywords": [],
"author": "ziggy",
"license": "NONE",
"devDependencies":
{
"#babel/core": "^7.16.7",
"#babel/preset-env": "^7.16.8",
"#babel/preset-react": "^7.16.7",
"babel-loader": "^8.2.3",
"css-loader": "^6.5.1",
"file-loader": "^6.2.0",
"html-loader": "^3.1.0",
"html-webpack-plugin": "^5.5.0",
"node-polyfill-webpack-plugin": "^1.1.4",
"style-loader": "^3.3.1",
"webpack": "^5.66.0",
"webpack-cli": "^4.9.1",
"webpack-dev-server": "^4.7.3"
},
"dependencies":
{
"#aws-amplify/ui-react": "^2.1.9",
"aws-amplify": "^4.3.12",
"aws-amplify-react": "^5.1.9",
"bootstrap": "^5.1.3",
"pandadoc-node-client": "^4.1.0",
"react": "^17.0.2",
"react-bootstrap": "^2.1.1",
"react-dom": "^17.0.2",
"typewriter-effect": "^2.18.2"
}
}
Here is my webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
const NodePolyfillPlugin = require('node-polyfill-webpack-plugin');
module.exports = {
mode: 'development',
entry: './src/index.js',
output:
{
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
},
resolve:
{
modules: [path.join(__dirname, 'src'), 'node_modules'],
alias: { react: path.join(__dirname, 'node_modules', 'react') }
},
plugins:
[
new NodePolyfillPlugin(),
new HtmlWebpackPlugin({ template: './src/index.html' }),
],
module:
{
rules: [
{
test: /\.css/i,
use: ['style-loader', 'css-loader']
},
{
test: /\.js$/,
exclude: /node_modules/,
use:
{
loader: "babel-loader",
options:
{
presets: ['#babel/preset-env', '#babel/preset-react']
}
}
},
{
test: /\.(png|mp4)$/i,
type: "asset/resource"
},
{
test: /\.txt$/i,
type: 'asset/source'
},
{
test: /\.(woff|woff2|ttf)$/i,
type: "asset/resource"
},
{
test: /\.html$/,
use: ["html-loader"]
},
{
test: /\.(mov|mp4)$/,
use:
[
{
loader: 'file-loader',
options:
{
name: '[name].[ext]'
}
}
]
},
{
test: /\.m?js/,
resolve:
{
fullySpecified: false
}
},
]
}
}

ReactJS - Unexpected Token with 3 comma

Im tring to compile my react frontend app but I got a couple of error about "..." syntax:
ERROR in condition.jsx
Module build failed: SyntaxError: Unexpected token (25:10)
23 | show_table : undefined,
24 | fa_count : 0,
> 25 | ...this.state
| ^
26 | }
condition.jsx extends (with OOP) another component so I need ...this.state to merge parent state with the local state.
When launcing it with npm start, it works perfectly but the compiler seems doesn't want that syntax.
UPDATED:
This is my current webpack settings:
const webpack = require('webpack');
const path = require('path');
const Uglify = require("uglifyjs-webpack-plugin");
var plugins = [];
plugins.push(new Uglify());
var config = {
context: __dirname + '/src',
entry: {
javascript: "./index.js",
},
plugins: plugins,
output: {
path: path.join(__dirname,'../static/js/'),
filename: 'bundle.js',
},
devServer: {
inline: true,
port: 8080
},
resolveLoader: {
modules: [path.join(__dirname, 'node_modules')]
},
module: {
loaders: [
{
test:/\.(js|jsx)?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['env','react']
}
},
{
test: /\.css$/,
loader: 'style-loader'
},
{
test: /\.css$/,
loader: 'css-loader',
query: {
modules: true,
localIdentName: '[name]__[local]___[hash:base64:5]'
}
},
{
test: /\.svg$/,
use: [
{
loader: "babel-loader"
},
{
loader: "react-svg-loader",
options: {
jsx: true // true outputs JSX tags
}
}
]
}
]
},
}
module.exports = env => {
return config;
}
Lanching with this command:
./node_modules/.bin/webpack --config webpack.config.js
In a comment, you said that you don't have any babelrc. Then I already re-read the Webpack offical document and take this sample code from there for you:
module: {
rules: [
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env'],
plugins: [require('#babel/plugin-proposal-object-rest-spread')]
}
}
}
]
after installing the babel-plugin-transform-object-rest-spread package, you could follow this sample code to update your webpack config. Read more about it: Webpack Loader
This is the combination that works for me, I'm using the babel-preset-stage-2 instead.
In the webpack.config.js:
....
module: {
rules: [
{
test:/\.(js|jsx)?$/,
use: ['babel-loader']
},
....
]
}
....
I create a .babelrc file in the root folder and its content is:
{
"presets": ["env", "react", "stage-2"],
....
}
And this is my package.json file:
{
"name": "demo",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"start": "webpack-dev-server --open"
},
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-core": "^6.26.3",
"babel-loader": "^7.1.4",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-2": "^6.24.1",
"clean-webpack-plugin": "^0.1.19",
"css-loader": "^0.28.11",
"html-webpack-plugin": "^3.2.0",
"node-sass": "^4.9.0",
"react-hot-loader": "^4.3.3",
"sass-loader": "^7.0.3",
"style-loader": "^0.21.0",
"webpack": "^4.15.0",
"webpack-cli": "^3.0.8",
"webpack-dev-server": "^3.1.4"
},
"dependencies": {
"prop-types": "^15.6.2",
"react": "^16.4.1",
"react-dom": "^16.4.1",
"react-redux": "^5.0.7",
"redux": "^4.0.0",
"uuid": "^3.3.2"
}
}
Hopefully, it works for you.
You didn't tell about your configuration. But I assume babel and webpack. This seems to be an issue with your babel config. Try this plugin:
https://www.npmjs.com/package/babel-plugin-transform-object-rest-spread
After you've installed it, add
"plugins": ["transform-object-rest-spread"]
To your .babelrc file and run the webpack again.

d.ts file not being created for typings-for-css-modules-loader

Here's my package.json file:
{
"name": "redacted",
"version": "1.0.0",
"description": "redacted",
"main": "webpack.config.js",
"directories": {
"doc": "docs"
},
"scripts": {
"start": "webpack-dev-server --mode development --open --hot",
"build": "webpack --mode production",
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "redacted"
},
"author": "",
"license": "ISC",
"bugs": {
"url": "URL"
},
"homepage": "Here",
"dependencies": {
"react": "^16.4.0",
"react-dom": "^16.4.0"
},
"devDependencies": {
"#types/react": "^16.3.16",
"#types/react-dom": "^16.0.6",
"awesome-typescript-loader": "^5.0.0",
"babel-core": "^6.26.3",
"babel-loader": "^7.1.4",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"css-loader": "^0.28.11",
"extract-text-webpack-plugin": "^3.0.2",
"html-webpack-plugin": "^3.2.0",
"source-map-loader": "^0.2.3",
"tslint": "^5.10.0",
"typescript": "^2.9.1",
"typings-for-css-modules-loader": "^1.7.0",
"webpack": "^4.11.1",
"webpack-cli": "^3.0.2",
"webpack-dev-server": "^3.1.4"
}
}
And here's webpack.config.js:
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry: "./src/index.tsx",
output: {
path: path.resolve(__dirname, "./dist"),
filename: "bundle.js"
},
module: {
rules: [
{
test: /\.tsx?$/,
loader: "awesome-typescript-loader",
exclude: /node_modules/,
},
{
enforce: "pre",
test: /\.js$/,
loader: "source-map-loader"
},
{
test: /\.css$/,
include: /src/,
exclude: /node_modules/,
loader: ExtractTextPlugin.extract('typings-for-css-modules-loader?modules&namedExport&camelCase&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]'),
},
{
test: /\.css$/,
include: /node_modules/,
loader: ExtractTextPlugin.extract({fallback: 'style-loader', use: 'css-loader?sourceMap'})
}
]
},
plugins: [
new ExtractTextPlugin('[name].css'),
new HtmlWebpackPlugin({
template: "./src/index.html"
})
],
devtool: "source-map",
resolve: {
extensions: [".js", ".ts", ".tsx"]
}
}
Doing the following in my component:
import * as React from "react";
import css = require("./App.css");
export class App extends React.Component<{}, {}> {
public render() {
return (
<div className={css.main}>I am working!</div>
);
}
}
But it doesn't generate d.ts file. import css line says [ts] Cannot find module './App.css'.
Instead I get this error:
ERROR in ./src/components/App.css
Module build failed: Error: "extract-text-webpack-plugin" loader is used without the corresponding plugin, refer to https://github.com/webpack/extract-text-webpack-plugin for the usage example
I also tried this tutorial but it didn't work either: https://medium.com/#sapegin/css-modules-with-typescript-and-webpack-6b221ebe5f10
How can I go about fixing this? Thanks!

Webpack with babel-loader doesn't recognize Typescript

I am using webpack and trying to leverage an existing React component library written in TS.
However, with the settings below, the webpack is giving 'unexpected Token' error. I copied the problematic code to babel online transpiler https://babeljs.io/repl/ but it is not showing any error.
I am very new to React development, any criticism/questions/answers are welcomed.
Thanks!
This is my webpack.config.js
var path = require("path")
var webpack = require('webpack')
var BundleTracker = require('webpack-bundle-tracker')
module.exports = {
context: __dirname,
entry: [
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server',
'./app/static/js/index'
],
output: {
path: path.resolve('./app/static/bundles/'),
filename: '[name]-[hash].js',
publicPath: 'http://localhost:3000/static/bundles/',
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
new BundleTracker({filename: './webpack-stats.json'}),
],
module: {
loaders: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loader: ["babel-loader?presets[]=es2015,presets[]=react"],
},
{
test: /\.tsx?$/,
loader: 'ts-loader',
options: {
configFileName: './tsconfig.json'
},
exclude: /node_modules/
},
{
test: /\.css$/,
loader: 'style-loader!css-loader'
}
]
},
resolve: {
extensions: ['.js', '.jsx', '.ts', '.tsx', '.css']
}
}
My entry point file index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import * as PropTypes from 'prop-types';
interface IDemoState {
value ?: string;
}
class Test extends React.Component<{}, IDemoState> {
state: IDemoState = {
value : 'general'
}
}
ReactDOM.render(<Test />, document.getElementById('tabnav'));
Package.json
{
"name": "djangoproject",
"version": "1.0.0",
"description": "Django Project",
"main": "index.js",
"scripts": {
"build": "webpack --config webpack.config.js --progress --colors",
"build-production": "webpack --config webpack.prod.config.js --progress --colors",
"watch": "node server.js"
},
"keywords": [
"Django"
],
"license": "ISC",
"devDependencies": {
"adp-css-framework": "^1.5.3",
"adp-react-components": "^1.4.3",
"adp-react-icons": "^1.16.0",
"babel": "^6.23.0",
"babel-cli": "^6.24.1",
"babel-core": "^6.25.0",
"babel-loader": "^7.1.0",
"babel-preset-env": "^1.5.2",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"css-loader": "^0.28.4",
"react": "^15.6.1",
"react-dom": "^15.6.1",
"react-hot-loader": "^1.3.1",
"style-loader": "^0.18.2",
"ts-loader": "^2.2.1",
"typescript": "^2.4.1",
"webpack": "^3.0.0",
"webpack-bundle-tracker": "^0.2.0",
"webpack-dev-server": "^2.5.0"
}
}
If I run npm run watch, I got this error:
ERROR in ./app/static/js/index.js
Module build failed: SyntaxError: xxxxx./app/static/js/index.js: Unexpected token (10:20)
8 |
9 | class Test extends React.Component<{}, IDemoState> {
> 10 | state: IDemoState = {
| ^
11 | value : 'general'
12 | }
13 | }
# multi webpack-dev-server/client?http://localhost:3000 webpack/hot/only-dev-se
rver ./app/static/js/index
The problem finally goes away after I changed the ts-loader to awesome-typescript-loader and write everything in a tsx file.

ERROR in multi ./main.js watch when running webpack

I get the following error when running:
webpack watch
ERROR in multi ./main.js watch
Module not found: Error: Can't resolve 'watch' in '/Users/name/directory/src'
# multi ./main.js watch
Heres my webpack.config.js file
const path = require('path');
module.exports = {
context: path.join(__dirname, 'src'),
entry: [
'./main.js',
],
output: {
path: path.join(__dirname, 'www'),
filename: 'bundle.js',
},
module: {
rules: [
{
test: /\.js$/,
include: [
path.resolve(__dirname, "src")
],
exclude: /node_modules/,
use: [
'babel-loader',
],
},
{
test: /\.scss$/,
exclude: /node_modules/,
use: [{
loader: "style-loader" // creates style nodes from JS strings
}, {
loader: "css-loader" // translates CSS into CommonJS
}, {
loader: "sass-loader" // compiles Sass to CSS
}]
}
],
},
resolve: {
modules: [
path.join(__dirname, 'node_modules'),
],
},
};
Here is my package.json
{
"name": "name",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"react": "^15.4.2",
"react-dom": "^15.4.2",
"webpack-dev-middleware": "^1.10.1"
},
"devDependencies": {
"babel-core": "^6.24.0",
"babel-loader": "^6.4.1",
"babel-preset-es2015": "^6.24.0",
"babel-preset-latest": "^6.24.0",
"babel-preset-react": "^6.23.0",
"babel-preset-stage-2": "^6.22.0",
"css-loader": "^0.27.3",
"express": "^4.15.2",
"node-sass": "^4.5.0",
"react-helmet": "^4.0.0",
"react-hot-loader": "^1.3.1",
"sass-loader": "^6.0.3",
"style-loader": "^0.14.1",
"webpack": "^2.2.1",
"webpack-dev-middleware": "^1.10.1",
"webpack-dev-server": "^2.4.2"
}
}
Below is my main.js file
import "./styles/stylesheet.scss";
import { Header } from "./components/headercomponent";
import React from "react";
import ReactDOM from "react-dom";
import { render } from "react-dom";
class App extends React.Component {
render(){
return (
<div id="container">
<Header/>
<h1>hello world</h1>
</div>
);
}
}
render(<App/>, window.document.getElementById("app"));
Do you know why I'm getting the webpack error?
Arguments you pass to the webpack CLI will be treated as entry points. You want to use the --watch option, not add watch as an entry. The correct command is:
webpack --watch

Resources