Read contents of file into array inside vue component - javascript

Inside my media.txt file, I have:
"https://www.dropbox.com/s/******/687.jpg?dl=0",
"https://www.dropbox.com/s/******/0688.jpg?dl=0
I have the following Vue carousel component:
<template>
<section>
<v-card
class="mx-auto"
color="#26c6da"
dark
max-width="1200"
>
<v-carousel>
<v-carousel-item v-for="(item,i) in items" :key="i" :src="item.src"></v-carousel-item>
</v-carousel>
</v-card>
</section>
</template>
<script>
var cache = {};
// const images = require.context('../static/', false, /\.png$|\.jpg/);
// const images = require.context('../static/', false, /\.png$|\.jpg|\.mp4/); // WORKING
const images = require.context('../static/media.txt', false, /\.png$|\.jpg|\.mp4/);
var imagesArray = Array.from(images.keys());
// const images = ["./52lv.PNG", "./Capture1.PNG", "./maps.PNG"]
console.log(images.keys());
console.log('images');
console.log(images);
var constructed = [];
function constructItems(fileNames, constructed) {
fileNames.forEach(fileName => {
constructed.push({
'src': fileName.substr(1)
})
});
return constructed;
}
console.log('items ');
console.log(imagesArray);
// At build-time cache will be populated with all required modules.
var res = constructItems(imagesArray, constructed);
console.log(res);
export default {
data: function() {
return {
items: res
};
}
};
</script>
I want to read the images from the media.txt file into an array, then populate the carousel src with these. I've been trying with Webpack's require.context function, but I'm getting a module not found error.
How can I get this working?

It looks like you're trying to import a string array (JSON) into a variable. That string array should be delimited by square brackets like this:
[
"foo",
"bar"
]
require.context(dirPath, useSubDirs, filenameRegex) is not the appropriate API to use here, as that method imports multiple files from a specified directory. For instance, the code below tells Webpack to load *.png, *.jpg, and *.mp4 files from the directory named ../static/media.txt (which presumably is actually a file).
require.context('../static/media.txt', false, /\.png$|\.jpg|\.mp4/) // DON'T DO THIS
Instead, you could simply use require('path/to/file.json') to import the specified file as a JSON object/array. For example, to import src/assets/media.json (containing the array mentioned at the top), the syntax would be:
// e.g., in src/components/Foo.vue
const media = require('../assets/media.json')
console.log(media) // => [ "foo", "bar" ]
demo

You probably should install https://github.com/webpack-contrib/raw-loader#getting-started (a loader for webpack read txt files), configure it in your vue.config.js and you should be able to import like this: import txt from 'raw-loader!./file.txt'; instead using require.

Related

Vue 2.6 with Rollup: import component by variable name

I am trying to add dynamic routes to my vue router (using router.addRoute()). It works so far, but I get a problem as soon as I try to set a component for my dynamic route.
This is the code that works:
var name = "reports";
var path = "reports/foo";
var item = {
name: name,
path: path,
component: () => import( "../pages/reports/Reports_Foo.vue" )
};
When calling the page it correctly loads the content of my Reports_Foo.vue
But when I want to load the vue file dynamically, like this:
var filename = "Reports_Foo";
var name = "reports";
var path = "reports/foo";
var item = {
name: name,
path: path,
component: () => import( "../pages/reports/"+filename+".vue" )
};
It no longer works and I get the following javascript error:
TypeError: Failed to fetch dynamically imported module: https://localhost:123456/js/pages/reports/Reports_Foo.vue
Why? Do you know a way to fix this ?
Edit: I'm using rollup to convert the files into chunks and then reference them.
Try explicitly loading the default export:
var item = {
name: name,
path: path,
component: async () => (await import("../pages/reports/"+filename+".vue")).default
}

require or import in forEach loop

I have the following object:
const basePoints = {}
which I need to fill with json files. Currently I do:
import WH11 from 'assets/WH11';
const basePoints = { WH11}
I have like a dozen of such Json files but only 2-3 can be used at a given time. INstead of importing and loading all the JSON files i don't need, I want to require/import based on a config file as shown below:
and my config.js:
const config = {
basePoints: {
"WH11": "West Gate",
"WH12": "West Gate Back Drop"
}
}
WH11, WH12 etc basically exist in json format in my assets directory:
assets/basepoints/WH11.json
{
"startingID" : 198
}
etc. Now there can a dozen or more of such json files. The user just adds the ones to be used for the month in config.js.
Is there a way to require/import the json file based on the config file. The app can't compile if I do:
Object.keys(config.basePoints).forEach(key => {
basePoints[key] = require('../assets/basepoints/' + key + '.json');
});
the error is unexpected require().
You can use the latest ES2020 feature - Dynamic Import
Syntax -
import('/modules/<module_name>')
.then(module => {
//
})
.catch(err => {
//
});
You can learn more about it in this MDN document (scroll down to the dynamic import section) -
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

How to import an array file into a javascript file

I want to create a json file in brackets only to store an array that has 200 elements in it, and I want to be able to import that file into my "main.js" file, and be able to use it even though the array itself is not in "main.js" anymore.
How can I do this?
dummyData.js
export const data = [{}, ......, {}];
main.js
import { data } from './dummyData';
if you are using vanilla js, without es6 features, you could do the following:
//dummyData.js
module.exports = [{} ,........, {}];
//main.js
var data = require('./dummyData');
you should first export your json/array from a file
file should be something like
export const myJsonArray = [{...}, {...}, ...]
then in your main.js you can import the jsonArray like this
import myJsonArray from "{file_path}"
Create a JS file, say dataProvider.js, have your json defined as a constant, make it global write a function to convert it to JSON and return it, or just return the JSON as-is.
Now in your main.js include the dataProvider.js, and then you can access the shared variable.
Make sure that the page you're loading has both main.js and dataProvider.js imported.
Ok, here is sample:
In the demo we will load each object in array and create a paragraph.
Because snippet does not support multi files, the working demo is here:
https://repl.it/#PaulThomas1/DemoForTaho
Our HTML:
<div id="content"></div>
<script src="data.js"></script>
<script src="script.js"></script>
Our main javascript (script.js):
document.addEventListener("DOMContentLoaded", function() {
let contentDiv = document.getElementById("content");
let template = document.createElement("template");
data.forEach(dataItem => {
let element = document.createElement('p');
element.innerHTML = newPara(dataItem.name);
contentDiv.appendChild(element);
});
});
const newPara = (name) => { return `Name: ${name}` };
Our data lives in data.js :
data = [
{
"name" : "bert"
},
{
"name" : "bert11"
},
{
"name" : "bert22"
},
{
"name" : "bert33"
},
{
"name" : "bert44"
},
{
"name" : "bert55"
},
{
"name" : "bert66"
}
];
Step 1 :
add "export" keyword before anything you want to export.
ex- export const data = [{1,2,3}]
Step 2 :
add type="module" in html, where you link your js to html.
ex- <script src="index.js" type="module"></script>
Step 3 : add import keyword on top of the file where you want to import data.
ex- import { data } from './Data.js';

How to dynamically load a Vue component after using require.context?

Currently I am loading all of my Vue components with require.context, this searches my components directory with a regex for .vue files. This works fine but I would like to load async components as well with dynamic imports.
Currently when I use require.context all files get loaded so even If I want to use a dynamic import my file is already loaded and nothing happens.
I need a way to exclude certain files from my require.context call. I cannot dynamically create a regex because this does not work with require.context.
// How I currently load my Vue components.
const components = require.context('#/components', true, /[A-Z]\w+\.vue$/);
components.keys().forEach((filePath) => {
const component = components(filePath);
const componentName = path.basename(filePath, '.vue');
// Dynamically register the component.
Vue.component(componentName, component);
});
// My component that I would like to load dynamically.
Vue.component('search-dropdown', () => import('./search/SearchDropdown'));
It seems the only way to do this is either manually declare all my components, which is a big hassle.
Or to create a static regex that skips files that have Async in their name. Which forces me to adopt a certain naming convention for components that are async. Also not ideal.
Would there be a better way to go about doing this?
const requireContext = require.context('./components', false, /.*\.vue$/)
const dynamicComponents = requireContext.keys()
.map(file =>
[file.replace(/(^.\/)|(\.vue$)/g, ''), requireContext(file)]
)
.reduce((components, [name, component]) => {
components[name] = component.default || component
return components
}, {})
Works with Vue 2.7 and Vue 3.
The lazy mode forces requireContext to return a promise.
const { defineAsyncComponent } = require('vue')
const requireContext = require.context('./yourfolder', true, /^your-regex$/, 'lazy')
module.exports = requireContext.keys().reduce((dynamicComponents, file) => {
const [, name] = file.match(/^regex-to-match-component-name$/)
const promise = requireContext(file)
dynamicComponents[name] = defineAsyncComponent(() => promise)
return dynamicComponents
}, {})
You can also use defineAsyncComponent({ loader: () => promise }) if you want to use the extra options of defineAsyncComponent.

Importing data object from file-to-file

I have a .JSON (named dataOut.json) file that looks similar to the following:
[
{
"scan_type": "nexpose",
"date_time": "2011-07-18 11:11:11",
"source_address": "1108",
"source_lat": "40.581160",
"source_lng": "-105.184110",
"dest_address": "11.166.181.0",
"dest_lat": "30.003880",
"dest_lng": "-604.800360"
},
...
]
I have a script that seperates the source/destination data points, and places the output in separate files, here is my code for doing so.
So here is my problem, I need to export the object variable "scan_type" from the code above, to another .JS file, named jsontonbh.js .
I tried using module exports:
//exporting 'scan_type'
obj.forEach(block => {
...
module.exports = {scan_type:block.scan_type};
...
});
and then importing it in my jsontobh.js file by requiring it, as shown here:
let sourceFile = require('./jsonParents.js');
obj.forEach(block => {
console.log(sourceFile.scan_type)
});
this code returns the error "Unexpected end of JSON input"
How can I export this variable scan_type from my first script, to my second script?

Categories