webpack duplicate work during serving files - javascript

I've just faced to unpredictable situation during using custom webpack config.
I will try to explain the problem.
This is my simple app (file index.js):
console.log('!!this', this);
This is my webpack config (file webpack.config.js):
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
mode: 'development',
entry: './src/index.js',
plugins: [
new HtmlWebpackPlugin({
template: './public/index.html',
}),
],
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
},
resolve: {
extensions: ['.js', '.jsx', '.json'],
},
module: {
rules: [
{
test: /\.jsx?$/,
loader: 'babel-loader',
},
{
test: /\.css$/i,
use: ['style-loader', 'css-loader'],
},
{
test: /\.scss$/,
use: [
'style-loader',
'css-loader',
{
loader: 'sass-loader',
options: {
additionalData: `#import './src/constants/global';`,
},
},
],
},
{
test: /\.(png|svg|jpe?g|gif)$/i,
use: [
{
loader: 'file-loader',
options: { name: 'img/[name].[ext]' },
},
'image-webpack-loader',
],
},
],
},
};
This is my npm script for launching the app (file package.json):
"scripts": {
"dev": "webpack serve --config webpack.config.js",
},
As a result I see the next picture - all code executes twice (index.js, VM787 index.js).
In addition to that, if I use data fetching callback in my app with this configuration, I will see two equal requests in the Network tab.
Who knows what is the reason for that and how to resolve it?
Thanks!

This might be result of StrictMode. It mounts, unmount and mount conponent again, to check if everything is running correctly. Try removing it from index.js (just to check). Mind that it's useful for its purpose, and it only has this behaviour in dev mode.

If you're importing JavaScript into an HTML file yourself, you'll need to disable injection in the HtmlWebpackPlugin:
new HtmlWebpackPlugin({
template: './public/index.html',
inject: false,
}),

Related

React native web storybook react-native-vector-icons problem icon

I'm developing a react native component on storybook, which uses react-native-paper and react-native-vector-icons.
The problem is that I can't see the icons, I tried to follow the guide on react-native-vector-icons, this: webpack
Below is the webpack, but I didn't quite understand how to use the second part of the code suggested in the guide, where and how I should use it.
Can anyone help me out?
webpack:
const path = require('path')
const HTMLWebpackPlugin = require('html-webpack-plugin')
const HTMLWebpackPluginConfig = new HTMLWebpackPlugin({
template: path.resolve(__dirname, './public/index.html'),
filename: 'index.html',
inject: 'body',
})
module.exports = {
entry: path.join(__dirname, 'index.web.js'),
output: {
filename: 'bundle.js',
path: path.join(__dirname, '/build'),
},
resolve: {
alias: {
'react-native$': 'react-native-web',
'#storybook/react-native': '#storybook/react',
'styled-components/native': 'styled-components',
},
},
module: {
rules: [
{
test: /\.(js|jsx|ts|tsx)$/,
exclude: /node_modules[/\\](?!react-native-vector-icons)/,
use: {
loader: 'babel-loader',
options: {
// Disable reading babel configuration
babelrc: false,
configFile: false,
presets: [
'#babel/preset-env',
'#babel/preset-react',
'#babel/preset-flow',
'#babel/preset-typescript',
{
plugins: ['#babel/plugin-proposal-class-properties', '#babel/plugin-proposal-object-rest-spread'],
},
],
},
},
},
{
test: /\.(jpg|png|woff|woff2|eot|ttf|svg)$/,
loader: 'file-loader',
},
{
test: /\.ttf$/,
loader: 'url-loader', // or directly file-loader
include: path.resolve(__dirname, 'node_modules/react-native-vector-icons'),
},
],
},
plugins: [HTMLWebpackPluginConfig],
devServer: {
historyApiFallback: true,
contentBase: './',
hot: true,
},
}
The reason for your problem could be that your webpack.config.js is located in the folder .storybook.
So you have to change the path for loading the react-native-vector-icons and add ../ before node_modules, because of the folder structure.
...
{
test: /\.ttf$/,
loader: 'url-loader', // or directly file-loader
// add .. to the path for node_modules
include: path.resolve(__dirname, '../node_modules/react-native-vector-icons'),
},
...
An similar issue has been described and solved here: React Native Vector Icons don't load on react-native-web storybook

Deployment Problem with Webpack & Github Pages

I've got a little API App built with Webpack. To publish it on GitHub Pages I've installed the npm package gh-pages.
Everything works fine, the dist-folder is pushed correctly and when I open the live-version the index and scss files are displayed as well.
The problem now is that my bundle.js doesn't load. So the whole functionality is not active. Another thing I've discovered is that my media queries doesn't pop in as well.
Would be great if anyone could help me fixing that issue!
My Repository:
https://github.com/jeanmarc5592/Cocktail-API-Project
My webpack.config.js File:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const multi = require('multi-loader');
module.exports = {
entry: ['babel-polyfill', './src/js/index.js'],
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'js/bundle.js'
},
devServer: {
contentBase: './dist'
},
plugins: [
new HtmlWebpackPlugin({
filename: 'index.html',
template: './src/index.html'
})
],
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
},
{
test: /\.scss$/,
use: {
loader: multi('style-loader!css-loader!sass-loader')
}
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader'
],
},
],
},
};

Objects called in browser after webpack bundle show undefined

I am new to webpack and I want to debug using console.log in my browser and by calling functions to see what works, but whenever I try to do this after my js files are bundled everything shows up as undefined. Webpack must be changing the names somehow when the files get bundled together so even if I make a simple let x = 'hello', I can't console.log it and I can't even call any functions I made without them being undefined when I use them in the console.
How can I fix this so that I can call the objects that I made in the console? Here is my simple webpack config-
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
devtool: 'cheap-module-source-map',
mode: 'development',
entry: {
app:'./src/js/index.js',
test:'./src/js/test2.js',
create: './src/js/create.js'
},
devtool: 'source-map ',
devServer: {
contentBase: './dist',
compress: true,
port: 8080,
},
plugins: [
new HtmlWebpackPlugin({
title: 'Menu',
template: './src/views/index.ejs',
})
],
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [
{
test: /\.scss$/,
use: [
'style-loader',
'css-loader',
'sass-loader'
]
},
{
test: /\.jsnpm$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['#babel/preset-env', {
'debug':true
}]
}
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader'
]
}
]
},
};
https://webpack.js.org/contribute/debugging/
This would be helpful for getting in depth of debugging webpacks! good documentation for debugging webpacks.
In case you want to use browser for debugging, this may be helpful:
Configure webpack to allow browser debugging
Hope this helps!

Webpack Image for React Application

I've read through most posts, but still can't figure out why my application won't display an image. I'm using webpack 4+ in a React application.
My webpack config:
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
mode: 'development',
entry: { main: './src/index.js' },
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
},
module: {
rules: [
{
test: /\.(html)$/,
use: ['html-loader'],
},
{
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['#babel/preset-env', '#babel/preset-react'],
},
},
{
test: /\.(s*)css$/,
use: [
'style-loader',
MiniCssExtractPlugin.loader,
'css-loader',
'sass-loader',
],
},
{
test: /\.(png|jpg|gif)$/,
use: [
{
loader: 'file-loader',
options: {},
},
],
},
],
},
plugins: [
new MiniCssExtractPlugin({
filename: 'style.css',
})
],
resolve: {
extensions: ['.ts', '.tsx', '.js', '.jsx'],
},
devServer: {
historyApiFallback: true,
contentBase: './',
watchOptions: {
aggregateTimeout: 300,
poll: 1000,
},
},
};
I then call an image JSX tag in one of my components <img src={require('../assets/GGGlogo.png')} /> where the assets folder is also contained within my src folder. When I run the webpack dev server, everything compiles successfully and the app starts.
However, my chrome console outputs: GET http://localhost:8080/app/b561359832a3836146dd3f42233e77f7.png 404 (Not Found)
When I run my dev script to make a dist folder with the bundle.js and image, the above hash is indeed the image I want. Why is there a 404 error when trying to find the image?

Webpack module-type sourcemaps are pointing to 'undefined' file

I'm building an app with multiple widgets. These widgets are fairly big in size, so they are placed in separate sub-directories within the parent directory. The file structure looks something like this:
./
+-- server/
|
+-- client/
|
+-- widget1/
|
+-- widget2/
|
+-- widget3/
|
+-- package.json
+-- webpack.base.config
Each widget is a module completely separated from the other client and widgets, and are developed on their own, with their own development servers, etc.
Now the problem: when setting the webpackConfig.devtool to anything that uses module (ie. cheap-module-source-map), the widget files do not receive the correct source-maps. Instead they receive a filename/line number that looks like: (index):40. (or webpack:///:40 when mousing over) When clicking on said file in chrome, it points me to a file with these contents:
undefined
/** WEBPACK FOOTER **
**
**/
Now the incredibly weird thing about this is that even when building the client app, which brings all the widgets and the client-side code together, only the widget files have these messed up source-maps.
The contents of each widget is simply a bunch of .js and .scss files, with an index.html and development-server.js for development. The client side code is virtually the same, expect for the development files.
This is webpack-1, version 1.13.0.
My webpack.base.config looks like such:
const babelQuery = {
es2015: require.resolve('babel-preset-es2015'),
react: require.resolve('babel-preset-react'),
};
function createQuery(...paths) {
return paths.map(resolvePath => `presets[]=${resolvePath}`).join(',');
}
const fullQuery = createQuery(babelQuery.es2015, babelQuery.react);
module.exports = {
cache: true,
context: __dirname,
debug: true,
devtool: '#cheap-module-source-map',
entry: {},
output: {},
resolve: {
extensions: ['', '.js', '.jsx'],
},
module: {
loaders: [
{
test: /\.js$/,
loader: `babel-loader?cacheDirectory,${createQuery(babelQuery.es2015)}`,
exclude: /node_modules/,
},
{
test: /\.jsx$/,
loader: `react-hot-loader!babel-loader?cacheDirectory,${fullQuery}`,
exclude: /node_modules/,
},
{
test: /\.json$/,
loader: 'json-loader',
},
{
test: /\.scss$/,
loader: 'style-loader' +
'!css-loader?modules&sourceMap&localIdentName=[name]__[local]___[hash:base64:5]' +
'!postcss-loader!sass-loader?outputStyle=expanded&sourceMap',
},
{
test: /\.(png|jpg|gif)$/,
loader: 'file-loader?name=img/[name].[ext]',
},
{
test: /\.(ttf|eot|svg|woff(2)?)(\?v=\d+\.\d+\.\d+)?(\?[a-z0-9]+)?$/,
loader: 'file-loader',
},
{
test: /\.css$/,
loader: 'style-loader!css-loader?modules&localIdentName=[name]__[local]___[hash:base64:5]',
include: /flexboxgrid/,
},
{
test: /\.css$/,
loader: 'style-loader!css-loader',
exclude: /flexboxgrid/,
},
],
},
postcss() {
return [autoprefixer];
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('development'),
},
}),
],
};
The widgets' development servers modify the base config like so: (if it matters)
context: __dirname,
entry: {
bundle: [
'webpack/hot/dev-server',
'webpack-hot-middleware/client',
'./entry.jsx',
],
},
output: {
path: path.resolve(__dirname, 'dist'),
publicPath: `http://localhost:${PORT}/assets/`,
filename: '[name].js',
},
Try eval-source-map or source-map.
It's slower I know, but with a small cost of longer rebuilding time in dev mode it works just fine.
My loader in webpack config looks like this:
{
output: {
pathinfo: true,
path: path.join(__dirname, "build"),
filename: "app.js",
publicPath: "/"
},
entry: [
"webpack-dev-server/client?http://0.0.0.0:3000",
"webpack/hot/only-dev-server",
"babel-polyfill",
"whatwg-fetch",
path.join(__dirname, "./main")
],
devtool: "eval-source-map",
module: {
loaders: [
{
test: /\.jsx?$/,
include: [
path.join(__dirname, "src"),
path.join(__dirname, "node_modules/localforage")
],
loader: "react-hot!babel?cacheDirectory"
},
]
}
plugins: [
new webpack.HotModuleReplacementPlugin(),
new HtmlWebpackPlugin(),
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.DefinePlugin({
"process.env": {
"NODE_ENV": "\"development\"",
"BASE_DIR": "\"baseDir\"",
}
})
]
}
and my .babelrc:
{
"presets": ["es2015", "stage-0", "react"],
"plugins": ["transform-decorators-legacy"],
"env": {
"production": {
"presets": ["react-optimize"]
}
}
}

Categories

Resources