How to remove duplicated dependencies code from webpack bundle? - node.js

I have these local NPM packages:
common-package
^ ^
| |
father-package mother-package
^ ^
| |
son-package
Both father-package and mother-package import common-package, and then son-package imports both father-package and mother-package
The problem here is that the son-package bundle duplicates the common-package code. The common-package has a User.ts class and as you can see there are 2 definitions of the User.ts class in the output bundle when searching for "class User {":
My goal is to dedupe it. I believe that is possible by tweaking webpack.config.js optimization but i cant figure how.
Here is what I have tried so far:
son-package webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
plugins:[
new HtmlWebpackPlugin({
template: './index.html',
inject: true,
filename: './index.html'
})
],
optimization: {
splitChunks: {
cacheGroups: {
commons: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all',
},
},
},
},
mode: 'development',
devtool: 'source-map',
target: 'es2017',
entry: {
index: './src/Index.ts'
},
output: {
path: `${path.resolve('dist')}`,
filename: '[name].js',
library: {
type: 'module'
},
chunkFormat: 'module'
},
module: {
rules: [
{
test: /\.(ts|tsx)$/,
use: 'ts-loader',
exclude: /node_modules/
},
{
test: /\.(js|jsx)$/,
use: 'babel-loader',
exclude: /node_modules/
},
],
},
resolve: {
extensions: ['.js', '.ts'],
}
};
Should i add the same optimization configuration in father-package and mother-package to webpack.config.json files?
Hope to have explained my problem well. Thanks in advance.
Btw, my node version is v18.11.0 and NPM is 8.19.2 and webpack 5.

Related

TreeShaking with RxJS 7.x and WebPack 5

I would like to treeshake rxjs in my TypeScript application that is bundled via WebPack:
rxjs#7.5.7
webpack#5.74.0
According to https://rxjs.dev/guide/installation I would have to use the ES2015 exports of rxjs, but I cannot find out how to do that.
Are you aware of an example or a link to some documentation?
My current webpack config is:
const path = require('path');
module.exports = {
entry: './src/index.ts',
devtool: 'source-map',
target: 'node16',
mode: 'production',
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/,
},
],
},
resolve: {
extensions: ['.tsx', '.ts', '.js'],
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
};
This config has successfully tree shaken the rxjs#6 version (which has the module entry point) but it fails to tree shake rxjs#7 and uses the full CJS version instead.
Thanks for any pointers!
Looks like this is a viable approach:
const path = require('path');
module.exports = {
entry: './src/index.ts',
devtool: 'source-map',
target: 'node18.12',
mode: 'development',
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/,
},
],
},
resolve: {
extensions: ['.tsx', '.ts', '.js'],
conditionNames: ['es2015', 'import'],
mainFields: ['es2015', 'module', 'main'],
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
};

Typescript library build

I am new with webpack and I am currently trying to build my library which is similiar to LINQ, Java 8 Stream API #szilanor/stream for npm.
Here is my webpack.config.ts
import {Configuration} from 'webpack';
import TerserPlugin from 'terser-webpack-plugin';
import * as path from 'path';
const config: Configuration = {
mode: 'production',
devtool: 'source-map',
entry: './src/index.ts',
output: {
filename: 'index.js',
path: path.resolve(__dirname, 'build'),
library: 'Stream',
libraryTarget: 'umd',
clean: true,
},
optimization: {
minimize: true,
minimizer: [new TerserPlugin({extractComments: false})],
},
module: {
rules: [
{
test: /\.([mjt])s$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
},
},
],
},
resolve: {
extensions: ['.ts', '.js', '.json'],
},
};
export default config;
as it show I am trying to create an 'umd' bundle with babel and generate the type definitions with tsc.
So my question is that is gonna work in every situation whatever project I am trying to use it in (for example angular, react, node...)? If not can you help me to fix it?

Critical dependency: require function is used in a way in which dependencies cannot be statically extracted - NodeJS, Express & Webpack

I am developing a web application using Node.js, Express & Webpack. Everything was going well until Webpack was upgraded to Webpack 5 and lots of bugs appeared. I have managed to solve all the errors but there is a warning I can't solve. I have seen this post but it's related to Angular so I don't think it helps me much: Critical dependency: require function is used in a way in which dependencies cannot be statically extracted
WARNING in ./node_modules/terser-webpack-plugin/dist/minify.js
Critical dependency: require function is used in a way in which dependencies cannot be statically extracted
This is my webpack.config.js; resolve fields and node-polyfill-webpack-plugin are used to solve Webpack 5 bugs and errors.
const path = require("path")
const NodePolyfillPlugin = require("node-polyfill-webpack-plugin")
const webpack = require('webpack')
const HtmlWebPackPlugin = require("html-webpack-plugin")
module.exports = {
resolve:{
fallback: {
"fs": false,
"path": false,
"worker_threads":false,
"child_process":false,
"http": false,
"https": false,
"stream": false,
"crypto": false,
}
},
entry: {
main: './src/js/main.js',
index:'./src/js/'
},
output: {
path: path.join(__dirname, 'dist'),
//publicPath: '/',
filename: '[name].js'
},
mode:"development",
target: 'web',
devtool: 'source-map',
module: {
rules: [
{
test: /\.(png|jp(e*)g|svg)$/,
use: [{
loader: 'url-loader',
options: {
limit: 8000, // Convert images < 8kb to base64 strings
name: 'images/[hash]-[name].[ext]'
}
}]
},
{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader",
},
{
test: /\.bpmn$/,
use: 'raw-loader'
},
{
// Loads the javacript into html template provided.
// Entry point is set below in HtmlWebPackPlugin in Plugins
test: /\.html$/,
use: [
{
loader: "html-loader",
//options: { minimize: true }
}
]
},
{
test: /\.css$/,
use: [ 'style-loader', 'css-loader' ]
}
]
},
plugins: [
new HtmlWebPackPlugin({
template: '!!raw-loader!./src/views/pages/index.ejs',
filename: "./index.ejs",
excludeChunks: [ 'server', 'main' ]
}),
new HtmlWebPackPlugin({
template: '!!raw-loader!./src/views/pages/bmv.ejs',
filename: "./bmv.ejs",
excludeChunks: [ 'server', 'index' ]
}),
new webpack.NoEmitOnErrorsPlugin(),
new NodePolyfillPlugin()
]
}
configure the webpack:
const path = require('path');
module.exports = {
//...
resolve: {
alias: {
'terser-webpack-plugin': path.resolve(__dirname, 'node_modules/terser-webpack-plugin/dist/minify.js'),
},
},
};

How to fix webpack Error: Cannot find module - on node.js (webpackEmptyContext)

My webpack.config.js is :
const path = require('path');
module.exports = {
entry: './app.ts',
target: 'node',
node: {
__dirname: true
},
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/,
},
],
},
resolve: {
extensions: [ '.tsx', '.ts', '.js' ],
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
};
When I build my project and run it I am getting the following error:
(node:51071) UnhandledPromiseRejectionWarning: Error: Cannot find module '../gather/gatherers/css-usage'
at webpackEmptyContext (webpack:///./node_modules/lighthouse/lighthouse-core/config_sync?:2:10)
at Function.requireGathererFr
This error is raised from a 3rd party library I am using - lighthouse.
How to fix this error ?
For target as node, you might have to use this package webpack-node-externals in order to ignore all modules in node_module folder. Then declare as externals:
const nodeExternals = require('webpack-node-externals');
module.exports = {
externals: [nodeExternals()],
// ...
};

TypeScript typings broken (error TS2687): All declarations of 'iterator' must have identical modifiers

I'm having an issue getting my typings correctly after I've added the router package to my Angular application (which required an upgrade of Core, Common, Compiler etc.).
Googling ob that specific error code led me to a number of problems, the main resolution for which is removing node_modules and typings and recreating them. I've done so but experience the same misbehavior.
On SO, there's another question but it's old, relates to a different versions of most of the packages and I hardly see how it relates to my problem.
Frankly, I'm a bit lost because I have no idea how to troubleshoot it at all. Below is my tsconfig.json if it helps to spot something odd.
edit
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const distribution = path.resolve(__dirname, "distribution");
const application = path.resolve(__dirname, "source/application");
const resources = path.resolve(__dirname, "source/resources");
module.exports = {
entry: "./source/application/main.ts",
output: {
path: distribution,
filename: "bundle.js"
},
module: {
loaders: [
{ test: /\.png$/, loader: "raw-loader", include: [resources] },
{ test: /\.s(a|c)ss$/, loaders: ["raw-loader", "sass-loader"] },
{ test: /\.html$/, loader: "raw-loader", include: [application] },
{ test: /\.ts$/, loader: "ts-loader", include: [application] },
]
},
resolve: {
modules: ["node_modules", application],
extensions: [".js", ".ts"]
},
performance: {},
devtool: "source-map",
context: __dirname,
target: "web",
externals: [],
stats: {},
devServer: {
contentBase: distribution,
port: 3002
},
plugins: [
new HtmlWebpackPlugin({ template: "./source/index.html" }),
new CopyWebpackPlugin([{ from: "./source/resources", to: "resources" }])
]
}
In Webpack.common.js remove the line debug=true, and change the below code
module.exports = {
entry: {
'polyfills': './src/polyfills.ts',
'vendor': './src/vendor.ts',
'app': './src/main.ts'
},
resolve: {
extensions: ['*', '.js', '.ts']
},
module: {
rules: [
]},
plugins: [
new webpack.ContextReplacementPlugin(
// The (\\|\/) piece accounts for path separators in *nix and Windows
/angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/,
helpers.root('./src'), // location of your src
{} // a map of your routes
),
new webpack.optimize.CommonsChunkPlugin({
name: ['app', 'vendor', 'polyfills']
}),

Resources