Require from the actual file using NormalModuleReplacementPlugin - javascript

I have a Storybook setup for which I need for my React component's children components to stop doing API calls. The setup is quite complex, and it is also irrelevant to the question, so I'll just say that I need the components to stop doing API calls.
My ultimate goal is to have the children component stay in a "loading state" forever, so mocking the server response not a solution here.
The approach that I came up with was to replace my Thunk action creators with a stubbed one. Similar to what we do on Jest unit tests
// note that I'm using redux ducks: https://github.com/erikras/ducks-modular-redux
jest.mock('./ducks/students');
Of course the above doesn't work since Storybook doesn't run on Jest. So my current approach is to use the NormalModuleReplacementPlugin to replace the real module ducks/students.js with a stubbed one ducks/stubs/students.js which contains the functions, but with an empty body:
// ./ducks/students.js
export const loadResources() = fetch('/resources');
export default (state, actions => {
// reducer's body
}
// ./ducks/stubs/students.js
export const loadResources() = Promise.resolve(); // STUBBED
export default (state, actions => {
// reducer's body
}
The problem is that I need only the thunk action creators to be stubbed, everything else in the file (other actions, and reducer) needs to be the same.
This are the approaches I have considered so far to fix this:
Copy/paste the rest of the actual file into the stubbed one. This wouldn't scale.
Attempting to use require.requireActual(). It turns out this is a Jest custom function so I can't use it on Storybook.
Ideally I could find a way to import everything from the actual module into the stubbed one, and export the stubbed functions and the rest of the real functions that I need.
Any ideas how can I access the actual module from the stubbed one when I'm using NormalModuleReplacementPlugin?
Update 1: 2019-07-08
Tarun suggestion about just mocking the fetch function and returning a new Promise() worked for the particular case of "indefinitely loading".
However, looking at the big picture, I still would rather just stubbing out all of the API calls, so that I can setup the stories by just modifying the redux state.
"But why can't you just mock the JSON response?" I hear you ask. The JSON response is not necessarily 1-to-1 mapping with the app domain model. We have mapper functions that takes care of the transformation.
I'd be better if the programmers could work and setup the test cases with just the domain model knowledge, and don't need to know the server response JSON structure. Needless to say, the app redux store structure is the domain model.
So I still need an answer on how to require from the actual file, when using NormalModuleReplacementPlugin.

I haven't tested this, but you might be able to achieve what you're after with the Aggregating/re-exporting modules syntax and overwriting your loadResources() function.
To do this, import your actual module into ./ducks/stubs/students.js, export all from that module, then define/overwrite loadResources() and export it as well. You can then use the NormalModuleReplacementPlugin as normal and pass in your stub file as the newResource that will contain all of your actual module reducers/actions that you wanted to keep with the thunk overwritten and stubbed out:
//ducks.stubs.students.js
export * from './ducks/students.js';
//override students.loadResources() with our stub
//order matters as the override must come after
//the export statement above
export const loadResources() = //some stubbed behavior;
//webpack.config.js
module.exports = {
plugins: [
new webpack.NormalModuleReplacementPlugin(
/ducks\.students\.js/,
'./ducks.stubs.students.js'
)
]
}
A couple of notes/caveats/gotchas with this solution:
You might have to update your exports to use let vs. const (not a big deal)
Per this issue, the export * from expression isn't supposed to handle default exports. As such, you might have to add export { default } from './ducks/students.js';. Of course, keep in mind that you won't be able to export a default function native to your stubs file (unless you're overriding the original default function with a stub of course).

Related

Javascript/Typescript Export Default Const as value from async function call

i've done a bunch of reading but haven't found a working solution
the closest i've seen is here: Export the result of async function in React
please keep in mind that I want to export an object, and that object is the result of an asynchronous function, NOT export the async function definition itself
here's my use case and implementation so far:
we have a file called config.ts
traditionally config.ts has contained an object with relevant runtime configurations as the default export
this lets us simply import config from '../config' or whatever
our config and secret management has gotten more complex so that it needs to make various calls to various secret repositories (aws, azure, etc)
i've refactored config.ts to now look something like this:
export const basicValues = {
color1: 'red'
}
async function buildConfig(){
const valuesOut = {...basicValues}
valuesOut.color2 = await getSecret('color2');
valuesOut.color3 = await getSecret('color3');
return valuesOut;
}
export default buildConfig()
where getSecret is some function that makes an arbitrary async call
i'm exporting basicValues above because i have some config settings in there that are necessary to make the calls inside getSecret.
by exporting basicValues like this i can get the values out with a simple const basicConfig = require('../config').basicValues. This way we can continue to manage all the fun config stuff in a clean, centralized, tested file but still make the values available for use very early and avoid cyclical dependencies
all together, this FEELS like it should work
i've tried lots of other patterns but this feels most natural and intuitive to read
here's the bad part:
import config from '../config' yields undefined, with export default buildConfig()
changing the export to be simply export default basicValuesgives us our config object as expected (but without the async values populated, obviously)
what exactly am I doing wrong here?
happy to provide more deets as necessary
thanks in advance
please keep in mind that I want to export an object, and that object is the result of an asynchronous function, NOT export the async function definition itself
This is not possible. Since the value is retrieved asynchronously, all modules that consume the value must wait for the asynchronous action to complete first - this will require exporting a Promise that resolves to the value you want.
In new versions of Node, you could import the Promise and use top-level await to wait for it to be populated:
import buildConfigProm from '../config';
const config = await buildConfigProm;
If you aren't in Node, top-level await isn't supported. You could call .then on the Promise everywhere it's imported:
buildConfigProm.then((config) => {
// put all the module's code in here
});
If you don't like that, the only real alternative is to use dependency injection. Have your modules export functions that take the config as a parameter, eg:
// useConfig.ts
export default (config: Config) => {
console.log('color2', config.color2);
};
This way, the only thing that has to be asynchronous is the entry point, which waits for the Promise to resolve, then calls the needed modules with it:
// index.ts
import buildConfigProm from './config';
import useConfig from './useConfig';
buildConfigProm
.then((config) => {
useConfig(config);
})
.catch(handleErrors);

Gatsby: Why Do I (Or Do I Even?) Need to Use exports.onCreateNode to Create Pages?

All of the examples in the Gatsby documentation seem to assume you want to define an exports.onCreateNode first to parse your data, and then define a separate exports.createPages to do your routing.
However, that seems needlessly complex. A much simpler option would seem to be to just use the graphql option provided to createPages:
exports.createPages = async ({ graphql, actions }) => {
const { createPage } = actions;
const { data } = await graphql(query);
// use data to build page
data.someArray.forEach(datum =>
createPage({ path: `/some/path/${datum.foo}`, component: SomeComponent }));
However, when I do that, I get an error:
TypeError: filepath.includes is not a function
I assume this is because my path prop for createPage is a string and it should be "slug". However, all the approaches for generating slugs seem to involve doing that whole exports.onCreateNode thing.
Am I missing a simple solution for generating valid slugs from a path string? Or am I misunderstanding Gatsby, and for some reason I need to use onCreateNode every time I use createPage?
It turns out the error I mentioned:
TypeError: filepath.includes is not a function
Wasn't coming from the path prop at all: it was coming from the (terribly named) component prop ... which does not take a component function/class! Instead it takes a path to a component (why they don't call the prop componentPath is just beyond me!)
But all that aside, once I fixed "component" to (sigh) no longer be a component, I was able to get past that error and create pages ... and it turns out the whole onCreateNode thing is unnecessary.
Why Do I Need to Use exports.onCreateNode to Create Pages?
You do not.
Gatsby heavily uses GraphQL behind the scenes. The Gatsby documentation is about teaching users that many of the features in Gatsby are often only available via GraphQL.
You can create pages without GraphQL as you do in answer with data.someArray.forEach ... but that is not the intended way. By skipping createNodeField you will not be able to query for these fields within your page queries. If you don't need these fields via GraphQL then your solution is perfect.

How to use javaScript file as Higher Order wrapper for other JavaScript File

I want to ask, as in react we have HOC (Higher order components) where we pass components that modify it and then return modified Component for use
can we do same in javaScript?
for Example
// index1.js
// this is file where i am importing all the folder modules and exporting them
export { methodA, methodB } from './xyzAB'
export { methodC, methodD } from './xyzCD'
i am importing this file in another folder like this
import * as allMethods from './modules'
// this allows me to use this syntax
allMethods.methodA()
allMethods.methodB()
this is working fine, but i am looking for this kind of wrapper
// index2.js
// this is another file somewhere else where i want to use index1.js exported methods
import * as allMethods from './modules/xyz'
import anotherMethod from './somewhere/xyz'
// here i want customize some of `allMethods` functions and export them as new object
//which contains modifed version of default `index1.js` methods
allMethods.methodA = allMethods.methodA( anotherMethod ) // this is example of modified as HO Method
export default allMethods
My Above example may seem confusing,
why i am looking for such solution, i have set of utilities which i am trying to make them as library and use them in multiple projects,
now some of utils are dependent on main project related things, so instead of giving my utilities hard coded reference to their dependencies,
i want to pass different dependencies for different methods through my higher order method or configuration file,
so that each new project pass its dependent utilities from their config or higher order wrapper file as example shown above
I hope i was able to clear my question,
Few things which i tried,
i tried importing all modules in file which i count as wrapper file
in that if i try to use any module that returns webpack error as undefined method, due to methods not loaded fully until few seconds, i tried setTimeOut, that works fine, but this is not valid way of managing thing,
then i tried some async way, i used dynamic import() which returns promise, i used async/await syntax, and also used .then syntax but couldn't extract data and save it as variable (i may be doing something wrong at this step but i was totally failed) but this was only available with in promise or async await scope,
there were also other steps tried,
i am hoping i could find some neater syntax like below
import * as F from '../../core/lib/functions'
import { getModel } from '../entities'
F.getKeys = F.getKeys( getModel )
export default F
any suggestion is welcome
I think what you're looking for is some sort of currying or factory-like pattern.
There is no such thing as higher order modules but since JavaScript support higher order functions that is what you should use.
Just as a reminder, a higher order component is any component that takes a component as a parameter and returns another component. Similarly (simplified) a higher order function is one that takes a function as a parameter and returns a new function. (in reality all React components are more or less functions so thus why we are able to have higher order components).
The key thing is that you need to call a higher order function, not just import it (since again, there is no such thing as a higher order module). But this ties well into your idea of dependency injection.
I think, what you want is something like this in your utilities:
function a(dependency1, arg1, arg2) {}
function b(dependency2, arg1, arg2) {}
function createUtils(dependency1, dependency2) {
return {
a: a.bind(null, dependency1),
b: b.bind(null, dependency2)
}
}
This allows you to customize per project what dependency 1 and 2 are and the details for how they work (with some common interface). With the binding you don't have to pass that dependency in with every call to a function.
Then in one of your projects you'd set them up something like this:
import { createUtils} from 'utils';
import { dependency1, dependency2 } from 'somewhere' ;
const { a, b } = createUtils(dependency1, dependency2)
export { a, b };
You're not really doing any higher order function stuff, like I said this is more like a factory/dependency injection thing. Though bind is a higher order function (it takes the function it's called in and returns a new function with some arguments bound).
You can put place in createUtils for general modifications through another parameter with options. Or you can export smaller "factories" for each method that you want to be able to modify.
With that in mind you might to only export the raw functions from utils and use bind in your module setup code to bind the dependencies. I think bind is what you are missing. As well as that you have to create new functions to export, rather than modifying the imported functions. That also means that your imports in the rest of your code will come only from within your own module, not from the utils module.

Write Vue plugin with custom options

I'm trying to write a vue plugin with custom options. I followed the official vue guidelines (https://v2.vuejs.org/v2/guide/plugins.html) on doing so but can't find a way to define custom options. These options should be read by normal javascript which then exports an object that is used by a vue component.
My folder structure is like this:
/src
factory.js
CustomComponent.vue
factory.js
import Vue from "vue";
import ImgixClient from "imgix-core-js";
var imgixClient = new ImgixClient({
domain: CUSTOM_OPTION_URL <-- important bit
domain: Vue.prototype.$imgixBaseUrl //tried it like this
});
export { imgixClient };
I already tried to set this custom bit by utilizing Vue.prototype in the install method like this but can't seem to get it working
export function install(Vue, options) {
if (install.installed) return;
install.installed = true;
Vue.prototype.$imgixBaseUrl = options.baseUrl;
Vue.component("CustomComponent", component);
}
I'm afraid this isn't going to be the simple answer you might have been hoping for... there's a lot to unpick here.
Let's start with factory.js. That is not a factory. It's a singleton. Singletons have problems around dependencies, configuration and the timing of instantiation and that's precisely the problem you're hitting. More on that later.
Now let's take a look at the plugin. First up, these two lines:
if (install.installed) return;
install.installed = true;
That shouldn't be necessary. Vue already does this automatically and should ensure your plugin is only installed once. Perhaps this came from an old tutorial? Take a look at the source code for Vue.use, there's not a lot to it:
https://github.com/vuejs/vue/blob/4821149b8bbd4650b1d9c9c3cfbb539ac1e24589/src/core/global-api/use.js
Digging into the Vue source code is a really good habit to get into. Sometimes it will melt your mind but there are some bits, like this, that aren't particularly difficult to follow. Once you get used to it even the more opaque sections start to become a little clearer.
Back to the the plugin.
Vue.prototype.$imgixBaseUrl = options.baseUrl;
It is not clear why you are adding this to the prototype.
I'm going to assume you are already familiar with how JavaScript function prototypes work.
Component instances are actually instances of Vue. So any properties added to Vue.prototype will be inherited by your components with almost no overhead. Consider the following simple component:
<template>
<div #click="onClick">
{{ $imgixBaseUrl }}
</div>
</template>
<script>
export default {
methods: {
onClick () {
const url = this.$imgixBaseUrl
// ...
}
}
}
</script>
As $imgixBaseUrl is an inherited property it is available within onClick via this.$imgixBaseUrl. Further, templates resolve identifiers as properties of the current Vue instance, so {{ $imgixBaseUrl }} will also access this.$imgixBaseUrl.
However, if you don't need to access $imgixBaseUrl within a component then there is no need to put it on the Vue prototype. You might as well just dump it directly on Vue:
Vue.imgixBaseUrl = options.baseUrl;
In the code above I've ditched the $ as there's no longer a risk of colliding with component instance properties, which is what motivates the $ when using the prototype.
So, back to the core problem.
As I've already mentioned, singletons have major problems around creation timing and configuration. Vue has its own built-in solution for these 'do it once at the start' scenarios. That's what plugins are. However, the key feature is that plugins don't do anything until you call install, allowing you to control the timing.
The problem with your original code is that the contents of factory.js will run as soon as the file is imported. That will be before your plugin is installed, so Vue.prototype.$imgixBaseUrl won't have been set yet. The ImgixClient instance will be created immediately. It won't wait until something tries to use it. When Vue.prototype.$imgixBaseUrl is subsequently set to the correct value that won't have any effect, it's too late.
One way (though not necessarily the best way) to fix this would be to lazily instantiate ImgixClient. That might look something like this:
import Vue from "vue";
import ImgixClient from "imgix-core-js";
var imgixClient = null;
export function getClient () {
if (!imgixClient) {
imgixClient = new ImgixClient({
domain: Vue.prototype.$imgixBaseUrl
});
}
return imgixClient;
}
So long as nothing calls getClient() before the plugin is installed this should work. However, that's a big condition. It'd be easy to make the mistake of calling it too soon. Besides the temporal coupling that this creates there's also the much more direct coupling created by sharing the configuration via Vue. While the idea of having the ImgixClient instantiation code in its own little file makes perfect sense it only really stands up to scrutiny if it is independent of Vue.
Instead I'd probably just move the instantiation to within the plugin, something like this:
import ImgixClient from "imgix-core-js";
export default {
install (Vue, options) {
Vue.imgixClient = Vue.prototype.$imgixClient = new ImgixClient({
domain: options.baseUrl
});
Vue.component("CustomComponent", component);
}
}
I've made a few superficial changes, using a default export and wrapping the function in an object, but you can ignore those if you prefer the way you had it in the original code.
If the client is needed within a component it can be accessed via the property $imgixClient, inherited from the prototype. For any other code that needs access to the client it can either be passed from the component or (more likely) grabbed directly from Vue.imgixClient. If either of these use cases doesn't apply then you can remove the relevant section of the plugin.

how to make global variable and functions which can be accessible in all the components in angular 4

I am struggling with global variables as I want some variables which I need to access in all the components so what should i do in angular 4.
I've tried something like this:
Created one file with the name of global.ts and made a class with the name GlobalComponent something like this
export class GlobalComponent {
globalVar:string = "My Global Value";
}
and am using it on HeaderComponent by importing and making instance and it's working fine but this is very long process to import in each and every files to get it available.
So I want it to be available on all the components without importing it.
Is there any way or trick to achieve this? Any suggestion would be appreciated :)
As #bgraham is suggesting, it is definitely better to let angular injector to instantiate the service.
But you could also export just a simple object with key-value pairs, including functions. Then you can simply import it and use it (without the instantiation part).
globals.ts file:
export const GLOBALS = {
globalVar: 'My Global Value',
globalFunc: () => alert('123')
};
your.component.ts file:
import { GLOBALS } from './globals.ts';
console.log(GLOBALS.globalVar);
GLOBALS.globalFunc();
Btw I don't think there is a way how to get rid of the import statement - that is part of how typescript works...
I don't think what you want to do is possible and it's probably not a good idea.
The import statements are how webpack (or other bundlers) are able to build a tree to figure out which files to include. So it might be tricky to get global files built into all your bundles.
Also I would add, I'm not sure just importing the static file is the way to go either. It's kind of quick and dirty, which maybe is what you want I guess, but for production apps I would recommend making an angular service and injecting it.
export class GlobalVariablesService {
globalVar:string = "My Global Value";
}
This way you can mock these for unit tests or potentially pass in different variables depending on your changing needs in the future.
If you need these to update and push that into lots of components throughout your app, you might look into Redux. Its pretty handy for that kind of thing.
Sorry, perhaps not the answer you were hoping for
Simply create constant file - constant.ts under src folder.
Now import constant.ts file whenever you require parameter to be called
It will look like so
export const constant = {
COSNT_STRING : 'My Global Value',
}
how to use constant:
1) Import file.
2) constant.CONST_STRING
Also this is a good practice from future prospective, if you want to modify response just made change in one file not in 800 files.

Categories

Resources