Ways to import a JSON file in public folder in Vue-CLI - vue.js

I want to import a JSON file to use it, I need it to modify it in the future so I put it in public folder not assets, When I refer to it like this import JSON from ../../public/Data.json it works but I don't think so after building project can be resolved because after building there is no public folder. So I tried this :
let addr = process.env.BASE_URL;
import JSON from `${addr}Data.json`;
But It throws an error : SyntaxError
I'm confused now which way is the best and is there another way ?

The assets in the public folder are copied as is to the root of the dist folder. In your code, you can reference it just as /Data.json (if your app is deployed at the root of the domain).
E.g
async someMethod() {
const baseUrl = process.env.BASE_URL;
const data = await this.someHttpClient.get(`${ baseUrl }/Data.json`);
}
If you want to import the JSON as you have tried, I suggest to put it somewhere in the src folder and import from there
E.g.
import data from '#/data/someData.json'
console.log(data);

I came across this because I was doing a stand alone SPA that I wanted to run with no DB and keep the config in a JSON file. The import statement above works great for a static conf file, but anything imported like that gets compiled with the build, so even though your someData.json will exist in the public folder you won't see any changes in your dist because it's actually reading a JS compiled file.
To get around this I:
Convert the JSON file into a simple JS variable in a conf.js file:
e.g.
var srcConf={'bGreatJSON':true};
In index.html, did
<script src='./conf.js'>
Now that the JS variable has been declared in my Vue component I can just look for the window.srcConf and assign it if it exists in mounted or created:
if(typeof window.srcConf!='undefined')
this.sConf=window.srcConf;
This also avoids the GET CORS issue that others posts I've seen runs into, even in the same directory I kept getting CORS violations trying to do an axios call to read the file.

Related

webpack creating 100's of js chunks crippling performance for a single page view with vue cli

We have a vuejs 2 project.
We needed some function of dayjs.
We abstracted the dayjs into a single utility file and following the guide ended up with this:
import { i18n } from '#/plugins/i18n';
import dayjs from 'dayjs';
import calendar from 'dayjs/plugin/calendar';
dayjs.extend(calendar);
export default async (date: Date, locale?: string): Promise<string> => {
import(`dayjs\locales\${locale}`)
const time:any = i18n.t('datetime.dict');
return dayjs(date).locale(userLocale).calendar(null, {
lastDay: `[${time.yesterday} ${time.at}] LT`,
sameDay: `[${time.today} ${time.at}] LT`,
nextDay: `[${time.tomorrow} ${time.at}] LT`,
lastWeek: `[${time.last}] dddd [${time.at}] LT`,
nextWeek: `dddd [${time.at}] LT`,
sameElse: 'LLLL'
});
};
The app works perfectly fine, but vuejs is outputting every single langauge file from dayjs as a chunk and also adding the prefetch script tag to the index.html.
Has anyone else hit this issue and is the above code snippet wrong or should there be a more precise import?
Here is a screenshot of only some of the dayjs chunks.. each is completely the same with different langauge strings in... but we didn't even import the locale setting options yet.
#MichalLevĂ˝ gave the direction to the answer to this issue.
Essentially, webpack cannot know which single file to import when you say:
import(`dayjs\locales\${locale}`)
So.. it just creates a js chunk for every single file it finds. Which is not overly bad on its own.
When you combine this behaviour with vue-cli's default prefetch behaviour, this is when things get bad... the result is that every single chunk that webpack creates ends up being a "pre-fetched" line in the HTML head in the outputted index HTML file.
So when there is 400 chunks from a dynamic import (in this case locales from dayjs) then there is a prefetch for all of them.
It depends on your setup but.. for us, the app is also a PWA so there is effectively no requirement for prefetching as the PWA will also download... in fact it doubles the downloads.
The answer for us was to be more specific on the prefetch:
https://cli.vuejs.org/guide/html-and-static-assets.html#prefetch
And also, as we only needed a few languages, import only what was needed but being specific and not passing a variable to map to a path

How to build individual component chunks with Vite to load with defineAsyncComponent

I'm not sure this is even possible, but it looks like some of the moving parts are there.
GOAL:
Create a library of single file Vue 3 components that will compile into separate chunks using Vite, and be dynamically/async loaded at runtime. The app itself will load, then load up a directory of individually chunk'd elements to put in a toolbox, so afterward each element could be updated, and new ones could be added by putting new chunks in the same path.
So far, I can create the separate chunks within the vite.config as follows:
...
build: {
rollupOptions: {
output: {
...buildChunks()
}
}
}
...
The buildChunks function iterates over SFC files in the ./src/toolbox path and returns an object like...
{
'toolbox/comp1':['./src/toolbox/comp1.vue'],
'toolbox/comp2':['./src/toolbox/comp2.vue'],
'toolbox/comp3':['./src/toolbox/comp3.vue'],
...
}
This all works, but I'm not sure how to make that next leap where the server code dynamically loads all of those generated chunk files without explicitly listing them in code. Also, since the Vite build adds an ID in the file name (e.g. comp.59677d29.js) on each build, referencing the actual file name in the import can't be done explicitly.
So far what I've considered is using defineAsyncComponent(()=>import(url)) to each of the files, but I'd need to generate a list of those files to import...which could be done by building a manifest file at build time, I guess.
Any suggestions? Is there a better approach?

Why FileExtensionContentTypeProvider no work with .min.js extension?

I have some css&js files in my project and I used the BuildBundlerMinifier NuGet package to minify and obfuscate them.
For example, the app.js will minify and obfuscate into app.min.js in the same directory.
Now I want the user can access the app.min.js but can't access the app.js.
I do this for I don't want anybody else to access the source code of my js.
Although someone still can get its source code from the app.min.js while I don't want them to get it easily.
I tried to use FileExtensionContentTypeProvider in Configure of startup.cs to achieve this:
var provider = new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider();
provider.Mappings.Remove(".js");
provider.Mappings.Add(new KeyValuePair<string, string>(".min.js", "application/javascript"));
app.UseStaticFiles(new StaticFileOptions()
{
ContentTypeProvider=provider
});
However, after it runs I can access neither app.js nor app.min.js.
What's wrong with my code?
Thank you.
The FileExtensionContentTypeProvider is only meant to provide a mapping from file extension to the correct MIME type. In order to retrieve the file extension from a file name, it will do the following:
private static string? GetExtension(string path)
{
int index = path.LastIndexOf('.');
if (index < 0)
return null;
return path.Substring(index);
}
It will take the very last part of the extension. So with app.min.js, the reported file extension will still be .js and not .min.js, and as such the mapping for .js will be required.
Modifying the MIME type mapping in order to disallow certain file extensions is probably not the best strategy. It would be better to modify the underlying file provider itself to handle that.
Alternatively, if you want to prevent access to non-minified JavaScript files, you could also split the middleware to conditionally prevent serving static files for any request to a path that ends with .js that is not a .min.js:
app.UseWhen(ctx => !ctx.Request.Path.HasValue
|| !ctx.Request.Path.Value.EndsWith(".js")
|| ctx.Request.Path.Value.EndsWith(".min.js"), app2 =>
{
app2.UseStaticFiles();
});

Serverless offline CUSTOM: using external file AND internally added variables?

I am having a weird problem where I need to use Serverless "custom:" variables read both from an external file and internally from the serverless.yml file.
Something like this:
custom: ${file(../config.yml)}
dynamodb:
stages:
-local
..except this doesn't work. (getting bad indendation of a mapping entry error)
I'm not sure if that's possible and how do you do. Please help :)
The reason is dynamodb local serverless plugin won't work if it's config is set in the exteranl file. But we use the external file config in our project and we don't wanna change that.
So I need to have the dynamodb config separate in the serverless.yml file just not sure the proper way to do it.
Please someone help :) Thanks
You will either have to put all your vars in the external file or import each var from the custom file one at the time as {file(../config.yml):foo}
However... you can also use js instead of yml/json and create a serverless.js file instead allowing you to build your file programically if you need more power. I have fairly complex needs for my stuff and have about 10 yml files for all different services. For my offline sls I need to add extra stuff, modify some other so I just read the yaml files using node, parse them into json and build what I need then just export that.
Here's an example of loading multiple configs and exporting a merged one:
import { readFileSync } from 'fs'
import yaml from 'yaml-cfn'
import merge from 'deepmerge'
const { yamlParse } = yaml
const root = './' // wherever the config reside
// List of yml to read
const files = [
'lambdas',
'databases',
'whatever'
]
// A function to load them all
const getConfigs = () =>
files.map((file) =>
yamlParse(readFileSync(resolve(root, `${file}.yml`), 'utf8'))
)
// A function to merge together - you would want to adjust this - this uses deepmerge package which has options
const mergeConfigs = (configs) => merge.all(configs)
// No load and merge into one
const combined = mergeConfigs(getConfigs())
// Do stuff... maybe add some vars just for offline for ex
// Export - sls will pick that up
export default combined

Always "requiring unknown module" when reading json file

bit of an RN newb here. I'm trying to read some json data files:
function loadCategories() {
const ids = ['tl1', 'tl2', 'tl3', 'tl4', 'tl5', 'tl6'];
ids.forEach(function(id) {
var contents = require('../Content/top-level/' + id + ".json.js");
...
});
}
But here I always get an error:
Unhandled JS Exception: Requiring unknown module "../Content/top-level/tl1.json.js".If you are sure the module is there, try restarting the packager or running "npm install".
The files exist and my relative path logic should be OK given the project structure:
ProjectDir
Components
ThisComponent.js
Content
top-level
tl1.json.js
tl2.json.js
...
i.e. the above code is running from ThisComponent.js and trying to access tl1.json.js, etc so I would think the relative path of ../Content/top-level/tl1.json.js would work.
I've tried:
Restarting the packager
Referencing ./Content/top-level/tl1.json.js instead
Referencing /Content/top-level/tl1.json.js instead
I'm on RN 0.36.0. Gotta be something obvious…right?
This isn't possible in React Native because of how the packager works. You have to require files with static string path. You can use a switch statement something like this -
switch (id) {
case 'tl1': return require('../Content/top-level/tl1.json');
case 'tl2': return require('../Content/top-level/tl2.json');
...
}
Also why does your json files have .js extension?