How to include node_modules in a bundle file using webpack? - node.js

please help me.
I'm to creating utilize webpack to bundle a simple project. but this problem is that the output
file contains module.exports = require(...).
I want to have everything in one bundle file without module.exports.
main.ts
import moment from "moment";
console.log(moment().year());
main.js <- writed bandle file
/***/ ((module) => {
module.exports = require("moment"); // <- I don't want
/***/ })
webpack.config.ts
module.exports = {
entry: {
main: ["/workspace/apps/background/src/main.ts"],
},
devtool: "source-map",
mode: "development",
output: {
path: "/workspace/dist/background",
filename: "main.js",
hashFunction: "xxhash64",
pathinfo: false,
libraryTarget: "umd",
globalObject: "this",
},
module: {
unsafeCache: true,
rules: [
{
test: {},
loader: "/workspace/node_modules/ts-loader/index.js",
exclude: {},
options: {
configFile: "/workspace/apps/background/tsconfig.app.json",
transpileOnly: true,
experimentalWatchApi: true,
},
},
],
},
resolve: {
extensions: [".ts", ".tsx", ".mjs", ".js", ".jsx"],
alias: {},
plugins: [
{
source: "described-resolve",
target: "resolve",
extensions: [".ts", ".tsx", ".mjs", ".js", ".jsx"],
log: {},
baseUrl: "../..",
absoluteBaseUrl: "/workspace",
},
],
mainFields: ["es2015", "module", "main"],
},
performance: {
hints: false,
},
plugins: [
{
options: {
async: false,
typescript: {
enabled: true,
configFile: "/workspace/apps/background/tsconfig.app.json",
memoryLimit: 2048,
},
},
},
{
patterns: [
{
context: "/workspace/apps/background/src/assets",
to: "assets",
from: "**/*",
globOptions: {
ignore: [".gitkeep", "**/.DS_Store", "**/Thumbs.db"],
dot: true,
},
},
],
options: {},
},
],
watch: false,
watchOptions: {
aggregateTimeout: 200,
},
stats: {
hash: true,
timings: false,
cached: false,
cachedAssets: false,
modules: false,
warnings: true,
errors: true,
colors: true,
chunks: true,
assets: false,
chunkOrigins: false,
chunkModules: false,
children: false,
reasons: false,
version: false,
errorDetails: false,
moduleTrace: false,
usedExports: false,
},
experiments: {
cacheUnaffected: true,
},
target: "node",
node: false,
externals: [null],
};
Is there any solution?

Related

Babel config to SWC

Now I have such babel config on the project and I really want to rewrite this case under swc. Would anyone be able to help with this
module.exports = {
sourceMaps: true,
presets: [
[
'#babel/preset-env',
{
exclude: ['transform-async-to-generator', 'transform-regenerator'],
},
],
'#babel/preset-react',
[
'#babel/preset-typescript',
{
isTSX: true,
allExtensions: true,
},
],
],
plugins: [
'#babel/plugin-syntax-dynamic-import',
['#babel/plugin-proposal-decorators', { legacy: true }],
['#babel/plugin-proposal-class-properties', { loose: true }],
['module:fast-async', { spec: true }],
[
'#babel/plugin-transform-regenerator',
{
asyncGenerators: true,
generators: true,
async: false,
},
],
],
};
Now I have written such a config, but part of the application has stopped working with similar errors: [MobX] Cannot decorate undefined property: 'description'
test: /\.(tsx|ts|jsx|js)$/,
loader: 'swc-loader',
options: {
jsc: {
keepClassNames: true,
parser: {
syntax: 'typescript',
decorators: true,
tsx: true,
dynamicImport: true,
preserveAllComments: false
},
transform: {
legacyDecorator: true,
decoratorMetadata: true
},
loose: false
},
},

How to disable removeViewBox plugin in Next.Js and svgr?

I would like to disable the removeViewBox plugin in Next.js/svgr/svgo. The following next.config.js should work but it does not.
Anybody can help ?
I'm using it with:
"#svgr/webpack": "^6.2.0", "react": "17.0.2", "next": "^12.0.7",
module.exports = {
reactStrictMode: true,
i18n,
webpack(config) {
config.module.rules.push(
{
test: /\.svg$/i,
issuer: /\.[jt]sx?$/,
use: [
{
loader: '#svgr/webpack',
options: {
prettier: false,
svgo: true,
icon: true,
svgoConfig: {
plugins: [
{
name: 'preset-default',
params: {
overrides: {
removeViewBox: false,
},
},
},
],
},
titleProp: true,
},
},
],
})
return config
},
}
For #svgr/webpack#5.5.0 it worked when I added { removeViewBox: false } right to plugins array:
{
loader: '#svgr/webpack',
options: {
svgoConfig: {
plugins: [
{ removeViewBox: false },
],
},
},
},
This is what's worked for my with next#13.0.5 and #svgr/webpack#6.5.1
config.module.rules.push({
test: /\.svg$/i,
issuer: /\.[jt]sx?$/,
use: [{ loader: '#svgr/webpack', options: { icon: true } }]
});

Uncaught TypeError: Cannot read property 'split' of undefined (Webpack)

I'm making an update to a Chrome Extension (using Create React App) of mine, but suddenly I get this error:
Uncaught TypeError: Cannot read property 'split' of undefined
For the following code:
/* WEBPACK VAR INJECTION */(function(process) {
Object.defineProperty(exports, "__esModule", { value: true });
const defer_to_connect_1 = __webpack_require__(1533);
const nodejsMajorVersion = Number(process.versions.node.split('.')[0]);
The error occurs in the last line for (process.versions.node.split('.')[0] and the code is generated by Webpack.
Here is my Webpack Config:
"use strict";
const autoprefixer = require("autoprefixer");
const path = require("path");
const webpack = require("webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const ManifestPlugin = require("webpack-manifest-plugin");
const InterpolateHtmlPlugin = require("react-dev-utils/InterpolateHtmlPlugin");
const SWPrecacheWebpackPlugin = require("sw-precache-webpack-plugin");
const eslintFormatter = require("react-dev-utils/eslintFormatter");
const ModuleScopePlugin = require("react-dev-utils/ModuleScopePlugin");
const paths = require("./paths");
const getClientEnvironment = require("./env");
const publicPath = paths.servedPath;
const shouldUseRelativeAssetPaths = publicPath === "./";
const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== "false";
const publicUrl = publicPath.slice(0, -1);
const env = getClientEnvironment(publicUrl);
if (env.stringified["process.env"].NODE_ENV !== '"production"') {
throw new Error("Production builds must have NODE_ENV=production.");
}
const cssFilename = "static/css/[name].css";
const extractTextPluginOptions = shouldUseRelativeAssetPaths
? { publicPath: Array(cssFilename.split("/").length).join("../") }
: {};
module.exports = {
mode: "production",
externals: ["dns"],
bail: true,
devtool: shouldUseSourceMap ? "inline-source-map" : false,
entry: {
app: [require.resolve("./polyfills"), paths.appIndexJs],
content: [require.resolve("./polyfills"), "./src/content.js"],
},
optimization: {
minimize: false,
},
output: {
path: paths.appBuild,
filename: "static/js/[name].js",
chunkFilename: "static/js/[name].[chunkhash:8].chunk.js",
publicPath: publicPath,
devtoolModuleFilenameTemplate: (info) =>
path
.relative(paths.appSrc, info.absoluteResourcePath)
.replace(/\\/g, "/"),
},
resolve: {
modules: ["node_modules", paths.appNodeModules].concat(
process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
),
extensions: [".web.js", ".mjs", ".js", ".json", ".web.jsx", ".jsx"],
alias: {
"react-native": "react-native-web",
},
plugins: [new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson])],
},
module: {
strictExportPresence: true,
rules: [
{
test: /\.(js|jsx|mjs)$/,
enforce: "pre",
use: [
{
options: {
formatter: eslintFormatter,
eslintPath: require.resolve("eslint"),
},
loader: require.resolve("eslint-loader"),
},
],
include: paths.appSrc,
},
{
oneOf: [
{
test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
loader: require.resolve("url-loader"),
options: {
limit: 10000,
name: "static/media/[name].[hash:8].[ext]",
},
},
{
test: /\.(js|jsx|mjs)$/,
include: paths.appSrc,
loader: require.resolve("babel-loader"),
options: {
compact: true,
},
},
{
test: /\.css$/,
use: [{ loader: MiniCssExtractPlugin.loader }, "css-loader"],
},
{
loader: require.resolve("file-loader"),
exclude: [/\.(js|jsx|mjs)$/, /\.html$/, /\.json$/],
options: {
name: "static/media/[name].[hash:8].[ext]",
},
},
],
},
],
},
plugins: [
new HtmlWebpackPlugin({
inject: true,
template: paths.appHtml,
minify: {
removeComments: true,
collapseWhitespace: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true,
},
}),
new InterpolateHtmlPlugin(HtmlWebpackPlugin, env.raw),
new webpack.DefinePlugin(env.stringified),
new MiniCssExtractPlugin({
filename: cssFilename,
}),
new ManifestPlugin({
fileName: "asset-manifest.json",
}),
new SWPrecacheWebpackPlugin({
dontCacheBustUrlsMatching: /\.\w{8}\./,
filename: "service-worker.js",
logger(message) {
if (message.indexOf("Total precache size is") === 0) {
return;
}
if (message.indexOf("Skipping static resource") === 0) {
return;
}
console.log(message);
},
minify: true,
navigateFallback: publicUrl + "/index.html",
navigateFallbackWhitelist: [/^(?!\/__).*/],
staticFileGlobsIgnorePatterns: [/\.map$/, /asset-manifest\.json$/],
}),
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
],
node: {
dgram: "empty",
fs: "empty",
net: "empty",
tls: "empty",
child_process: "empty",
},
};
I've already tried updating the dependencies, but with little success. What could be the problem?

Issue with line width prittier/eslint airbnb styleguide

I am running into an issue where I can not get my printWidth settings to change. Regardless, of what value I put I can not get the printWidth settings to reflect.
Has anyone run into this before or see any glaring errors in my config files:
prittierrc.js
module.exports = {
printWidth: 500,
singleQuote: true,
trailingComma: 'all',
};
eslintrc.js
const { off } = require('process');
module.exports = {
extends: ['airbnb', 'plugin:prettier/recommended', 'prettier/react'],
env: {
browser: true,
commonjs: true,
es6: true,
jest: true,
node: true,
},
rules: {
'jsx-a11y/href-no-hash': ['off'],
'react/jsx-filename-extension': ['warn', { extensions: ['.js', '.jsx'] }],
'max-len': [
'warn',
{
code: 500,
tabWidth: 2,
comments: 250,
ignoreComments: false,
ignoreTrailingComments: true,
ignoreUrls: true,
ignoreStrings: true,
ignoreTemplateLiterals: true,
ignoreRegExpLiterals: true,
},
],
'no-unused-vars': 'warn',
'no-console': 'off',
},
};
how my editor looks:
click here for imgur url
Its clearly not reflecting the printWidth: 500 setting
Check the spelling on you config file name.

Sass relative import with webpack

I'm trying to import the SCSS files relative to the component in the same folder but ex:
import './ngg.scss';
The strange thing is when I change the path of this SCSS file or using dev server it's working fine but when I run it for the production it doesn't work as if the SCSS file doesn't exist, I'm using web-pack 4, I can't see the issue really because there are some components use relative import and it's working fine, please help!!
module.exports = function makeWebpackConfig(options) {
var BUILD = options.environment === 'prod';
var DEV_SERVER = process.env.WEBPACK_MODE === 'watch';
var config = {
mode: BUILD ? 'production' : 'development',
optimization: {
chunkIds: 'named',
moduleIds: 'hashed',
namedModules: true,
noEmitOnErrors: true,
usedExports: true,
splitChunks: {
cacheGroups: {
commons: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all'
},
desktop: {
test: /Resources\/desktop\/assets\/js/,
name: 'common-desktop',
chunks: 'initial',
minChunks: 5
},
mobile: {
test: /Resources\/mobile\/assets\/js/,
name: 'common-mobile',
chunks: 'initial',
minChunks: 5
}
}
},
minimizer: [
new UglifyJsPlugin({
cache: true,
parallel: true
})
]
},
entry: options.entry,
resolve: {
alias: options.alias,
extensions: ['.js', '.jsx'],
modules: ['node_modules']
},
output: {
path: options.parameters.path ? options.parameters.path : __dirname + '/../../web/compiled/',
publicPath: publicPath,
filename: BUILD ? '[name].[contenthash].js' : '[name].[hash].js',
chunkFilename: BUILD ? '[name].[contenthash].js' : '[name].[hash].js'
},
devServer: {
disableHostCheck: true,
overlay: {
warnings: true,
errors: true
},
headers: {
'Access-Control-Allow-Origin': '*'
}
}
};
config.module = {
rules: [
{
test: /\.jsx?$/i,
loader: 'babel-loader',
exclude: /node_modules/,
options: {
minified: !DEV_SERVER,
cacheDirectory: DEV_SERVER,
presets: ['es2015', 'react']
}
},
{
test: /\.(gif|png|jpe?g)(\?.*)?$/i,
enforce: 'pre',
loader: 'image-webpack-loader',
options: options.parameters.image_loader_options || !DEV_SERVER ? {
optipng: {
optimizationLevel: 7,
progressive: true
}
} : {
disable: true
}
},
{
test: /\.(png|jpg|jpeg|gif|svg)(\?.*)?$/i,
loader: 'file-loader',
options: {
name: '[name].[hash].[ext]'
}
},
{
test: /\.(eot|ttf|woff|woff2)$/,
loader: 'url-loader',
},
{
test: /\.html$/i,
loader: 'raw-loader'
},
{
test: /\.(css|scss)$/i,
use: [
DEV_SERVER ? 'style-loader' : MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
options: {
minimize: false,
sourceMap: true
}
},
{
loader: 'postcss-loader',
options: {
plugins: function () {
return [
autoprefixer({
browsers: ['last 2 version']
})
];
}
}
},
]
},
{
test: /\.scss$/i,
loader: 'sass-loader?sourceMap',
options: {
enforce: 'pre'
}
}
]
};
config.plugins = [
new MiniCssExtractPlugin({
filename: BUILD ? '[name].[id].[chunkhash].css' : '[name].[hash].css'
}),
new PostCssPipelineWebpackPlugin({
suffix: 'critical',
processor: postcss([
criticalSplit({
output: criticalSplit.output_types.CRITICAL_CSS
})
])
}),
new PostCssPipelineWebpackPlugin({
suffix: 'rest',
processor: postcss([
criticalSplit({
output: criticalSplit.output_types.REST_CSS
})
])
}),
new PostCssPipelineWebpackPlugin({
suffix: 'min',
processor: postcss([
csso({
restructure: false,
comments: false
})
]),
map: {
inline: false
}
}),
new AssetsPlugin({
filename: path.basename(options.manifest_path),
path: path.dirname(options.manifest_path)
}),
new webpack.ProvidePlugin({
React: "react",
ReactDOM: "react-dom",
$: "jquery",
jQuery: "jquery"
})
];
if (BUILD) {
config.devtool = 'nosources-source-map';
} else {
config.devtool = 'source-map';
}
return config;
};
Below is my webpack config
module: {
rules: [{
test: /\.scss$/,
use: [
'style-loader',
MiniCssExtractPlugin.loader,
{
loader: "css-loader",
options: {
minimize: true,
sourceMap: true
}
},
{
loader: "sass-loader"
}
]
}
]
}
Then in my js I only need to import like this
import "css/Client/client.scss";
You can view my full config here

Resources