React Webpack.config.js issue - reactjs

Being fairly new to the world of react, I'm trying to create a successfully webpack.config.js for my react solution. My webpack.config.js contains the following code:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/index.js',
plugins: [
new HtmlWebpackPlugin({
title: 'Caching',
template: './index.html'
})
],
output: {
filename: 'main.[hash].js',
chunkFilename: '[name].[hash].[chunkhash].chunk.js',
path: path.resolve(__dirname, 'build'),
clean: true,
publicPath: ""
},
optimization: {
moduleIds: 'deterministic',
runtimeChunk: 'single',
splitChunks: {
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all',
},
},
},
},
resolve: {
extensions: ['.js', '.jsx']
},
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.css$/,
exclude: /node_modules/,
use: [
{ loader: 'style-loader' },
{
loader: 'css-loader',
options: {
modules: {
localIdentName: "[name]__[local]___[hash:base64:5]",
},
sourceMap: true
}
}
]
},
{
test: /\.(png|jpe?g|gif)$/,
loader: 'url-loader?limit=10000&name=img/[name].[ext]'
}
]
}
};
However, when I execute npm run build the following files are created.
enter image description here
And the webpack.plugin interjects this line into my entry point
enter image description here
Which is obvious the wrong name, producing a 404 error message. I have read a number of articles about creating Webpack.config.js but I'm unable to resolve my issue for removing the 404 error and getting the correct filename interjected into my entry point

Related

webpack Can't resolve '../../assets/icon-font/icomoon.eot?e3uwku' in 'D:\sudi\aa-Server-side-render\MAPS101_Fresh_ssr\src\scss'

I want to implement SSR in an already build react application.
I am trying to include icon-fonts and ignore CSS files from node_modules of a particular library
Please help me, I am stuck here!!
I'm trying to load a font in my SCSS file but giving the below error.
my folder structure is :
my webpack.config.js is:
const path = require('path');
const HTMLWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
module.exports = {
// webpack optimization mode
mode: ('development' === process.env.NODE_ENV ? 'development' : 'production'),
// entry files
entry: 'development' === process.env.NODE_ENV ? [
'./src/index.js', // in development
] : [
'./src/index.js', // in production
],
// output files and chunks
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'build/[name].js',
},
// module/loaders configuration
module: {
rules: [
{
test: /\.(js|jsx)$/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env', '#babel/preset-react']
}
},
exclude: [/node_modules/, /static/]
},
{
test: /\.(sa|sc|c)ss$/,
use: [
true ? 'style-loader' : MiniCssExtractPlugin.loader,
'css-loader',
'postcss-loader',
'sass-loader',
],
exclude: [/node_modules/, /static/]
},
{
test: /\.(css)$/,
use: [{
loader: MiniCssExtractPlugin.loader,
options: {
publicPath: '/public/css'
}
}, 'css-loader'],
exclude: [/node_modules/, /static/]
},
{
test: /\.(jpg|jpeg|png|svg|gif)$/,
use: [{
loader: 'file-loader',
options: {
name: '[md5:hash:hex].[ext]',
publicPath: '/public/img',
outputPath: 'img'
}
}]
},
{
test: /\.woff(\?v=\d+\.\d+\.\d+)?$/,
use: 'url-loader?limit=10000&mimetype=application/font-woff',
},
{
test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/,
use: 'url-loader?limit=10000&mimetype=application/font-woff',
},
{
test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
use: 'url-loader?limit=10000&mimetype=application/octet-stream',
},
{
test: /\.otf(\?v=\d+\.\d+\.\d+)?$/,
use: 'url-loader?limit=10000&mimetype=application/octet-stream',
},
{
test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
use: 'url-loader?limit=10000&mimetype=application/vnd.ms-fontobject',
},
]
},
// webpack plugins
plugins: [
// extract css to external stylesheet file
new MiniCssExtractPlugin({
filename: 'build/styles.css'
}),
// prepare HTML file with assets
new HTMLWebpackPlugin({
filename: 'index.html',
template: path.resolve(__dirname, 'src/index.html'),
minify: false,
}),
// copy static files from `src` to `dist`
new CopyWebpackPlugin({
patterns: [
{
from: path.resolve(__dirname, 'src/assets'),
to: path.resolve(__dirname, 'dist/assets')
}
]
}),
],
// resolve files configuration
resolve: {
// file extensions
extensions: ['.js', '.jsx', '.css', '.scss'],
},
// webpack optimizations
optimization: {
splitChunks: {
cacheGroups: {
default: false,
vendors: false,
vendor: {
chunks: 'all', // both : consider sync + async chunks for evaluation
name: 'vendor', // name of chunk file
test: /node_modules/, // test regular expression
}
}
}
},
// development server configuration
devServer: {
port: 8088,
historyApiFallback: true,
}, // generate source map
devtool: 'source-map' };
For me, I had the icomoon font in fonts directory. Did some investigation and found that the .scss file was trying to link it like this
url("./assets/styles/fonts/icomoon.svg?y2smka#icomoon"). The problem with that is icomoon.svg?y2smka#icomoon does not exist. So I looked in the fonts directory and found that it's called icomoon.eot
Solution:
In your _fonts.scss file, change all url("./assets/styles/fonts/icomoon.svg?y2smka#icomoon"). to url("./icomoon.eot")

Not able to run react project

I am new to reactjs. i am trying to write webpack.
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './main.js',
output: {
path: path.join(__dirname, '/bundle'),
filename: 'index_bundle.js'
},
devServer: {
inline: true,
port: 3000
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
}
},
{
test: /\.scss$/,
use: [{
loader: "style-loader"
}, {
loader: "css-loader"
}, {
loader: "sass-loader",
options: {
includePaths: ["absolute/path/a", "absolute/path/b"]
}
}]
}
]
},
plugins:[
new HtmlWebpackPlugin({
template: './index.html'
})
]
}
Html Webpack Plugin:
Error: Child compilation failed:
Entry module not found: Error: Can't resolve 'F:\react-app\index.html' in 'F:\ react-app':
Error: Can't resolve 'F:\react-app\index.html' in 'F:\react-app'
compiler.js:141
[react-app]/[html-webpack-plugin]/lib/compiler.js:141:18
Compiler.js:306
[react-app]/[webpack]/lib/Compiler.js:306:11
Compiler.js:631
[react-app]/[webpack]/lib/Compiler.js:631:15
Hook.js:154 AsyncSeriesHook.lazyCompileHook
[react-app]/[tapable]/lib/Hook.js:154:20
Compiler.js:628
[react-app]/[webpack]/lib/Compiler.js:628:31
Hook.js:154 AsyncSeriesHook.lazyCompileHook
[react-app]/[tapable]/lib/Hook.js:154:20
Compilation.js:1325
[react-app]/[webpack]/lib/Compilation.js:1325:35
plugins:[
new HtmlWebpackPlugin({
hash:'true'
template: './index.html'
})
]
Put hash to true and make sure you have the correct location of the template file.

Resolve Relative Path from node_modules to Dist folder with Webpack

I'm using React component as an NPM Package. in the component, I have SCSS file
with url(../iamges/img..) path, but actually, the images folder located in the Dist folder, how can I point Webpack to take the relative path from node_modules and serve it from images folder located in the Dist?
located in node_modules =>
background: url('../images/some-icon.svg') no-repeat center center;
Webpack config:
const webpack = require('webpack');
const path = require('path');
module.exports = {
entry: './src/index.js',
devtool: 'inline-module-source-map',
output: {
path: path.resolve(__dirname, '/dist'),
filename: 'bundle.js',
publicPath: '/',
},
module: {
rules: [
{
test: /\.js$/,
use: {
loader: 'babel-loader',
},
},
{
test: /\.scss$/,
use: [
{ loader: 'style-loader' },
{ loader: 'css-loader' },
{
loader: 'resolve-url-loader',
// options: {
// debug: true,
// root: path.join(__dirname, './dist/images'),
// includeRoot: true,
// absolute: true,
// },
},
{
loader: 'sass-loader',
options: {
sourceMap: true,
sourceMapContents: false,
},
},
],
},
{
test: /\.css$/,
loaders: ['style-loader', 'css-loader'],
},
{
test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
use: {
loader: 'url-loader?name=/images/[name].[ext]',
options: {
limit: 10000,
},
},
},
],
},
resolve: {
extensions: ['.js', '.jsx'],
// modules: [path.resolve(__dirname, '/images'), 'node_modules'],
alias: {
'react-redux': path.resolve('./node_modules/react-redux'),
},
},
plugins: [new webpack.HotModuleReplacementPlugin()],
devServer: {
hot: true,
publicPath: '/dist/',
},
};
babel.config.js
module.exports = {
// presets: ['#babel/preset-env', '#babel/preset-react'],
plugins: [
'#babel/plugin-proposal-class-properties',
'#babel/plugin-proposal-export-default-from',
'#babel/transform-runtime',
],
sourceType: 'unambiguous',
presets: [
[
'#babel/preset-env',
{
targets: {
node: 'current',
},
},
],
'#babel/preset-react',
],
};
dist
-- images
-- index.html
ERROR:
ERROR in ./node_modules/comp/src/styles/details.scss (./node_modules/css-loader!./node_modules/resolve-url-loader!./node_modules/sass-loader/lib/loader.js??ref--5-3!./node_modules/compdetails/src/styles/details.scss)
Module not found: Error: Can't resolve '../images/icon.svg'
Anything referred through url('...') in css will be computed with reference to the path of deployed application (scss will not compute the path unless variable or function is not being used):
For example:
If your referred component SCSS module is having background: url('../images/some-icon.svg') no-repeat center center;
The final CSS compilation will be same (it is also because the component is not using any SCSS variables or functions to compute the final path).
So your application will always try to find that image as:
Example: http://localhost:3000/../images/some-icon.svg which is a problem.
(.. is referred as parent directory)
If you try to run your app with some sub-url (also known as sub context) as http://localhost:3000/sub-url/ and you keep your images parallel to sub-url folder it will automatically work.
-- /
|
|-- sub-url
|
|-- index.html
|-- images
|
|-- some-icon.svg
Another option can be override the component SCSS with yours.
You already found the solution to use resolve-url-loader, but in this case you need to import the component's scss file into you scss.
so your webpack config should look like:
const webpack = require('webpack');
const path = require('path');
module.exports = {
entry: './src/index.js',
devtool: 'inline-module-source-map',
output: {
path: path.resolve(__dirname, '/dist'),
filename: 'bundle.js',
publicPath: '/',
},
module: {
rules: [
{
test: /\.js$/,
use: {
loader: 'babel-loader',
},
},
{
test: /\.scss$/,
use: [
{ loader: 'style-loader' },
{ loader: 'css-loader' },
// CHANGE HERE
{
loader: 'resolve-url-loader',
options: {
root: '/images', // considering all your images are placed in specified folder. Note: this is just a string that will get as prefix to image path
includeRoot: true,
absolute: true,
},
},
{
loader: 'sass-loader',
options: {
sourceMap: true,
sourceMapContents: false,
},
},
],
},
{
test: /\.css$/,
loaders: ['style-loader', 'css-loader'],
},
{
test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
use: {
loader: 'url-loader?name=/images/[name].[ext]',
options: {
limit: 10000,
},
},
},
],
},
resolve: {
extensions: ['.js', '.jsx'],
// modules: [path.resolve(__dirname, '/images'), 'node_modules'],
alias: {
'react-redux': path.resolve('./node_modules/react-redux'),
},
},
plugins: [new webpack.HotModuleReplacementPlugin()],
devServer: {
hot: true,
publicPath: '/dist/',
},
};
I hope it helps.

bundle.js not found with webpack dev server

I'm having an issue with React/Redux/Webpack/Router.
Any "sub pages", such as: "/home/test", "users/registration" etc... fail to be loaded - and I get errors loading the "bundle.js" file generated by webpack.
The reason seems to be that the request to fetch the "bundle.js" is with the following url:
for path "/home/test": "/home/bundle.js"
for path "/users/registration": "/users/bundle.js"
Same issue occurs with the loading of "css" files and other resources.
This is my webpack configuration:
const { resolve } = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const OpenBrowserPlugin = require('open-browser-webpack-plugin');
const config = {
devtool: 'cheap-module-eval-source-map',
entry: [
'react-hot-loader/patch',
'webpack-dev-server/client?http://localhost:8080',
'webpack/hot/only-dev-server',
'./main.js',
//'./assets/scss/main.scss',
],
output: {
filename: 'bundle.js',
path: resolve(__dirname, 'dist'),
publicPath: '/',
},
context: resolve(__dirname, 'src'),
devServer: {
hot: true,
contentBase: resolve(__dirname, 'build'),
publicPath: '/',
historyApiFallback: true
},
module: {
rules: [
/* {
enforce: "pre",
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loader: "eslint-loader"
}, */
{
test: /\.(js|jsx)$/,
loaders: [
'babel-loader',
],
exclude: /node_modules/,
},
{
test: /\.(scss|sass)$/,
exclude: /node_modules/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
'css-loader',
{
loader: 'sass-loader',
query: {
sourceMap: false,
},
},
],
publicPath: '../'
}),
},
{ test: /\.(png|jpg|gif)$/, use: 'url-loader?limit=15000&name=images/[name].[ext]' },
{ test: /\.eot(\?v=\d+.\d+.\d+)?$/, use: 'file-loader?&name=fonts/[name].[ext]' },
{ test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, use: 'url-loader?limit=10000&mimetype=application/font-woff&name=fonts/[name].[ext]' },
{ test: /\.[ot]tf(\?v=\d+.\d+.\d+)?$/, use: 'url-loader?limit=10000&mimetype=application/octet-stream&name=fonts/[name].[ext]' },
{ test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, use: 'url-loader?limit=10000&mimetype=image/svg+xml&name=images/[name].[ext]' },
]
},
plugins: [
new webpack.LoaderOptionsPlugin({
test: /\.js$/,
options: {
eslint: {
configFile: resolve(__dirname, '.eslintrc'),
cache: false,
}
},
}),
new webpack.optimize.ModuleConcatenationPlugin(),
new ExtractTextPlugin({ filename: './styles/style.css', disable: true, allChunks: true }),
new CopyWebpackPlugin([{ from: 'vendors', to: 'vendors' }]),
new OpenBrowserPlugin({ url: 'http://localhost:8080' }),
new webpack.HotModuleReplacementPlugin(),
],
};
module.exports = config;
It seems as if it always uses "../bundle.js" to find it for some reason.
Any help would be appreciated :)
Thank you,

css modules object import returns empty

I am trying to use css modules inside react, but it is not working.
The log of this code:
import React from 'react'
import styles from '../../css/test.css'
class Test extends React.Component {
render() {
console.log(styles)
return (
<div className={styles.app}>
<p>This text will be blue</p>
</div>
);
}
}
export default Test
returns Object {}
and the rendered code are tags with no class:
<div><p>This text will be blue</p></div>
The css code is available at site, here is my test.css:
.test p {
color: blue;
}
If I changed the div to have class='test', the color of p changes to blue
Here is my webpack.config.js
var path = require('path')
var webpack = require('webpack')
var HappyPack = require('happypack')
var BundleTracker = require('webpack-bundle-tracker')
var path = require('path')
var ExtractTextPlugin = require("extract-text-webpack-plugin")
function _path(p) {
return path.join(__dirname, p);
}
module.exports = {
context: __dirname,
entry: [
'./assets/js/index'
],
output: {
path: path.resolve('./assets/bundles/'),
filename: '[name].js'
},
devtool: 'inline-eval-cheap-source-map',
plugins: [
new BundleTracker({filename: './webpack-stats.json'}),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery'
}),
new HappyPack({
id: 'jsx',
threads: 4,
loaders: ["babel-loader"]
}),
new ExtractTextPlugin("[name].css", { allChunks: true })
],
module: {
loaders: [
{
test: /\.css$/,
include: path.resolve(__dirname, './assets/css/'),
loader: ExtractTextPlugin.extract("style-loader", "css-loader!resolve-url-loader?modules=true&localIdentName=[name]__[local]___[hash:base64:5]")
},
{
test: /\.scss$/,
include: path.resolve(__dirname, './assets/css/'),
loader: ExtractTextPlugin.extract("style-loader", "css-loader!resolve-url-loader!sass-loader?modules=true&localIdentName=[name]__[local]___[hash:base64:5]")
},
{
test: /\.jsx?$/,
include: path.resolve(__dirname, './assets/js/'),
exclude: /node_modules/,
loaders: ["happypack/loader?id=jsx"]
},
{
test: /\.png$/,
loader: 'file-loader',
query: {
name: '/static/img/[name].[ext]'
}
}
]
},
resolve: {
modulesDirectories: ['node_modules'],
extensions: ['', '.js', '.jsx'],
alias: {
'inputmask' : _path('node_modules/jquery-mask-plugin/dist/jquery.mask')
},
}
}
Can anyone help me?
Thanks in advance.
Looks like your passing the css-loader params to the resolve-url-loader:
"css-loader!resolve-url-loader?modules=true&localIdentName=[name]__[local]___[hash:base64:5]"
Should be:
"css-loader?modules=true&localIdentName=[name]__[local]___[hash:base64:5]&importLoaders=1!resolve-url-loader"
A lot of time passed since this question, so my webpack was update many times with another technologies.
This webpack config is working:
...
module.exports = {
entry,
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist'),
publicPath: '/'
},
devtool:
process.env.NODE_ENV === 'production' ? 'source-map' : 'inline-source-map',
module: {
rules: [
{
test: /\.jsx?$/,
include: path.resolve(__dirname, './app/view/'),
exclude: /node_modules/,
loader: 'babel-loader'
},
{
test: /\.pcss$/,
include: path.resolve(__dirname, './app/view/'),
use: [
{
loader: 'style-loader'
},
{
loader:
'css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]'
},
{
loader: 'postcss-loader',
options: {
plugins: function() {
return [
require('postcss-import'),
require('postcss-mixins'),
require('postcss-cssnext')({
browsers: ['last 2 versions']
}),
require('postcss-nested'),
require('postcss-brand-colors')
];
}
}
}
],
exclude: /node_modules/
},
{
test: /\.(png|svg|jpg|webp)$/,
use: {
loader: 'file-loader'
}
}
]
},
resolve: {
extensions: ['.js', '.jsx'],
modules: [path.resolve(__dirname, 'node_modules')]
},
plugins
};
I guess that there is an issue with older versions at webpack with this line:
'css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]'
Try importLoaders and importLoader
You can see my repo too.
In my specific case, I'm using official utility facebook/create-react-app. You have to run the following command to get access to the webpack configuration:
npm run eject
You will then need to edit config/webpack.config.js and set the css-loader modules option to true.
use: getStyleLoaders({
importLoaders: 1,
sourceMap: isEnvProduction && shouldUseSourceMap,
modules:true <-----
}),

Resources