Bundle size is big, how to reduce size of app.js? - vue.js

I am using Vue.js and have only 4 components in my project.
I imported only bootstrap, jquery and lodash:
import { map } from 'lodash';
import 'bootstrap/js/dist/modal';
import $ from "jquery";
But npm run production creates
bundle of 400kb size.
npm run production is configured as shown below.
cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js
Is it possible to reduce bundle size to ~100KB ? If yes how?

You should add bundle analyzer to your webpack config.
That tool will help you to understand what is going on with your final bundle for example:
you have imported something accidentally and didn't noticed that
one of your dependencies is really big and you should avoid using it
you accidentally imported whole library when you just wanted to import single function from that library (that is common with lodash)
Here is an example of how you can add bundle analyzer to your webpack config:
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
const isBundleAnalyze = true; // turn it too true only when you want to analyze your bundle, should be false by default
module.exports = {
// ... rest webpack config here
plugins: [
// ... rest webpack plugins here
...isBundleAnalyze ? [ new BundleAnalyzerPlugin() ] : []
]
};
Also check your final js file.
It should be a single line of code with simple variables. Something like this: !function(e){function t(t){for(var n,r,o=t[0],i=t[1],s=0,l=[];s<o.length;s++) if it doesn't looks like that it means that you configured your production webpack build incorrectly.

It's pretty obvious why your bundle is over 400kb, you are importing lodash and jquery, you are just missing moment.js (a little joke), but one thing that you can do is use only what you need.
First, if you are using Vue, or React, or any of those jQuery UI libraries you shouldn't be using jQuery unless is necessary.
Another thing that you can do is import only what you need, instead of:
import { map } from 'lodash';
try
import map from 'lodash/map';
or even better
import map from 'lodash.map';
https://www.npmjs.com/package/lodash.map
Lazy imports, read more here. This will allow splitting your bundle into pieces that can be called at execution time, reducing considerably your app size.
const Foo = () => import('./Foo.vue')
There is also SSR (Server Side Rendering), which is basically generating the initial HTML code of your app at build time and rendering outputting that, to show the users that something is on the site, but you also need to understand that, this won't do much, since the browser needs to parse the Javascript code (the hydration process) in order to make the site functional.
If you are using React as of April 2021, the React team announced React Server Components, which seems like a big thing coming up, I supposed that many other libraries will be moving components to the server (and I hope Vue does).
Again as of today don't use it on production.
Other answers mentioned the use of webpack-bundle-analyzer, here is a trick how to use it:
webpack.config.js
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
const analyzing = process.env.NODE_ENV === 'analyze';
module.exports = {
plugin: [
...(analyzing ? [new BundleAnalyzerPlugin()] : [])
]
}
on your package.json
{
"scripts": {
"analyze": "NODE_ENV=analyze webpack build"
}
}

use CompressionWebpackPlugin and try gzip

Related

How to prerender a Vue3 application?

I try without success to apply a prerendering (or a SSG) to my Vue3 application to make it more SEO friendly.
I found the vue-cli-plugin-prerender-spa, and when I try it with the command line: vue add prerender-spa I have the error:
ERROR TypeError: Cannot read properties of undefined (reading 'endsWith')
After that I tried prerender-spa-plugin but I have an error when I make a npm run build:
[prerender-spa-plugin] Unable to prerender all routes!
ERROR Error: Build failed with errors.
Error: Build failed with errors.
at /Users/myusername/Workspace/myproject/node_modules/#vue/cli-service/lib/commands/build/index.js:207:23
at /Users/myusername/Workspace/myproject/node_modules/webpack/lib/webpack.js:148:8
at /Users/myusername/Workspace/myproject/node_modules/webpack/lib/HookWebpackError.js:68:3
What do you think about this? Do you have any idea?
Nuxt3 is a really powerful meta-framework with a lot of features and huge ecosystem. Meanwhile, it's in RC2 right now so not 100% stable (may still work perfectly fine).
If your project is aiming for something simpler, I'd recommend using Vitesse. It may be a bit more stable and it's probably powerful enough (check what's coming with it to help you decide).
Some solutions like Prerender also exist but it's paid and not as good as some real SSG (/SSR). Also, it's more of a freemium.
I struggled with the same error output until I found the prerender-spa-plugin-next. Then I notice the latest version of prerender-spa-plugin was published 4 years ago and prerender-spa-plugin-next is continually updating. It seems like that prerender-spa-plugin-next is a new version of prerender-spa-plugin with the same functions. So I use prerender-spa-plugin-next instead of prerender-spa-plugin then everything works fine!
Here is my step:
install the package
npm i -D prerender-spa-plugin-next
modify vue.config.js like
const plugins = [];
if (process.env.NODE_ENV === 'production') {
const { join } = require('path');
const PrerenderPlugin = require('prerender-spa-plugin-next');
plugins.unshift(
new PrerenderPlugin({
staticDir: join(__dirname, 'dist'),
routes: ['/'], //the page route you want to prerender
})
);
}
module.exports = {
transpileDependencies: true,
configureWebpack(config) {
config.plugins = [...config.plugins, ...plugins];
},
};
build
npm run build
Then check the index.html under the dist folder you can see the page is prerendered.
Further usage refers to the homepage of prerender-spa-plugin-next
Found and fix about the scss files to import.
In nuxt.config.ts use :
vite: {
css: {
preprocessorOptions: {
scss: {
additionalData: `
#import "#/assets/scss/_variables.scss";
#import "#/assets/scss/my-style.scss";
`
}
},
},
}
Now my 2 mains issue are : how to install vuetify properly, currently syles and components seems working but the JS not, for example, accordions don't expands on click.
And second topic is to have a i18n module, it seems that vue-i18N no longer works.
Thanks.

How to bundle tailwind css inside a Vue Component Package

In one of my projects, I build a nice vue3 component that could be useful to several other projects. So I decided to publish it as an NPM package and share it with everyone.
I wrote the isolate component, build it and publish BUT I use Tailwind css to make the style.
When I publish and install the component everything is working BUT without the beauty of the css part.
I tried several configurations and alternative tools to generate the package that automatically add the tailwind as an inner dependency to my package.
Does someone have experience with this? how can build/bundle my component by adding the tailwind CSS instructions into it?
You're almost there
Since you've got your component working, the majority of the part has been done.
For configuring the styling of the component you need to identify the Tailwind CSS classes being used by your Vue component package and retain them in the final CSS that is generated by the Tailwind engine in your project.
Follow below steps in the project where you want to use your tailwind vue component package.
For Tailwind CSS V3
// tailwind.config.js
module.exports = [
//...
content: [
"./index.html",
"./src/**/*.{vue,js,ts,jsx,tsx}",
"./node_modules/package-name/**/*.{vue,js,ts,jsx,tsx}" // Add this line
// Replace "package-name" with the name of the dependency package
],
//...
]
For Tailwind CSS V2
// tailwind.config.js
module.exports = [
//...
purge: {
//...
content: [
"./index.html",
"./src/**/*.{vue,js,ts,jsx,tsx}",
"./node_modules/package-name/**/*.{vue,js,ts,jsx,tsx}" // Add this line
// Replace "package-name" with the name of the dependency package
],
//...
//...
}
]
The content property in the tailwind.config.js file defines file path pattern that the tailwind engine should look into, for generating the final CSS file.
For Pro users
You may also try to automate the above setup by writing an install script for your npm package to add this configuration to the tailwind.config.js file
References
Tailwind Docs - 3rd party integration
It's a bit difficult for someone to answer your question as you've not really shared the source code, but thankfully (and a bit incorrectly), you've published the src directory to npm.
The core issue here is that when you're building a component library, you are running npm run build:npm which translates to vue-cli-service build --target lib --name getjvNumPad src/index.js.
The index.js reads as follows:
import component from './components/numeric-pad.vue'
// Declare install function executed by Vue.use()
export function install (Vue) {
if (install.installed) return
install.installed = true
Vue.component('getjv-num-pad', component)
}
// Create module definition for Vue.use()
const plugin = {
install
}
// Auto-install when vue is found (eg. in browser via <script> tag)
let GlobalVue = null
if (typeof window !== 'undefined') {
GlobalVue = window.Vue
} else if (typeof global !== 'undefined') {
GlobalVue = global.Vue
}
if (GlobalVue) {
GlobalVue.use(plugin)
}
// To allow use as module (npm/webpack/etc.) export component
export default component
There is no mention of importing any CSS, hence no CSS included in the built version.
The simplest solution would be to include the index.css import in your index.js or the src/components/numeric-pad.vue file under the <style> section.
Lastly, I'm a bit rusty on how components are built, but you might find that Vue outputs the CSS as a separate file. In that case, you would also need to update your package.json to include an exports field.

Vue: icons are not displayed when css.extract: false

When building a Vue library (component), according to Vue docs, you can set css.extract: false in vue.config.js to avoid the users having to import the CSS manually when they import the library into an app:
vue.config.js
module.exports = {
css: {
extract: false
}
}
However, when you do that, the icons are not displayed in the production build.
In this case I'm using #mdi/font and weather-icons. Neither of them load:
To reproduce
You can reproduce this with this Vue library (component):
Create new Vue project with vue create test
Clone the repo and put in the same directory as the Vue test project
In vue-open-weather-widget set css.extract: false in vue.config.js;
And comment out CSS import:
import 'vue-open-weather-widget/dist/vue-open-weather-widget.css'
Build vue-open-weather-widget with yarn build
Import it into the test Vue app with yarn add "../vue-open-weather-widget";
Serve the test app yarn serve
I have looked at your lib (nice component BTW). I created a build with css: { extract: false } and first looked at the behavior when importing vue-open-weather-widget.umd.js directly into an HTML file. And that worked without any problems.
The thing is that the fonts remain external in the dist after the build. And it seems that there is a problem to find the fonts when your component is loaded in a Webpack project (in our case Vue CLI project). I don't know why the fonts are not referenced correctly. But I have found another, and possibly a better solution.
As it is stated in the MDI docs, the use of the web fonts can negatively affect the page performance. When importing only one icon, all of them are imported, which in turn increases the bundle size. In such a small component this is more than suboptimal, especially for the component users. Therefore here is the alternative solution, also suggested by MDI:
Use #mdi/js instead of #mdi/font
Remove all #mdi/font references in your code and install deps:
npm install #mdi/js #jamescoyle/vue-icon
Replace all icons with SVG(e.g. in MainView.vue). Note that on this way only icons are included in the bundle that are used in your components:
...
<span #click="state.settings.view = 'settings'">
<svg-icon type="mdi" :path="mdiCogOutline"></svg-icon>
</span>
...
import SvgIcon from '#jamescoyle/vue-icon'
import { mdiCogOutline } from '#mdi/js'
...
components: {
SvgIcon
},
data () {
return {
mdiCogOutline: mdiCogOutline
}
},
Adjust vue.config.js:
module.exports = {
css: {
extract: false
}
}
Build component:
# i would also include --formats umd-min
vue-cli-service build --target lib --formats umd-min --name vue-open-weather-widget src/main.js
Now your dist contains only 192.68 KiB vue-open-weather-widget.umd.min.js and the component is ready to use over CDN or in a Vue CLI Project, without importing any CSS or fonts. I have tested both cases. Here is how it looks like:
Hope it helps you! Feel free to ask if you have further questions.

Nuxt ignoring babel on build process

https://nuxtjs.org/api/configuration-build#babel
I originally left the presets as default.
I then followed the suggestions on
https://github.com/nuxt/nuxt.js/issues/1776
However this dealt more with pipelines
I am just trying to get it to convert the es6 to es5 (import chief among the reasons)
I get the same result or a complete failure no matter if i add the .babelrc, adjust package.json, adjust nuxt.config.js or a combination of them.
currently i have adjusted my nuxt.config.js to:
/*
** Build configuration
*/
build: {
babel: {
presets: ['#babel/preset-env'],
configFile: false,
babelrc: false,
plugins: ['#babel/plugin-syntax-dynamic-import']
}
}
When i upload the entire .nuxt folder to my server (running plesk using phusion passenger)
I get the following error
/var/www/vhosts/website.com/app/client/server.js:1
(function (exports, require, module, __filename, __dirname) { import { stringify } from 'querystring'
My site root is
/var/www/vhosts/website.com/app/client/
The first line of server.js
import { stringify } from 'querystring
Changing this to
var stringify = require("querystring").stringify
Eliminates the error however i would need to go through page after page to remove this. My understanding is i can progamically adjust this using babel. But no matter what ive tried the file stays the same.
I did use the Nuxt CLI to automatically set up babel and webpack but using the above build config is not the default. I have attempted to play with it but i get the same result
I added babel/polyfill to try and get around the import issues without any success

pass environment variables during babel build phase for importing different files

I'm building a web (react with webpack & babel) and mobile apps (react-native with expo) for a project. I therefore created a common library for business logic and redux/api library.
Some code will be slightly different between web and mobile. In my case it's localStorage vs AsyncStorage, which I use for authentication among other things...
I'm trying to pass an environment variable for the build stage to switch import of certain files so that the correct file is loaded for each build which are simply path linked (ie no pre-build of my library, I just do import '../mylib') ex:
if(PLATFORM === 'mobile'){
import StorageModule from './mobile-storage-module`
} else {
import StorageModule from './mobile-storage-module`
}
export default StorageModule
Try 1
#babel/preset-env to say if it's mobile or web so that it imports different libraries depending on build like so:
My .babelrc has this:
{
"presets": [
[
"#babel/preset-env",
{
"platform": "mobile"
}
]
]
}
And then in local storage file I do this:
export default () => {
const platform = process.env.platform
if (platform === 'mobile') {
return import './storage-modules/storage-mobile'
}
return import './storage-modules/storage-web'
}
That didn't work, and this also didn't work for me.
Try 2
I installed react-native-dotenv and created a .env file with:
PLATFORM=mobile
And set the plugin in my .babelrc:
{
"presets": [
"babel-preset-expo",
"react-native-dotenv"
]
}
And in my example file, I tried this:
import { PLATFORM } from 'react-native-dotenv'
export default PLATFORM === 'mobile' ? import './storage-modules/storage-mobile' : import './storage-modules/storage-web'
But now my build doesn't work. Any idea how I do dynamic imports during the build process that works for babel in react-native app and webpack build (also uses babel)?
First, #babel/preset-env does not do what you think it does. This is not for specifying your own variables, it is a plugin to automatically use the right target and pollyfills for the browsers you want to support.
The easiest way to get environment variables is with the webpack define plugin (which is part of webpack, so no need to install anything extra)
Just add this to your webpack config.
plugins: [
new webpack.DefinePlugin({
'process.env': {
platform: 'mobile',
},
}),
],
Next, you can't use normal import statements inside of ifs.
import gets resolved before any code runs, either on build by webpack, or in supported environments on script load.
To import something on runtime, you need to use dynamic imports.
Here is an example of how this could look like.
export default new Promise(async resolve => {
resolve(
process.env.platform === 'mobile'
? (await import('./mobile.js')).default
: (await import('./desktop.js')).default
);
});
You can now import from this file like you normally would, but be aware that the default export is a promise.
As your question's title says "during babel build phase", I assume you would like to make different builds for desktop and mobile (not one build for both and load the needed modules dynamically run-time). So I would go like this:
Define the run scripts in package.json for desktop and mobile:
"scripts": {
"devmobile": "cross-env NODE_ENV=development PLATFORM=mobile webpack --progress",
"dev": "cross-env NODE_ENV=development webpack --progress",
}
... or you can create two different webpack.config.js files for desktop and mobile builds but I think the above is easier...
Then npm run devmobile to build for mobile and npm run dev for desktop.
Since I'm on Windows I use the cross-env package but this is the recommended way to be OS independent.
Then I would use Webpack's NormalModuleReplacementPlugin:
(based on this exmaple)
In your webpack.config.js:
// defining the wanted platform for the build (comfing form the npm run script)
const targetPlatform = process.env.PLATFORM || 'desktop';
// then use the plugin like this
plugins: [
new webpack.NormalModuleReplacementPlugin(/(.*)-PLATFORM(\.*)/, function(resource) {
resource.request = resource.request.replace(/-PLATFORM/, `-${targetPlatform}`);
}),
]
...then if you have these two files:
./storage-modules/storage-mobile.js
./storage-modules/storage-desktop.js
import the needed one in your script like this:
import './storage-modules/storage-PLATFORM';
This way the generated build will only contain the needed file for the current PLATFORM used for the build process.
Another possible solution could be the ifdef-loader but I haven't tested it. Maybe worth to try, seems easy.
If you want one build though and import the needed module dynamically, you could do something like this in your app.js (or whatever):
// this needs to have defined when the app is running
const targetPlatform = process.env.PLATFORM || 'desktop';
import(
/* webpackChunkName: "[request]" */
`./storage-modules/storage-${targetPlatform}`
).then(storageModule => {
// use the loaded module
});
or:
(async () => {
const storageModule = await import(
/* webpackChunkName: "[request]" */
`./storage-modules/storage-${targetPlatform}`
);
// use the loaded module
})();
For this to work Babel has to be configured.
More on Webpack with dynamic imports here.
You can use transform-inline-environment-variablesto pass platform to babel
"build-mobile": "PLATFORM=mobile ...",
"build-app": "PLATFORM=app ...",