Webpack renames functions - javascript

Hello i have some problems with webpack. I have this config for webpack
module.exports = {
name: "front",
mode: "production",
context: path.resolve(__dirname, 'src'),
entry: [
'./jquery/photoswipe.addon_offer_and_order.min.js',
'./jquery/photoswipe.min.js',
'./jquery/photoswipe-ui-default.min.js',
'./deprecated.js',
'./index.js',
],
output: {
filename: "index.min.js",
path: path.resolve(__dirname, 'dist')
},
optimization: {
moduleIds: 'named'
}
}
All good but i have a deprecated.js and have all deprecated functions in it...
Example:
function updateSearchCharacteristic(url, category_id) {
console.warn("This method is deprecated please use shopSearch.updateCharacteristic()");
return shopSearch.updateCharacteristic(url, category_id);
}
function moveBlockAnfrageGuest() {
console.warn("This method is deprecated please use shopUser.moveOrderAndOfferLinkForGuest()");
return shopUser.moveOrderAndOfferLinkForGuest();
}
Webpack rename all these functions, if someone used the old functions, he does not see errors and the return does not work ..
How not to rename functions in this file, but compress

I resolved this problem :
npm install -D script-loader terser-webpack-plugin
Added a module into config and 'require' a plugin
const TerserPlugin = require('terser-webpack-plugin')
module: {
rules: [
{
test: /deprecated.js/,
use : [
{
loader: 'script-loader',
options:{
plugins: [
new TerserPlugin({
terserOptions: {
keep_fnames: true,
}
})
]
}
}
]
}
]
}

Related

React : You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file(Local Node module)

I have babel loader in the library. Still after I add the library to the react application while yarn serve, I get the above error.
This is the webpack.dev.config.js (required in the webpack.config.js) in library-
//webpack.dev.config.js
const babelRCPath = require('#appfabric/infra-scripts').getConfigPath('babel', 'plugin');
const babelRCGenerator = require(babelRCPath);
const babelRC = babelRCGenerator([]);
module.exports = {
{
BaseModule: `${process.cwd()}/src/BaseModule`,
BaseObject: `${process.cwd()}/src/BaseObject`,
BaseWidget: `${process.cwd()}/src/widgets/BaseWidget`,
HOCWidget: `${process.cwd()}/src/widgets/HOCWidget`,
PortalWidget: `${process.cwd()}/src/widgets/PortalWidget`,
BaseActivator: `${process.cwd()}/src/application/BaseActivator`,
CorePlugin: `${process.cwd()}/src/application/CorePlugin`,
BaseAppDelegate: `${process.cwd()}/src/application/appdelegates/BaseAppDelegate`,
EmbeddedAppDelegate: `${process.cwd()}/src/default/appdelegates/embedded/EmbeddedAppDelegate`,
ActionType: `${process.cwd()}/src/application/appdelegates/actions/ActionType`,
types: `${process.cwd()}/src/application/appdelegates/actions/types`,
CommandActionType: `${process.cwd()}/src/application/appdelegates/actions/CommandActionType`,
CommandForResponseActionType: `${process.cwd()}/src/application/appdelegates/actions/CommandForResponseActionType`,
PluginRegistryService: `${process.cwd()}/src/default/PluginRegistryService`,
},
mode: 'development',
externals: [
'dcl',
'react',
'react-dom',
'prop-types',
'pubsub',
'semver',
'#appfabric/ui-profiler',
].map(
// Add this regex to each entry to ensure we don't miss any imports like 'web-shell-core/...`
(value) => new RegExp(`^(${value})((\\\\|/|!).+)?$`),
),
output: {
path: `${process.cwd()}/build/dist`,
filename: '[name].js',
library: 'web-shell-core',
libraryTarget: 'umd',
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
use: {
loader: 'babel-loader',
options: babelRC,
},
},
],
},
};
This is the webpack.config.js
const developmentConfig = require('./webpack.dev.config.js');
module.exports = merge(developmentConfig, {
mode: 'production',
output: {
filename: '[name].min.js',
chunkFilename: '[name].min.js',
},
});
First I add a new file Secure.jsx(having the tags) in the library. I do npm install --save <path-to-library> on my application. After I do yarn install. Then I can see the new file Secure.jsx in the node modules in the application. When I try to run the application, I get the error.
Please let me know what am I missing and also which side(library / application) I have to add the code.
You can view my full config here
I think you also need to add this
resolve: {
modules: [
path.resolve('./node_modules')
]
},
Then import like this
import "jquery/dist/jquery.min.js";
import "bootstrap/dist/js/bootstrap.min.js";

variables I defined in webpack.DefinePlugin is undefined

webpack.config.js
const path = require('path')
HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
entry: './src/index.js',
output: {
path: path.join(__dirname, 'dist'),
filename: 'index_bundle.js',
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ["#babel/preset-env", "#babel/preset-react"],
plugins: ["#babel/plugin-proposal-class-properties"]
}
}
},
{
test:/\.css$/,
use:['style-loader','css-loader']
}
]
},
plugins: [
new webpack.DefinePlugin({
APIHOST: JSON.stringify('test'),
BLOCKCHAINHOST: JSON.stringify('test')
}),
new HtmlWebpackPlugin({
template: './src/template.html'
}),
]
}
I defined 2 variables APIHOST and BLOCKCHAINHOST and I tried to console log this in reactjs App.js like so
componentDidMount() {
console.log(APIHOST)
}
The error I'm getting is APIHOST is undefined. I'm not sure what to do here, I've tried adding single quotes for webpack.defineplugin so it looks like 'APIHOST': JSON.stringify('test') but it's still giving me the same error.
You can do like this
plugins: [
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('development')
}
})
],
Then in your code
process.env.NODE_ENV
The version I'm using is
"webpack": "^4.29.6"
It looks like this is a known issue:
https://github.com/webpack/webpack/issues/1977
DefinePlugin doesn't work inside React Components
Fixed later on in Webpack 3:
This is fixed. Since webpack 3, the parser now fully understands ES6 semantics.
What version are you using? Does it make sense to upgrade?

How to include and use DefinePlugin in webpack config?

Hi there i am trying to use the define plugin so i can update the version number to make sure my JS refreshes after releasing a new build. I can't seem to get DefinePlugin to work properly though. I see it in the folder webpack and i'm trying to follow the documentation but i get errors that it isn't found. Here is my config:
const path = require('path'),
settings = require('./settings');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const webpack = require('webpack');
module.exports = {
entry: {
'scrollerbundled': [settings.themeLocation + "js/scroller.js"],
'mapbundled': [settings.themeLocation + "js/shopmap.js"],
'sculptor': [settings.themeLocation + "js/sculptor.js"]
},
output: {
path: path.resolve(__dirname, settings.themeLocation + "js-dist"),
filename: "[name].js"
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env']
}
}
}
],
plugins: [new webpack.DefinePlugin({
PRODUCTION: JSON.stringify(true),
VERSION: JSON.stringify('5fa3b9'),
})]
},
optimization: {
minimizer: [new UglifyJsPlugin({
uglifyOptions: {
mangle: true,
output: {
comments: false
}
}
})]
},
mode: 'production'
}
{
"parser": "babel-eslint",
"extends": [
"airbnb",
"plugin:react/recommended",
"prettier",
"prettier/react"
],
"plugins": ["react", "import", "prettier"],
"env": {
"browser": true
},
"settings": {
"import/resolver": {
"webpack": {
"config": "webpack.dev.js"
}
}
}
}
That's my eslintrc. This is for use absolute imports created in your webpack config with the modules alias. You need to install eslint-import-resolver-webpack
I Have "webpack": "^4.28.4" and define in webpack config
new webpack.DefinePlugin({
PRODUCTION: JSON.stringify(true),
});
if you console that variables, you don't find it. I use in conditional
if (PRODUCTION) {
//do stuff
}
Another case is to set globals variables in a object and share with webpack.
here is an example
new webpack.ProvidePlugin({
CONFIG: path.resolve(__dirname, './CONSTS.js')
}),
// the path is src/CONST.JS
In the eslintrc file you can add that variables to avoid import errors.
"settings": {
"import/resolver": {
"webpack": {
"config": "webpack.dev.js"
}
}
}
then in any file you can use import {value} from 'CONFIG'
If you are using laravel mix, you can place that new webpack.DefinePlugin code into the plugins array of your .webpackConfig block:
webpack.mix.js:
mix
.webpackConfig({
devtool: 'source-map',
resolve: {
alias: {
'sass': path.resolve('resources/sass'),
}
},
plugins: [
new webpack.ProvidePlugin({
'window.Quill': 'quill', // <--------------------- this right here
__VERSION__: JSON.stringify('12345')
})
]
})
.js('resources/js/app.js', 'public/js')
.sass('resources/sass/app.scss', 'public/css')
.copy([
'resources/fonts/*',
], 'public/fonts');
By extrapolation, that means you can also add this code to the similar block in your regular (not laravel mix) webpack config.
Install devtools globally
npm install -g #vue/devtools
... and try again.
If уоu have any issues try following the official instructions.

webpack 2 multiple entries yet use react hot loader

I used this and it work in webpack 1
entry: {
vendor : ['react', 'react-dom', 'react-router', 'classnames', 'lodash', 'alt'],
app : ['webpack-dev-server/client?http://localhost:8080',
'webpack/hot/only-dev-server',
path.resolve(__dirname, PATHS.app, 'entries', 'app.js')],
otherFile : ['webpack-dev-server/client?http://localhost:8080',
'webpack/hot/only-dev-server',
path.resolve(__dirname, PATHS.app, 'entries', 'otherFile.js')]
}
But this won't work in webpack 2, it worked when I removed the landing property. How do I use HMR and multiple entires? in this guide https://webpack.js.org/guides/hmr-react/ it used array but in my case I'm also using multiple entries.
Could you add the complete config?
I was having an issue, but it turned out that the culprit was a misconfigured proxy.
I had it set to something like for webpack 1:
proxy: {
'/api*': {
target: 'http://0.0.0.0:3000',
secure: false
},
'/admin': {
bypass: () => 'admin.html'
}
},
But in webpack 2 I had to change it to:
proxy: {
'/api': {
target: 'http://0.0.0.0:3000',
secure: false,
bypass: (req, res, opts) => {
if (req.originalUrl === '/admin') {
return 'admin.html';
}
}
}
},
In your files, where are you trying to point path.resolve to? I have the webpack config on the root directory, and it lets me just do:
entry: {
main: [
'babel-polyfill',
'whatwg-fetch',
'react-hot-loader/patch',
'webpack-dev-server/client?http://0.0.0.0:8000',
'webpack/hot/only-dev-server',
'./app/components/main.jsx'
]
}

External source maps for minified, transpiled ES6 code with webpack and gulp

I'm writing ES6 code and transpile it to ES5 with Babel, then minify with Uglify. All run with webpack via gulp. I would like to use external source maps (to keep filesize as small as possible).
The gulp task is pretty basic - all the funky stuff is in the webpack config:
var gulp = require("gulp");
var webpack = require("gulp-webpack");
gulp.task("js:es6", function () {
return gulp.src(path.join(__dirname, "PTH", "TO", "SRC", "index.js"))
.pipe(webpack(require("./webpack.config.js")))
.pipe(gulp.dest(path.join(__dirname, "PTH", "TO", "DEST")));
});
webpack.config.js:
var path = require("path");
var webpack = require("webpack");
module.exports = {
output: {
filename: "main.js",
sourceMapFilename: "main.js.map"
},
devtool: "#inline-source-map",
module: {
loaders: [
{ test: path.join(__dirname, "PTH", "TO", "SRC"),
loader: "babel-loader" }
]
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
},
output: {
comments: false,
semicolons: true
},
sourceMap: true
})
]
};
The above works and it creates working source maps - but they are inline.
If I change webpack.config.js so that it says devtool: "#source-map", the source map is created as a separate file (using sourceMapFilename as filename). But it isn't usable - Chrome dev tools doesn't seem to understand it. If I remove the webpack.optimize.UglifyJsPlugin the source map is usable - but the code is not minified. So source map works for the two individual steps, but not when they are run in sequence.
I suspect the uglify step ignores the external sourcemap from the previous transpiler step, so the sourcemap it generates is based on the stream, which of course doesn't exist outside of gulp. Hence the unusable source map.
I'm pretty new to webpack so I may be missing something obvious.
What I'm trying to do is similar to this question, but with webpack instead of browserify: Gulp + browserify + 6to5 + source maps
Thanks in advance.
I highly recommend putting your webpack config inside the gulpfile, or at least make it a function. This has some nice benefits, such as being able to reuse it for different tasks, but with different options.
I also recommend using webpack directly instead of using gulp-webpack (especially if it's the only thing you're piping through). This will give much more predictable results, in my experience. With the following configuration, source maps work fine for me even when UglifyJS is used:
"use strict";
var path = require("path");
var gulp = require("gulp");
var gutil = require("gulp-util");
var webpack = require("webpack");
function buildJs (options, callback) {
var plugins = options.minify ? [
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false,
},
output: {
comments: false,
semicolons: true,
},
}),
] : [];
webpack({
entry: path.join(__dirname, "src", "index.js"),
bail: !options.watch,
watch: options.watch,
devtool: "source-map",
plugins: plugins,
output: {
path: path.join(__dirname, "dist"),
filename: "index.js",
},
module: {
loaders: [{
loader: "babel-loader",
test: /\.js$/,
include: [
path.join(__dirname, "src"),
],
}],
},
}, function (error, stats) {
if ( error ) {
var pluginError = new gutil.PluginError("webpack", error);
if ( callback ) {
callback(pluginError);
} else {
gutil.log("[webpack]", pluginError);
}
return;
}
gutil.log("[webpack]", stats.toString());
if (callback) { callback(); }
});
}
gulp.task("js:es6", function (callback) {
buildJs({ watch: false, minify: false }, callback);
});
gulp.task("js:es6:minify", function (callback) {
buildJs({ watch: false, minify: true }, callback);
});
gulp.task("watch", function () {
buildJs({ watch: true, minify: false });
});
I would recommend using webpack's devtool: 'source-map'
Here's an example webpack.config with source mapping below:
var path = require('path');
var webpack = require('webpack');
module.exports = {
devtool: 'source-map',
entry: ['./index'],
output: {
filename: 'bundle.js',
path: path.join(__dirname, 'public'),
publicPath: '/public/'
},
module: {
loaders: [
{ test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ }
]
},
plugins: [
]
};

Categories