In a javacscript file I have something that looks like this,
module.exports = {
ROUTES: [
{"route1" : "route-1"},
{"route2" : "route-2"},
{"route3" : "route-3"}
]
}
I am doing the following to use these values in another file,
const routes = require("/routes");
meaning to access the values I have to do the following,
routes.ROUTES.route1
Is it possible to import the ROUTES array directly from the file so I can do,
ROUTES.route1
Since you're using common JS modules, you can use destructuring:
const { ROUTES } = require('./routes');
You could also export the routes array directly if you don't have anything else in the file:
module.exports = [
{"route1" : "route-1"},
{"route2" : "route-2"},
{"route3" : "route-3"}
]
That way you could keep your import:
const routes = require("/routes");
Related
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
}
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
I believe this to be primarily a question about regex, but I may be wrong.
Let's say I wanted to exclude the folder in my project root called art.
My output regex in the CLI looks like:
blacklistRE: /(all|the|other|matchers|art\.*)$/
But this leads to an error:
Unable to resolve "art/core/color" from "..\..\node_modules\react-native\Libraries\ART\ReactNativeART.js"
How can I exclude the top level art directory without affecting all child directories?
From the bundler's docs
blacklistRE
Type: RegExp
A RegEx defining which paths to ignore.
https://facebook.github.io/metro/docs/configuration/#blacklistre
The code of the function I'm calling:
It's short and self-contained in this file, if anyone better than me with regex might have any insight. https://github.com/facebook/metro/blob/8c53c38932c3e396109014ac707287fbdf2500d3/packages/metro-config/src/defaults/blacklist.js#L35-L44
My full code looks like:
const blacklist = require('metro-config/src/defaults/blacklist');
const regexStrings = [
// DEFAULTS
'.*\\android\\ReactAndroid\\.*',
'.*\\versioned-react-native\\.*',
'node_modules[\\\\]react[\\\\]dist[\\\\].*',
'node_modules[\\\\].cache[\\\\].*',
'packages[\\\\]electron[\\\\].*',
'node_modules[\\\\]electron.*',
'website\\node_modules\\.*',
'heapCapture\\bundle.js',
'.*\\__tests__\\.*',
'.*\\.git\\.*',
// CUSTOM
'art\\.*',
]
const constructBlacklistRE = () => {
const formedRegexes = regexStrings.map(piece => new RegExp(piece));
console.warn(formedRegexes);
return blacklist([...formedRegexes]);
};
const config = {
blacklistRE: constructBlacklistRE(),
}
This should work:
const blacklist = require('metro-config/src/defaults/blacklist');
const path = require('path');
const ignoreTopLevelFolders = [
'art'
// add more top level folders here
].map(f => new RegExp(`${ path.resolve(f) }/.*`));
module.exports = { resolver: { blacklistRE: blacklist(ignoreTopLevelFolders) } };
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';
My goal is to fetch username from a url
Inside app.routing I have route
export const routes: Routes = [
{ path: 'dashboard/:username', component: App }
];
inside appp component I'm trying to fetch this username using
let username = this.route.snapshot.queryParams["username"];
My browser is using localhost:91/dashboard/john
username is always undefined.
You should be using it as params
let username = this.route.snapshot.params["username"];
You don't need to use queryParams here. This is useful when you have something like this:
localhost:91/dashboard?username=john
Just use params property.
this.route.snapshot.params["username"];
I suppose you declared route in following way:
{ path: 'dashboard/:username', component: SomeComponent}
Try this :
this.route.snapshot.params['username']
Instead of queryParams