can we lazy load packages in angular, can I download required package only when I click on some button? - npm

I am using pdfmake.js(which is around 2mb) and XLSX(which is around 1mb) with angular 7, but they are used only on one page of the application. when I load my home page, in developer tools I can see main.js file size is around 8mb, I implemented lazy loading which reduced main.js file size to 7mb can I somehow further reduce main.js file by loading pdfmake.js and XLSX only when I click on some button?

pdfMake:any;
async loadPdfMaker() {
if (!this.pdfMake) {
const pdfMakeModule = await import('pdfmake/build/pdfmake');
const pdfFontsModule = await import('pdfmake/build/vfs_fonts');
this.pdfMake = pdfMakeModule.default;
this.pdfMake.vfs = pdfFontsModule.default.pdfMake.vfs;
}
}
async generatePdf() {
await this.loadPdfMaker();
const def = { content: 'A sam`enter code here`ple PDF document generated using Angular and PDFMake' };
this.pdfMake.createPdf(def).download('optionalName.pdf');;
}

You can further reduce the size by importing minified version of the library.
import * as pdfMake from 'pdfmake/build/pdfmake.min';

Related

Save a genrated pdf file in react native in interal memory in React Native Expo

I am trying to generate pdf and trying to download the same generated pdf in React Native Expo. I am not able to find any solution that lets me store file directly in my phone memory.The only solution i am getting is using expo-share share the generated pdf . Is there any way to do it ?
This is what my SavePDF functions look like
const SavePDF = async()=> {
const file = await printToFileAsync({
html: "Hello World",
base64: false,
})
await shareAsync(file.uri);
}

Vue static assets are not accessible to a library

I am using a single file Vue component and import a face-api library. I want to use a function from that library, loadSsdMobilenetv1Model(url), which takes URL of folder, where the necessary files are located and loads them. The function however cannot fetch the files if I use #/assets/weights as url (# in Vue represents the src folder). I would like to be able to host the assets for. I'm able to read files from the assets folder folder with require('#/assets/file.json), but the library seems to need a static url.
What is the best solution in my situation? Maybe I'm missing some understanding.
Can I make it so that the assets folder is served and accessible?
Here's my component and the comments show some things I've tried:
<template>
<div>...stuff...</div>
</template>
<script>
import * as faceapi from 'face-api.js';
async function load() {
// example below: If I serve the files on a separate port with CORS allowed, the function loads files fine.
// const MODEL_URL = 'http://127.0.0.1:8081/weights/';
// example below: this does not work, but I would like this to work!
const MODEL_URL = '#/assets/weights';
// example below: also doesn't work, conscious of relative paths
// const MODEL_URL = '../assets/weights';
// example below: a file loads, but I can't just this unfortunately
// return require('#/assets/file.json')
return await faceapi.loadSsdMobilenetv1Model(MODEL_URL);
}
export default {
mounted() {
var promise = load();
promise.then((model) => {
this.model = model
}, (reject) => {
console.log(reject)
// alert(reject);
})
},
name: "Home",
data() {
return {
model: null
}
}
};
</script>
I'm not sure if it's relevant, but I set up the project with
vue create
and run the dev environment with
nmp run serve

How to remove window.__NUXT__ without any issue from Vuex in Nuxt

I'm on Nuxt 2.13 and I'm having an issue with window.__Nuxt__(function(a,b,c,d,.....)). I don't know if it will affect my SEO or not, but it's on my nerve and shows all my language file.
here is the situation : there is a lang.json file in my app. i read it and store it in a lang state in Vuex. but window.__Nuxt__ shows my lang which i don't want to!!
i have found three solutions so far to remove it:
1: by adding this code to nuxt.config.js
link to stack answer
hooks: {
'vue-renderer:ssr:context'(context) {
const routePath = JSON.stringify(context.nuxt.routePath);
context.nuxt = {serverRendered: true, routePath};
}
}
}
2: by commenting some codes in node_module/#nuxt/vue-renderer/dist/vue-renderer.js
link to article
3: by using cheerio package and scraping the script from body
link to article
const cherrio = const cheerio = require('cheerio');
export default {
//The rest configuration is omitted
hooks: {
'render:route': (url, result) => {
this.$ = cheerio.load(result.html,{decodeEntities: false});
//Since window.__nuxt__ is always located in the first script in the body,
//So I removed the first script tag in the body
this.$(`body script`).eq(0).remove();
result.html = this.$.html()
}
}
}
all three will do the job, BUT !! my components won't be lazy loaded anymore as i use an state in Vuex to give theme address for lazy load! for example:
computed:{
mycomponent(){
return ()=>import(`~/components/${this.$store.state.siteDirection}/mycomp.vue`)
}
}
it will give error that webpack cant lazy load this as this.$store.state.siteDirection is null.
how can i solve this??

React-native: download and unzip large language file

A multilingual react-native app. Each language bundle is ~50MB. It doesn't make sense to include all of them in a bundle. So, what do I do about it?
I assume the right way to go here is to download the respective language files upon language selection.
What do I do with it next? Do I suppose to store it using AsyncStorage or what?
Briefly explaining, you will:
Store JSON as ZIP in Google Storage (save memory/bandwidth/time)
Unzip file to JSON (in RN)
Store JSON in AsyncStorage (in RN)
Retrieve from AsyncStorage (in RN)
[Dependencies Summary] You can do this, using these deps:
react-native
react-native-async-storage
rn-fetch-blob
react-native-zip-archive
Tip: Always store big language json in zip format (this can save up to 90% of size).
I made a quick test here: one 3.52MB json file, turned out a 26KB zipped file!
Let's consider that yours stored zip file, can be accessed by using a public url, eg: https://storage.googleapis.com/bucket/folder/lang-file.zip.
Install and link all above RN deps, it's required to get this working.
Import the deps
import RNFetchBlob from 'rn-fetch-blob';
import { unzip } from 'react-native-zip-archive';
import AsyncStorage from '#react-native-community/async-storage';
Download the file using rn-fetch-blob. This can be done using:
RNFetchBlob
.config({
// add this option that makes response data to be stored as a file,
// this is much more performant.
fileCache : true,
})
.fetch('GET', 'http://www.example.com/file/example.zip', {
//some headers ..
})
.then((res) => {
// the temp file path
console.log('The file saved to ', res.path())
// Unzip will be called here!
unzipDownloadFile(res.path(), (jsonFilePath) => {
// Let's store this json.
storeJSONtoAsyncStorage(jsonFilePath);
// Done!
// Now you can read the AsyncStorage everytime you need (using function bellow).
});
});
[function] Unzip the downloaded file, using react-native-zip-archive:
function unzipDownloadFile(target, cb) {
const targetPath = target;
const sourcePath = `${target}.json`;
const charset = 'UTF-8';
unzip(sourcePath, targetPath, charset)
.then((path) => {
console.log(`unzip completed at ${path}`)
return cb(path);
})
.catch((error) => {
console.error(error)
});
}
[function] Store JSON in AsyncStorage:
function storeJSONtoAsyncStorage (path) {
RNFetchBlob.fs.readFile(path, 'utf-8')
.then((data) => {
AsyncStorage.setItem('myJSON', data);
});
}
Retrieve JSON data from AsyncStorage (everytime you want):
AsyncStorage.getItem('myJSON', (err, json) => {
if (err) {
console.log(err);
} else {
const myJSON = JSON.parse(json);
// ... do what you need with you json lang file here...
}
})
That's enough to get dynamic json lang files working in React Native.
I'm using this approach to give a similar feature to my i18n'ed project.
Yes you are right to make the translation file downloadable.
You can store the downloaded file in the document directory of your app.
After that you can use a package to load the translations. For instance
https://github.com/fnando/i18n-js.
I would also suggest taking a look at the i18n library which is a standard tool for internationalisation in JavaScript.
Consider taking a look at this documentations page where you can find an option of loading a translation bundle or setting up a backend provider and hooking into it.
Also, to answer the storage question, if you do not plan on setting up a backend: AsyncStorage would be an appropriate place to store your key - translation text pairs.

I need a make zip for the multiple files using JSZip on nuxtjs

I Want to make zip for the multiple file using JSZip on nuxtjs and i want the files are convert to base64 format to pdf and also file format is any.If all files are in jpg then it convert to jpeg and if all files are in pdf then it convert list of pdf and put in the zip folder.
I want to do this vuejs or nuxtjs with JSZip package.
I use this below code but not getting anything.
download_btn() {
var zip = new JSZip()
var img = zip.folder("images")
for (i = 0; i < this.image.length; i++) {
img.file("img.png", this.image[i].imageurl)
}
zip.generateAsync({
type: "blob"
}).then(function(content) {
saveAs(content, "img_archive.zip")
})
}
I don't know about JSZip, but for Nuxtjs you can create a plugin to call it.
Should be something in the likes of:
Install JSZip via npm:
npm install jszip
Create a file plugins/jszip.js. Inside plugins/jszip.js add:
/* ~/plugins/jszip.js */
import Vue from 'vue'
import JSZip from 'jszip'
Vue.use(JSZip)
Add the reference to the plugin on nuxt.config.js. I'm guessing that it should run on the visitor's browser, so you should include 'mode: client'. This will make it bypass the Server-Side-Rendering.
export default {
...
plugins: [
{ src: '~/plugins/jszip', mode: 'client' }
]
...
}
You may try your code like this:
download_btn() {
var img = JSZip.folder("images")
for (i = 0; i < this.image.length; i++) {
img.file("img.png", this.image[i].imageurl)
}
JSZip.generateAsync({
type: "blob"
}).then(function(content) {
saveAs(content, "img_archive.zip")
})
}
You can read more here: NuxtJS / Plugins
Hope it helps :)
Download jszip manually and it to your static folder in nuxt.
In nuxt-config under script section add { src: '/js/jszip.js' },.