How to remove console logs from Production Build in Vue 3 - vue.js

Here is my vue.config.js file. I have followed the instructions given here: https://github.com/JayeshLab/demo-vue-console-log-removal
Still I can see logs in browser, what else am I missing?
const TerserPlugin = require("terser-webpack-plugin");
const isProd = true
module.exports = {
lintOnSave: false,
devServer: {
proxy: 'http://localhost:3000/'
},
chainWebpack: config => {
config.module
.rule('vue')
.use('vue-loader')
.tap(args => {
})
},
configureWebpack: {
optimization: {
minimize: true,
minimizer: isProd ? [
new TerserPlugin({
terserOptions: {
compress: {
drop_console: true
},
output: {
comments: false
}
}
})
] : []
}
}
}

Managed to solve it by changing babel.config.js configuration. Added transform-remove-console plugin
const removeConsolePlugin = []
if(process.env.NODE_ENV == 'staging' || process.env.NODE_ENV == 'production') {
removeConsolePlugin.push("transform-remove-console")
}
module.exports = {
presets: [
'#vue/cli-plugin-babel/preset'
],
plugins: removeConsolePlugin
}

Related

Terser Plugin doesnt run with Vue CLI 5 on vue build

I am trying to create a production build with the following configureWebpack but Terser doesnt run during build.
Code is not minimized or uglified. Ialso tried hidden-source-map
Using "terser-webpack-plugin": "^5.3.3" with #vue/cli#5.0.7
isProd is correctly set to true.
const TerserPlugin = require('terser-webpack-plugin');
const isProd = process.env.NODE_ENV === 'production';
module.exports = {
publicPath: '/',
devServer: {
host: 'staging-beta.myDomain.com',
port: 9000,
allowedHosts: 'all',
},
transpileDependencies: ['vuetify'],
chainWebpack: (config) => {
// reducted code
},
configureWebpack: {
devtool: 'source-map',
optimization: {
minimize: isProd,
minimizer: isProd
? [
new TerserPlugin({
minify: TerserPlugin.uglifyJsMinify,
terserOptions: {
compress: {
drop_console: true,
},
output: {
comments: false,
},
},
}),
]
: [],
},
},
};
The correct setup is:
module.exports = defineConfig({
terser: {
minify: 'uglifyJs',
terserOptions: {
compress: {
drop_console: true,
},
},
},
})
You also need to npm install uglify-js
comments under output is deprecated.

How to change filename inside a rule? (Vue CLI 5)

I have this rule, using vue inspect
/* config.module.rule('svg') */
{
test: /\.(svg)(\?.*)?$/,
type: 'asset/resource',
generator: {
filename: 'img/[name][ext]'
}
},
I need to change filename for example to "[contenthash][ext]"
but I cannot do it using
module.exports = defineConfig({
chainWebpack: (config) => {
config.module.rule("svg").generator.filename = "[contenthash][ext]";
},
})
because I cannot set generator ,
I can rewrite all rules using
module.exports = defineConfig({
configureWebpack: (config) => {
config.module.rules = [
{
test: /\.(svg)(\?.*)?$/,
use: [
{
loader: "svg-inline-loader",
options: {
name: "[contenthash].[ext]",
},
},
],
},
];
},
})
but I need other rules to exist... so how can I change fileName of svg?
Try this:
chainWebpack: (config) => {
config.module.rule("svg")
.set('generator', {
filename: "[contenthash][ext]"
})
}
Source

Webpack optimise and compress CSS and Javascript based on production mode inside webpack.config.js

I have the following NPM scripts inside package.json:
"scripts": {
"start": "cross-env NODE_ENV=development webpack --mode development",
"build": "cross-env NODE_ENV=production webpack --mode production"
},
if I run npm run build (production mode) I want to add optimization (see below) to compress my CSS and Uglify the Javascript. How do I achieve that?
optimization: {
minimizer: [new TerserJSPlugin({}), new OptimizeCSSAssetsPlugin({})],
},
if I run npm start I want to watch the files and further the same as production mode except optimization. I am building a Drupal site so I need to build the assets also in development.
My webpack.config.js looks like this now:
const path = require('path');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CopyPlugin = require('copy-webpack-plugin');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const webpack = require('webpack');
const autoprefixer = require('autoprefixer');
const config = {
entry: {
main: "./src/index.js",
courses: "./src/courses.js",
vendor: "./src/vendor.js"
},
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
},
plugins: [
new MiniCssExtractPlugin({ filename: '[name].css' }),
new CopyPlugin([
{ from: './src/assets/images', to: 'assets/images' },
{ from: './src/assets/icons', to: 'assets/icons' }
]),
],
module: {
rules: [
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
{ loader: 'css-loader', options: { importLoaders: 1 } },
'postcss-loader',
]
},
{
test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
use: {
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: './assets/fonts',
},
},
}
]
}
};
module.exports = (env, argv) => {
if (argv.mode === 'development') {
//...
}
if (argv.mode === 'production') {
//...
}
return config;
};
How do I build this in?
I fix it by adjusting webpack.config.js like below:
const path = require('path');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CopyPlugin = require('copy-webpack-plugin');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const webpack = require('webpack');
const autoprefixer = require('autoprefixer');
const config = {
//Entry Point
entry: {
main: "./src/index.js",
courses: "./src/courses.js",
vendor: "./src/vendor.js"
},
//Output
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
},
//Watch
watch: false,
watchOptions: {
ignored: ['node_modules']
},
//Loader
module: {
rules: [
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
{ loader: 'css-loader', options: { importLoaders: 1 } },
'postcss-loader',
]
},
{
//For fonts
test: /\.(woff|woff2|ttf|otf|eot)$/,
use: [
{
//using file-loader too
loader: "file-loader",
options: {
outputPath: "fonts"
}
}
]
}
]
},
//plugin
plugins: [
new MiniCssExtractPlugin({ filename: '[name].css' }),
new CopyPlugin([
{ from: './src/assets/images', to: 'assets/images' },
{ from: './src/assets/icons', to: 'assets/icons' }
]),
],
};
module.exports = (env, argv) => {
if (argv.mode === 'development') {
//...
config.mode = "development";
config.watch = true;
}
if (argv.mode === 'production') {
//...
config.mode = "production";
config.optimization = {
splitChunks: {
chunks: "all"
},
minimize: true,
minimizer: [
new OptimizeCssAssetsPlugin(),
new TerserPlugin({
cache: true
})
]
};
}
return config;
};
If anybody have improvements on above, please let me know.

How can I have both a vue.config.js and babel.config.js working together?

Having added also a vue.config.js next to my babel.config.js I realized that the code doesn't get transpiled to ES5 anymore, probably because babel.config.js is fully ignored once there's a vue.config.js (?)
How can I keep babel transpiling the code when building with the presets given while yet having a vue.config.js with other configurations?
babel.config.js
module.exports = {
presets: [['#vue/app', { useBuiltIns: 'entry', corejs: 'core-js#2' }]],
}
vue.config.js
const TerserPlugin = require('terser-webpack-plugin')
module.exports = {
configureWebpack: config => {
if (process.env.NODE_ENV === 'production') {
config.optimization.minimizer = [
new TerserPlugin({
terserOptions: {
// needed for vuex-typex to work in production:
keep_fnames: true,
},
}),
]
}
},
css: {
loaderOptions: {
sass: {
data: `#import "./src/core/style/core/_variables.scss";`,
},
},
},
runtimeCompiler: true,
}

webpack build css rules have different order then in development

I am not sure if this is a webpack issue, vue-loader for webpack issue or just something that I am doing wrong.
When I am running npm run build to build a distribution for my Vue.js application the CSS rules applied in the dist app are in different order then in my development environment thus my CSS overrides are different and app doesn't render right...
Here is demonstration for one element:
npm run dev - proper render
npm run build - improper render
UPDATE: added webpack config files
webpack.base.conf.js
var path = require('path')
module.exports = {
entry: {
app: './src/main.js'
},
output: {
path: path.resolve(__dirname, '../dist/static'),
publicPath: '/static/',
filename: '[name].js'
},
resolve: {
extensions: ['', '.js', '.vue'],
alias: {
'src': path.resolve(__dirname, '../src')
}
},
resolveLoader: {
root: path.join(__dirname, 'node_modules')
},
module: {
preLoaders: [
{
test: /\.vue$/,
loader: 'eslint',
exclude: /node_modules/
},
{
test: /\.js$/,
loader: 'eslint',
exclude: /node_modules/
}
],
loaders: [
{
test: /\.vue$/,
loader: 'vue'
},
{
test: /\.js$/,
loader: 'babel',
exclude: /node_modules/
},
{
test: /\.json$/,
loader: 'json'
},
{
test: /\.scss$/,
loaders: ['style', 'css?sourceMap', 'sass?sourceMap']
},
{
test: /\.(png|jp?g|gif|svg|woff2?|eot|ttf)(\?.*)?$/,
loaders: [
'url?limit=20000&name=[name].[ext]?[hash:7]',
'image-webpack?{progressive:true, optimizationLevel: 7, interlaced: false, pngquant:{quality: "65-90", speed: 4}}'
]
},
{
test: /\.html$/,
loader: 'html'
}
]
},
eslint: {
formatter: require('eslint-friendly-formatter')
},
vue: {
loaders: {
sass: 'style!css!sass?indentedSyntax'
}
},
stylus: {
use: [require('nib')()],
import: ['~nib/lib/nib/index.styl']
}
}
webpack.dev.conf.js
var webpack = require('webpack')
var config = require('./webpack.base.conf')
var HtmlWebpackPlugin = require('html-webpack-plugin')
// eval-source-map is faster for development
config.devtool = '#eval-source-map'
// add hot-reload related code to entry chunks
var polyfill = 'eventsource-polyfill'
var devClient = './build/dev-client'
Object.keys(config.entry).forEach(function (name, i) {
var extras = i === 0 ? [polyfill, devClient] : [devClient]
config.entry[name] = extras.concat(config.entry[name])
})
// necessary for the html plugin to work properly
// when serving the html from in-memory
config.output.publicPath = '/'
config.plugins = (config.plugins || []).concat([
// https://github.com/glenjamin/webpack-hot-middleware#installation--usage
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
// https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'src/index.html',
inject: true
})
])
module.exports = config
webpack.prod.conf.js
var webpack = require('webpack')
var config = require('./webpack.base.conf')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
var HtmlWebpackPlugin = require('html-webpack-plugin')
// naming output files with hashes for better caching.
// dist/index.html will be auto-generated with correct URLs.
config.output.filename = '[name].[chunkhash].js'
config.output.chunkFilename = '[id].[chunkhash].js'
// whether to generate source map for production files.
// disabling this can speed up the build.
var SOURCE_MAP = true
config.devtool = SOURCE_MAP ? 'source-map' : false
// generate loader string to be used with extract text plugin
function generateExtractLoaders (loaders) {
return loaders.map(function (loader) {
return loader + '-loader' + (SOURCE_MAP ? '?sourceMap' : '')
}).join('!')
}
// http://vuejs.github.io/vue-loader/configurations/extract-css.html
var cssExtractLoaders = {
css: ExtractTextPlugin.extract('vue-style-loader', generateExtractLoaders(['css'])),
less: ExtractTextPlugin.extract('vue-style-loader', generateExtractLoaders(['css', 'less'])),
sass: ExtractTextPlugin.extract('vue-style-loader', generateExtractLoaders(['css', 'sass'])),
stylus: ExtractTextPlugin.extract('vue-style-loader', generateExtractLoaders(['css', 'stylus']))
}
config.vue = config.vue || {}
config.vue.loaders = config.vue.loaders || {}
Object.keys(cssExtractLoaders).forEach(function (key) {
config.vue.loaders[key] = cssExtractLoaders[key]
})
config.plugins = (config.plugins || []).concat([
// http://vuejs.github.io/vue-loader/workflow/production.html
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"'
}
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
}),
new webpack.optimize.OccurenceOrderPlugin(),
// extract css into its own file
new ExtractTextPlugin('[name].[contenthash].css'),
// generate dist index.html with correct asset hash for caching.
// you can customize output by editing /src/index.html
// see https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({
filename: '../index.html',
template: 'src/index.html',
inject: true,
minify: {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true
// more options:
// https://github.com/kangax/html-minifier#options-quick-reference
}
})
])
module.exports = config
What helped me, was tapping into the html plugin config, by adding this to vue.config.js
chainWebpack: config => {
config
.plugin('html')
.tap(args => {
args[0].chunksSortMode = function (chunk1, chunk2) {
const order = ['first', 'second', 'third']
const order1 = order.indexOf(chunk1.names[0])
const order2 = order.indexOf(chunk2.names[0])
return order1 - order2
}
return args
})
},