How to bundle vendor and main scripts separately using webpack? - reactjs

I really appreciate some help here, in this case, I would Like to separate my vendor.js and my main.js at the final build operation.
I've tried that before to loop through in my package.json devDependency for separate my third party libraries and put it into vendor.js, it is working correctly but it produces vendor.js that is unnecessary in building process since my third library already is in my main.js
here is my weppack.config.js
var config = {
devtool: 'eval-source-map',
cache: true,
entry: {
main: path.join(__dirname, "app", "App.js"),
},
output: {
path: path.join(__dirname, 'scripts', 'js'),
filename: '[name].js',
chunkFilename: '[name].js',
sourceMapFilename: '[file].map',
publicPath: '/scripts/js/'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
['es2015', { modules: false }],
'react',
],
plugins: [
'syntax-dynamic-import',
'transform-object-rest-spread',
'transform-class-properties',
'transform-object-assign',
],
}
},
},
],
},
resolve: {
extensions: ['.js', '.jsx' ,'.css', '.ts'],
alias: {
'react-loadable': path.resolve(__dirname, 'app/app.js'),
},
},
};

Due to this answer
in his webpack.config.js (Version 1,2,3) file, He has
function isExternal(module) {
var context = module.context;
if (typeof context !== 'string') {
return false;
}
return context.indexOf('node_modules') !== -1;
}
in his plugins array
plugins: [
new CommonsChunkPlugin({
name: 'vendors',
minChunks: function(module) {
return isExternal(module);
}
}),
// Other plugins
]
This should solve your problem like mine.

Related

Resolve fonts from ui components with react + webpack 5

I am creating a library with UI components to share among my react projects. Components are created with React and with Webpack 5. This is the webpack config file:
const path = require('path');
const webpack = require('webpack');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
entry: './src/index.js',
mode: 'production',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'index.js',
libraryTarget: 'umd',
library: 'ui-lib',
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: ['babel-loader'],
},
{
test: /\.(png|jpg|gif|svg)$/,
type: 'asset/resource',
},
{
test: /.(ttf|otf|eot|woff(2)?)(\?[a-z0-9]+)?$/,
type: 'asset/resource',
generator: {
filename: '[name][ext]',
},
},
{
test: /\.s[ac]ss$/i,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
modules: true,
sourceMap: false,
},
},
{
loader: 'resolve-url-loader',
options: { sourceMap: true, root: path.resolve(__dirname, 'src') },
},
{
loader: 'sass-loader',
options: {
sourceMap: true,
},
},
],
},
],
},
plugins: [
new MiniCssExtractPlugin({
filename: '[name].[hash].css',
chunkFilename: '[id].[hash].css',
}),
new webpack.ProvidePlugin({
React: 'react',
}),
],
resolve: {
extensions: ['.js', '.jsx', '.scss'],
modules: ['node_modules', path.resolve(__dirname, 'src')],
},
externals: {
react: 'react',
},
};
This is generating a dist/ folder with this content:
Seems everything is fine. The problem is when using this library in a React project, The components seems ok but fonts are not loaded correctly. The console throughs this message:
Failed to decode downloaded font: http://localhost:3000/static/js/GilroySemiBold-webfont.woff2
Fonts are being downloaded but not sure that files are not corrupt.
So, any clue about how can I use the fonts from the library??? Thanks in advance

Webpack 5: Is it possible to output a javascript file non-bundled for configuration

I have a React TypeScript project that uses webpack 5.
I am trying to get a runtime-config.js file that I can change out in production by importing it as decribed in a similar Vuejs Docker issue.
I wanted to use File Loader but found that it's been deprecated in webpack 5
Here's what I want to achieve:
have ./runtime-config.js non bundled so that I can refer to it on the window object
easily reference that file in React (TypeScript) so that this dynamic configuration can be read.
Any help is appreciated.
Below is my webpack configuration:
// webpack.config.js
import path from 'path'
import { Configuration as WebpackConfiguration, DefinePlugin, NormalModuleReplacementPlugin } from 'webpack'
import { Configuration as WebpackDevServerConfiguration } from 'webpack-dev-server';
import HtmlWebpackPlugin from 'html-webpack-plugin'
import ForkTsCheckerWebpackPlugin from 'fork-ts-checker-webpack-plugin'
import ESLintPlugin from 'eslint-webpack-plugin'
import tailwindcss from 'tailwindcss'
import autoprefixer from 'autoprefixer'
const CopyPlugin = require('copy-webpack-plugin');
interface Configuration extends WebpackConfiguration {
devServer?: WebpackDevServerConfiguration;
}
const config: Configuration = {
mode: 'development',
target: 'web',
devServer: {
static: path.join(__dirname, 'build'),
historyApiFallback: true,
port: 4000,
open: true,
liveReload: true,
},
output: {
publicPath: '/',
path: path.join(__dirname, 'dist'),
filename: '[name].bundle.js',
},
entry: {
main: './src/index.tsx',
'pdf.worker': path.join(__dirname, '../node_modules/pdfjs-dist/build/pdf.worker.js'),
},
module: {
rules: [
{
test: /\.(ts|js)x?$/i,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
'#babel/preset-env',
'#babel/preset-react',
'#babel/preset-typescript',
],
},
},
},
{
test: /\.(sa|sc|c)ss$/i,
use: [
'style-loader',
'css-loader',
'sass-loader',
{
loader: 'postcss-loader', // postcss loader needed for tailwindcss
options: {
postcssOptions: {
ident: 'postcss',
plugins: [tailwindcss, autoprefixer],
},
},
},
],
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
loader: 'file-loader',
options: {
outputPath: '../fonts',
},
},
{
test: /runtime-config.js$/,
use: [
{
loader: 'file-loader',
options: {
name: 'runtime-config.js',
},
},
],
},
],
},
resolve: {
extensions: ['.tsx', '.ts', '.js'],
},
plugins: [
new HtmlWebpackPlugin({
template: 'public/index.html',
}),
new NormalModuleReplacementPlugin(
/^pdfjs-dist$/,
(resource) => {
// eslint-disable-next-line no-param-reassign
resource.request = path.join(__dirname, '../node_modules/pdfjs-dist/webpack.js')
},
),
new CopyPlugin({
patterns: [
// relative path is from src
{ from: 'public/images', to: 'images' },
],
}),
// Add type checking on dev run
new ForkTsCheckerWebpackPlugin({
async: false,
}),
// Environment Variable for Build Number - Done in NPM scripts
new DefinePlugin({
VERSION_NUMBER: JSON.stringify(process.env.VERSION_NUMBER || 'development'),
}),
// Add lint checking on dev run
new ESLintPlugin({
extensions: ['js', 'jsx', 'ts', 'tsx'],
}),
],
devtool: 'inline-source-map',
};
export default config

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")

Webpack hot module replacement stuck at [HMR] Waiting for update signal from WDS

I'm using webpack hot module replacement in my react project.
configuration looks like below.
let compilerConfig = {
entry: [
'babel-polyfill',
'webpack-dev-server/client?http://0.0.0.0:9000/',
'webpack/hot/only-dev-server',
path.join(ws.srcDir, 'client', 'src', 'index.js'),
],
devtool: 'source-map',
output: {
path: path.resolve(ws.srcDir, 'public'),
filename: 'main.js',
publicPath: '/'
},
module: {
rules: [
{
test: /\.(?:p|s)?css$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
{
loader: 'css-loader',
options: {
sourceMap: true,
},
},
{
loader: 'postcss-loader',
options: { config: { path: path.join(__dirname, "postcss.config.js") } }
},
],
}),
},
{
test: /\.(png|woff|woff2|eot|ttf)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'url-loader',
},
{
test: /\.(js|jsx)?$/,
include: [
path.resolve(__dirname, 'src'),
path.resolve(__dirname, 'node_modules', 'astro'),
],
loader: 'babel-loader',
options: {
babelrc: false,
presets: [
'react',
'es2015',
'stage-2'
]
},
},
{
test: /\.svg$/i,
use: [
{
loader: "babel-loader",
},
{
loader: "svg-react-loader",
query: {
classIdPrefix: '[name]-[hash:8]__',
propsMap: {
fillRule: 'fill-rule',
foo: 'bar'
},
xmlnsTest: /^xmlns.*$/
}
}
],
},
],
},
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': `"${NODE_ENV}"`,
}),
new ExtractTextPlugin('styles.css'),
new HTMLWebpackPlugin({
template: path.join(ws.srcDir, 'client', 'src', "index.html"),
}),
new webpack.NamedModulesPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
};
const serverConfig = {
contentBase: path.resolve(ws.srcDir, 'client', 'src'),
port: process.env.PORT || '9000',
inline: true,
host: '0.0.0.0',
historyApiFallback: true,
stats: {
colors: true,
},
headers: {
'Access-Control-Allow-Origin': '*'
},
};
And i'm starting webpack dev server through gulp as below.
gulp.task('webpack-dev', function() {
WebpackDevServer.addDevServerEntrypoints(compilerConfig, serverConfig);
const webpackConf = webpack(compilerConfig);
new WebpackDevServer(webpackConf, serverConfig)
.listen('9000', '0.0.0.0', function(err) {
if (err)
throw new Error("webpack-dev-server", err);
// Server listening
console.info("[webpack-dev-server]", "http://localhost:9000");
})
})
Getting [WDS] Disconnected! error after some time. And also i'm not seeing [WDS] Hot Module Replacement enabled. log in the console.
when i do a code change webpack is recompiling, but don't see it reflecting in the browser.
Using below version.
webpack = 2.3.x
webpack-dev-server = 2.4.x
Found the problem. I was loading a script in my index.html. That got failed(404). This is causing Hot Module Replacement to fail.

Migrating from web pack v1.15 config to v2.6.1

Updated webpack to the latest version(2.6.1), so the webpack config file, that came with the boilerplate, became outdated...
Looked at the official documentation on migration, but still a bit lost regarding how exactly i need to update my config file:
'use strict';
const path = require('path');
const webpack = require('webpack');
const NODE_ENV = process.env.NODE_ENV;
const SaveAssetsJson = require('assets-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
module.exports = {
devtool: '#source-map',
// Capture timing information for each module
profile: false,
// Switch loaders to debug mode
debug: false,
// Report the first error as a hard error instead of tolerating it
bail: true,
entry: [
'babel-polyfill',
'./assets/main.jsx',
],
output: {
path: 'public/dist/',
pathInfo: true,
publicPath: '/dist/',
filename: 'bundle.[hash].min.js',
},
resolve: {
root: path.join(__dirname, ''),
modulesDirectories: [
'web_modules',
'node_modules',
'assets',
'assets/components',
],
extensions: ['', '.webpack.js', '.web.js', '.js', '.jsx'],
},
resolveLoader: {
},
plugins: [
new CleanWebpackPlugin(['public/dist'], {
verbose: true,
dry: false,
}),
new webpack.optimize.UglifyJsPlugin({
minimize: true,
output: {
comments: false,
},
compress: {
warnings: false,
screw_ie8: true,
},
}),
new SaveAssetsJson({
path: process.cwd(),
filename: 'assets.json',
}),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production'),
},
}),
],
query: {presets: ['es2015', 'react'] },
module: {
rules: [
{
use: [
"style-loader",
"css-loader",
"autoprefixer-loader",
]
},
{
test: /\.scss$/, // sass files
loader: 'style!css!autoprefixer?browsers=last 2 version!sass?outputStyle=expanded',
},
{
test: /\.(ttf|eot|svg|woff)(\?[a-z0-9]+)?$/, // fonts files
loader: 'file-loader?name=[path][name].[ext]',
},
{
test: /\.jsx?$/, // react files
exclude: /node_modules/,
loaders: ['babel?presets[]=es2015,presets[]=stage-0,presets[]=react'],
include: path.join(__dirname, 'assets'),
},
],
noParse: /\.min\.js/,
}
};
In the end there were few deletion of the deprecated plugin calls and restructuring some of the fields. Here is the 2.6.1 compatible version, the parts of the file that were changed:
'use strict';
module.exports = {
devtool: '#source-map',
// Capture timing information for each module
profile: false,
// Switch loaders to debug mode
//debug: false,
// Report the first error as a hard error instead of tolerating it
bail: true,
entry: [
'babel-polyfill',
'./assets/main.jsx',
],
output: {
path: '/public/dist/', //This has to be an absolute path
publicPath: '/dist/',
filename: 'bundle.[hash].min.js',
},
resolve: {
//merging root and modules
modules: [
path.join(__dirname, ''),
'web_modules',
'node_modules',
'assets',
'assets/components',
],
extensions: [ '.webpack.js', '.web.js', '.js', '.jsx'], //Removed empty entry
},
resolveLoader: {
},
plugins: [
new CleanWebpackPlugin(['public/dist'], {
verbose: true,
dry: false,
}),
new webpack.optimize.UglifyJsPlugin({
minimize: true,
sourceMap: true, //added this
output: {
comments: false,
},
compress: {
warnings: false,
screw_ie8: true,
},
}),
new SaveAssetsJson({
path: process.cwd(),
filename: 'assets.json',
}),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production'),
},
}),
],
module: {
//Modules are slightly differently listed now
rules: [
{
test: /\.(css|scss)$/,
use: [{
loader: "style-loader" // creates style nodes from JS strings
}, {
loader: "css-loader" // translates CSS into CommonJS
}, {
loader: "sass-loader" // compiles Sass to CSS
}]
},
{
test: /\.(js|jsx)$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['es2015', "stage-0", 'react']
}
}
}
],
noParse: /\.min\.js/,
}
};

Resources