投稿時間:2023-02-06 01:15:06 RSSフィード2023-02-06 01:00 分まとめ(20件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
IT 気になる、記になる… 「Beats Fit Pro」にイエローやブルーなどの新色が登場か https://taisy0.com/2023/02/06/168124.html beats 2023-02-05 15:33:35
IT 気になる、記になる… 2024年発売の「iPhone 16」シリーズでは”Pro/Pro MAX”よりも更に上位のモデルが登場か https://taisy0.com/2023/02/06/168122.html apple 2023-02-05 15:05:24
python Pythonタグが付けられた新着投稿 - Qiita Presigned URL を用いた S3 multipart upload を行う (by JavaScript + Python Chalice) https://qiita.com/t-kigi/items/01327137443b72ee8a60 byjavascriptpythonchalice 2023-02-06 00:17:06
python Pythonタグが付けられた新着投稿 - Qiita huggingface tutorial "Fine-tune a pretrained model"をDDPでやってみた https://qiita.com/oriki101/items/df58d1f1eff8642fe657 huggingface 2023-02-06 00:05:18
python Pythonタグが付けられた新着投稿 - Qiita ChatGPTで長いコードを最後まで全て出力する方法 https://qiita.com/0Kizw5B6S6Zi7Da/items/035de026106965e92e0c chatgpt 2023-02-06 00:03:42
js JavaScriptタグが付けられた新着投稿 - Qiita [Vue]画面スクロールに合わせてバックグラウンドのalphaを調整 https://qiita.com/purupurupu/items/38f0cfc6c94de16bab97 alpha 2023-02-06 00:28:06
js JavaScriptタグが付けられた新着投稿 - Qiita Presigned URL を用いた S3 multipart upload を行う (by JavaScript + Python Chalice) https://qiita.com/t-kigi/items/01327137443b72ee8a60 byjavascriptpythonchalice 2023-02-06 00:17:06
AWS AWSタグが付けられた新着投稿 - Qiita Presigned URL を用いた S3 multipart upload を行う (by JavaScript + Python Chalice) https://qiita.com/t-kigi/items/01327137443b72ee8a60 byjavascriptpythonchalice 2023-02-06 00:17:06
GCP gcpタグが付けられた新着投稿 - Qiita 「Permission 'iam.serviceAccounts.signBlob' denied on resourceエラー」の解決方法 https://qiita.com/takagimeow/items/939d7f6d25c1bea9f3da bucketbucketnameconstfile 2023-02-06 00:33:24
海外TECH MakeUseOf 7 Quick Photoshop Touch-Up Tricks to Enhance Your Photos https://www.makeuseof.com/tag/amazingly-diverse-touch-tricks-photoshop/ enhance 2023-02-05 15:30:16
海外TECH MakeUseOf Get Absolute Control of Your Windows PC With PowerToys Run https://www.makeuseof.com/absolute-control-of-your-pc-at-your-fingertips-with-powertoys-run/ powertoys 2023-02-05 15:15:16
海外TECH DEV Community React Anti-Patterns and Best Practices - Do's and Don'ts https://dev.to/perssondennis/react-anti-patterns-and-best-practices-dos-and-donts-3c2g React Anti Patterns and Best Practices Do x s and Don x tsReact may seem to be one of the least opinionated frameworks in the Wild West Web Despite that there s a lot of mistakes you can do and even more things you can do to write clean and readable code This article explains common anti patterns and best practices in React In This ArticleUse useState Instead of VariablesDeclare CSS Outside ComponentsUse useCallback To Prevent Function RecreationsUse useCallback To Prevent Dependency ChangesUse useCallback To Prevent useEffect TriggersAdd an Empty Dependency List to useEffect When No Dependencies Are RequiredAlways Add All Dependencies to useEffects and Other React HooksDo Not Use useEffect To Initiate External CodeDo Not Wrap External Functions in a useCallbackDo Not Use useMemo With Empty Dependency ListDo Not Declare Components Within Other ComponentsDo Not Use Hooks in If Statements No Conditional Hooks Do Not Use Hooks After Return No Conditional Hooks Let Child Components Decide if They Should RenderUse useReducer Instead of Multiple useStateWrite Initial States as Functions Rather Than ObjectsUse useRef Instead of useState When a Component Should Not Rerender Use useState Instead of VariablesThis first one should be a basic one but I still see developers doing this sometimes even seniors To store a state in React you should always use one of the React hooks like useState or useReducer Never declare the state directly as a variable in a component Doing so will redeclare the variable on every render which means that React cannot memoize things it normally memoizes import AnotherComponent from components AnotherComponent const Component gt Don t do this const value someKey someValue return lt AnotherComponent value value gt In the case above AnotherComponent and everything that depends on value will rerender on every render even if they are memoized with memo useMemo or useCallback If you would add a useEffect to your component with value as a dependency it would trigger on every render The reason for that is that the JavaScript reference for value will be different on every render By using React s useState React will keep the same reference for value all until you update it with setValue React will then be able to detect when to and when not to trigger effects and recalculate memoizations import useState from react import AnotherComponent from components AnotherComponent const Component gt Do this instead const value setValue useState someKey someValue return lt AnotherComponent value value gt If you only need a state that is initiated once and then never updated then declare the variable outside the component When doing that the JavaScript reference will never change Do this if you never need to update the value const value someKey someValue const Component gt return lt AnotherComponent value value gt Declare CSS Outside ComponentsIf you are using a CSS in JS solution avoid declaring CSS within components import makeCss from some css in js library const Component gt Don t do this return lt div className makeCss background red width gt The reason why not to do it is because the object has to be recreated on every render Instead lift it out of the component import cssLibrary from some css in js library Do this instead const someCssClass makeCss background red width const Component gt return lt div className someCssClass gt List of Free Image Tools Every Frontend Developer Needs Dennis Persson・Jul ・ min read webdev ux css productivity Use useCallback To Prevent Function RecreationsWhenever a functional React component is rerendered it will recreate all normal functions in the component React provided a useCallback hook that can be used to avoid that useCallback will keep the old instance of the function between renders as long as its dependencies doesn t change import useCallback from react const Component gt const value setValue useState false This function will be recreated on each render const handleClick gt setValue true return lt button onClick handleClick gt Click me lt button gt import useCallback from react const Component gt const value setValue useState false This function will only be recreated when the variable value updates const handleClick useCallback gt setValue true value return lt button onClick handleClick gt Click me lt button gt This time I won t say do this or do that Some people would tell you to optimize each function with a useCallback hook but I won t For small functions like the one in the example I can t assure it really is better to wrap the function in useCallback Under the hood React will have to check dependencies on every render to know if a new function needs to be created or not and sometimes the dependencies changes frequently anyways The optmization useCallback gives might therefore not always be needed If the dependencies to the function doesn t update a lot though useCallback can be a good optimization to avoid recreating the function on each render Is React difficult Join this dude creating another js framework Use useCallback To Prevent Dependency ChangesWhile useCallback can be used to avoid function instantiations it can also be used for something even more important Since useCallback keeps the same memory reference for the wrapped function between renders it can be used to optimize usages of other useCallbacks and memoizations import memo useCallback useMemo from react const MemoizedChildComponent memo onTriggerFn gt Some component code const Component someProp gt Reference to onTrigger function will only change when someProp does const onTrigger useCallback gt Some code someProp This memoized value will only update when onTrigger function updates The value would be recalculated on every render if onTrigger wasn t wrapper in useCallback const memoizedValue useMemo gt Some code onTrigger MemoizedChildComponent will only rerender when onTrigger function updates If onTrigger wasn t wrapped in a useCallback MemoizedChildComponent would rerender every time this component renders return lt gt lt MemoizedChildComponent onTriggerFn onTrigger gt lt button onClick onTrigger gt Click me lt button gt lt gt Use useCallback To Prevent useEffect TriggersThe previous example showed how to optimize renders with help of useCallback in the same way it is also possible to avoid unnecessary useEffect triggers import useCallback useEffect from react const Component someProp gt Reference to onTrigger function will only change when someProp does const onTrigger useCallback gt Some code someProp useEffect will only run when onTrigger function updates If onTrigger wasn t wrapped in a useCallback useEffect would run every time this function renders useEffect gt Some code onTrigger return lt button onClick onTrigger gt Click me lt button gt Add an Empty Dependency List to useEffect When No Dependencies Are RequiredIf you have an effect which isn t dependent on any variables make sure to an empty dependency list as the second argument to useEffect If you don t do that the effect will run on every render import useEffect from react const Component gt useEffect gt Some code Do not do this return lt div gt Example lt div gt import useEffect from react const Component gt useEffect gt Some code Do this return lt div gt Example lt div gt The same logic applies to other React hooks such as useCallback and useMemo Although as described later in this article you may not need to use those hooks at all if you don t have any dependencies Always Add All Dependencies to useEffects and Other React HooksWhen dealing with dependency lists for built in React hooks such as useEffects and useCallback make sure to always add all dependencies to the dependency list second argument of the hooks When a dependency is omitted the effect or callback may use an old value of it which often results in bugs which can be hard to detect Adding all variables may be a very tricky thing to do sometimes you simply don t want an effect to run again if a value updates but trying to find a solution for it will not only save you from bugs it usually leads to better written code as well Even more important if you leave out a dependency to prevent a bug that bug will come back for you when upgrading to newer React versions In strict mode in React updating hooks e g useEffect useMemo are triggered twice in development and that may happen in production in future React versions Better add all dependencies to react hooks to be on the safe sideimport useEffect from react const Component gt const value setValue useState useEffect gt Some code Don t neglect adding variables to dependency list The value variable should be added here return lt div gt value lt div gt You may wonder how can you circumvent side effects when useEffects are triggered more times than you wish Unfortunately there isn t a one for all solution to that Different scenarios requires different solutions You can try to use hooks to only run code once that can sometimes be useful but it isn t a solution to recommend really Most often you can solve your problem using if cases You can look at the current state and logically decide whether or not you really need to run the code For example if your reason not to add the variable value as a dependency to the effect above was to only run the code when value is undefined you can simply add an if statement inside the effect import useEffect from react const Component gt const value setValue useState useEffect gt if value Some code to run when value isn t set Do this always add all dependencies value return lt div gt value lt div gt Other scenarios may be more complex maybe it isn t very feasible to use if statements to prevent effects from happening multiple times And if it isn t easily done you should avoid it to avoid bugs When that s the case you should first ask yourself do you really need an effect There are a lot of cases where developers use effect when they really shouldn t do that However life is not trivial let s say you really do need to use useEffect and you don t manage to easily solve it with if cases What else options do you have Actually the easy way is potentially the best way in this case just to add all dependencies and let the effect run more times than you want it to Instead of trying to prevent code from being executing you can write the code so it doesn t matter if it is called multiple times or not Such code is called to be idempotent and suits very well with functional programming Such behavior can be achieved by using caches throttles and debounce functions I may write and article explaining this topic in detail in the future but for now I will leave it here Top Celebrities Who Code Dennis Persson・Jul ・ min read jokes webdev programming discuss Do Not Use useEffect To Initiate External CodeLet say you want to run some code to initialize a library Plenty of times I have seen initializion code like that being placed in an useEffect with an empty dependency list which is completely unnecessary and error prone If the function you call isn t dependent on a component s internal state it should be initialized outside the component import useEffect from react import initLibrary from libraries initLibrary const Component gt Do not do this useEffect gt initLibrary return lt div gt Example lt div gt import initLibrary from libraries initLibrary Do this instead initLibrary const Component gt return lt div gt Example lt div gt If the component s internal state is needed for the initialization you can put it in an useEffect but if you are doing that make sure you are adding all the dependencies you use to the dependency list of useEffect as described under the previous heading Do Not Wrap External Functions in a useCallbackJust like in the case with triggering init functions in a useEffect above you don t need a useCallback to call an external function Simply just invoke the external function as is This saves React from having to check if the useCallback needs to be recreated or not and it makes the code briefer import useCallback from react import externalFunction from services externalFunction const Component gt Do not do this const handleClick useCallback gt externalFunction return lt button onClick handleClick gt Click me lt button gt import externalFunction from services externalFunction const Component gt Do this instead return lt button onClick externalFunction gt Click me lt button gt Valid use cases for using a useCallback are when the callback calls multiple functions or when it reads or updates an internal state such as a value from useState hook or one of the components passed in props import useCallback from react import externalFunction anotherExternalFunction from services const Component passedInProp gt const value setValue useState This is okay const handleClick useCallback gt because we call multiple functions externalFunction anotherExternalFunction because we read and or set an internal value or prop setValue passedInProp passedInProp value return lt button onClick handleClick gt Click me lt button gt Do Not Use useMemo With Empty Dependency ListIf you ever add a useMemo with an empty dependency list ask yourself why you are doing so Is it because it is dependent on a component s state variable and you don t want to add it In that case we have already discussed that you should always list all dependency variables Is it because the useMemo doesn t really have any dependencies Well then just lift it out of the component it doesn t belong in there import useMemo from react const Component gt Do not do this const memoizedValue useMemo gt return return lt div gt memoizedValue lt div gt Do this instead const memoizedValue const Component gt return lt div gt memoizedValue lt div gt Do Not Declare Components Within Other ComponentsI see this a lot please stop doing it already const Component gt Don t do this const ChildComponent gt return lt div gt I m a child component lt div gt return lt div gt lt ChildComponent gt lt div gt What is the problem with it The problem is that you are misusing React As discussed before variables declared within a component will be redeclared every time the component renders In this case it means that the functional child component has to be recreated every time the parent rerenders This is problematic for multiple reasons A function will have to be instantiated on every render React won t be able to decide when to do any kind of component optimizations If hooks are used in ChildComponent they will be reinitiated on every render The component s lines of code increases and it gets hard to read I have seen files with tens or maybe twenties of these child components within a single React component What to do instead Merely declare the child component outside the parent component Do this instead const ChildComponent gt return lt div gt I m a child component lt div gt const Component gt return lt div gt lt ChildComponent gt lt div gt Or even better in a separate file Do this instead import ChildComponent from components ChildComponent const Component gt return lt div gt lt ChildComponent gt lt div gt Remember I write this article for a reason Do Not Use Hooks in If Statements No Conditional Hooks This one is explained in React s Documentation One should never write conditional hooks simply as that import useState from react const Component propValue gt if propValue Don t do this const value setValue useState propValue return lt div gt value lt div gt Do Not Use Hooks After Return No Conditional Hooks If statements are conditional by definition it s therefore easy to understand that you shouldn t place hooks within them when reading React s Documentation A little more sneaky keyword is the return keyword Many people don t realize return can result in conditional hook renders Look at this example import useState from react const Component propValue gt if propValue return null This hook is conditional since it will only be called if propValue exists const value setValue useState propValue return lt div gt value lt div gt As you can see a conditional return statement will make a succeeding hook conditional To avoid this put all your hooks above the component s first conditional rendering Or easier to remember simply always put you hooks at the top of the component import useState from react const Component propValue gt Do this instead place hooks before conditional renderings const value setValue useState propValue if propValue return null return lt div gt value lt div gt Let Child Components Decide if They Should RenderThis one isn t something you always should do but in many situations it s appropriate Let s consider the following code import useState from react const ChildComponent shouldRender gt return lt div gt Rendered shouldRender lt div gt const Component gt const shouldRender setShouldRender useState false return lt gt shouldRender amp amp lt ChildComponent shouldRender shouldRender gt lt gt Above is a common way to conditionally render a child component The code is fine apart from being a bit verbose when there are many child components But dependent on what ChildComponent does there may exist a better solution Let s rewrite the code slightly import useState from react const ChildComponent shouldRender gt if shouldRender return null return lt div gt Rendered shouldRender lt div gt const Component gt const shouldRender setShouldRender useState false return lt ChildComponent shouldRender shouldRender gt In the example above we have rewritten the two component s to move the conditional rendering into the child component You may wonder what s the benefit of moving conditional rendering into the child component The biggest benefit is that React can continue rendering ChildComponent even when it isn t visible That means ChildComponent can keep its state when it is hidden and then later getting rendered a second time without losing its state It s always there just not visible If the component instead would stop rendering as it does with the first code states saved in useState would be reset and useEffects useCallbacks and useMemos would all need to rerun and recalculate new values as soon as the component renders again If your code would trigger some network requests or doing some heavy calculations those would also run when the component is rendered again Likewise if you would have some form data stored in the component s internal state that would reset every time the component goes hidden As initially mentioned this isn t something you always want to do Sometimes you really want the component to unmount completely For example if you have a useEffect within the child component you may not want to continue running it on rerenders See the example below const ChildComponent shouldRender someOtherPropThatChanges gt useEffect gt If we don t want this code to run when shouldRender is false then don t keep render this component when shouldRender is false someOtherPropThatChanges if shouldRender return null return lt div gt Rendered shouldRender lt div gt const Component gt const shouldRender setShouldRender useState false return lt ChildComponent shouldRender shouldRender someOtherPropThatChanges someOtherPropThatChanges gt We could of course use conditional logic inside the child component to make the code above to work but that could be error prone And please recall conditional hooks aren t allowed so you cannot place the useEffect after the if statement const ChildComponent shouldRender someOtherPropThatChanges gt if shouldRender return null useEffect gt We cannot avoid running this useEffect by putting it after the null render Conditional hook rendering is not allowed in React someOtherPropThatChanges return lt div gt Rendered shouldRender lt div gt const Component gt const shouldRender setShouldRender useState false return lt ChildComponent shouldRender shouldRender someOtherPropThatChanges someOtherPropThatChanges gt Understanding useEffect useRef and Custom Hooks Dennis Persson・Mar ・ min read react frontend javascript beginners Use useReducer Instead of Multiple useStateInstead of bloating the component with multiple useState you can use one useReducer instead It may be cumbersome to write but it will both avoid unnecessary renders and can make the logic more understandable Once you have a useReducer it will be much easier to add new logic and states to your component There s no magical number of how many useState to write before refactoring to useReducer but I would personally say around three import useState from react const Component gt Do not add a lot of useState const text setText useState false const error setError useState const touched setTouched useState false const handleChange event gt const value event target value setText value if value length lt setError Too short else setError return lt gt touched amp amp lt div gt Write something lt div gt lt input type text value text onChange handleChange gt lt div gt Error error lt div gt lt gt import useReducers from react const UPDATE TEXT ACTION UPDATE TEXT ACTION const RESET FORM RESET FORM const getInitialFormState gt text error touched false const formReducer state action gt const data type action switch type case UPDATE TEXT ACTION const text data text return state text text error text length lt touched true case RESET FORM return getInitialFormState default return state const Component gt const state dispatch useReducer formReducer getInitialFormState const text error touched state const handleChange event gt const value event target value dispatch type UPDATE TEXT ACTION text value return lt gt touched amp amp lt div gt Write something lt div gt lt input type text value text onChange handleChange gt lt div gt Error error lt div gt lt gt Need even more structure consider using TypeScript Write Initial States as Functions Rather Than ObjectsNote the code from the current tip Look at getInitialFormState function Code removed for brevity Initial state is a function here const getInitialFormState gt text error touched false const formReducer state action gt Code removed for brevity const Component gt const state dispatch useReducer formReducer getInitialFormState Code removed for brevity See that I wrote the initial state as a function I could rather have used an object directly Code removed for brevity Initial state is an object here const initialFormState text error touched false const formReducer state action gt Code removed for brevity const Component gt const state dispatch useReducer formReducer initialFormState Code removed for brevity Why didn t I do that The answer is simple to avoid mutability In the case above when initialFormState is an object we could happen to mutate the object somewhere in our code If that s the case we wouldn t get the initial state back if we used the variable another time for example when resetting the form We would instead get the mutated object where for example touched could have a value of true That is also the case when running unit tests When testing the code above several tests could use the initialFormState and mutate it Each test would then work when they run individually while some of the tests would likely fail when all tests ran together in a test suite For that reason it s a good practice to turn initial states into getter functions that returns the initial state object Or even better use libraries like Immer which is used to avoid writing mutable code Use useRef Instead of useState When a Component Should Not RerenderDid you know you can optimize component renderings by replacing useState with useRef Check this code import useEffect from react const Component gt const triggered setTriggered useState false useEffect gt if triggered setTriggered true Some code to run here triggered When you run the code above the component will rerender when setTriggered is invoked In this case triggered state variable could be a way to make sure that the effect only runs one time which actually doesn t work in React learn why in this article about useRunOnce hook Since the only use of triggered variable in this case is to keep track if a function has been triggered or not we do not need the component to render any new state We can therefore replace useState with useRef which won t trigger the component to rerender when it is updated import useRef from react const Component gt Do this instead const triggeredRef useRef false useEffect gt if triggeredRef current triggeredRef current true Some code to run here Note missing dependency This isn t optimal Note the missing dependency to the useEffect that one is a bit tricker to fix when using useRef but React explains it in their documentation In the case above you may wonder why we need to use a useRef at all Why can t we simply use a variable outside of the component This does not work the same way const triggered falseconst Component gt useEffect gt if triggered triggered true Some code to run here The reason we need a useRef is because the above code doesn t work in the same way The above triggered variable will only be false once If the component unmounts the variable triggered will still be set to true when the component mounts again because the triggered variable is not bound to React s life cycle When useRef is used React will reset its value when a component unmounts and mounts again In this case we probably would want to uses useRef but in other cases a variable outside the component may be what we are searching for Dennis PerssonFollow I m a former teacher writing articles about software development and everything around it My ambition is to provide people all around the world with free education and humorous reading 2023-02-05 15:35:00
海外TECH DEV Community Get viewport width and height in JavaScript (with examples) https://dev.to/lavary/get-viewport-width-and-height-in-javascript-with-examples-1bn4 Get viewport width and height in JavaScript with examples Update This post was originally published on my blog decodingweb dev where you can read the latest version for a user experience rezaSometimes you need to get the viewport width or height in JavaScript probably to adjust an element based on the window size The good news is it s easy and quick Let s see how What is the viewport size You may ask Here s an explanation In a web browser context the term viewport more precisely the layout viewport refers to the area of the document you re currently viewing in the browser window Content outside the viewport is not visible onscreen until scrolled into view And the viewport size is the dimensions of this rectangular area But how do you find the width and height of a viewport in JavaScript yes without jQuery First of all you need to answer the following question Do I need a viewport width or height without or without the vertical scrollbar Let s see how we can solve both use cases Get viewport width including the vertical scrollbarTo get the viewport width including the vertical scrollbar if there s one all you need is the window innerWidth property a read only property that gives you the “interior viewport width in pixels console log window innerWidth And here s how you d do it for the layout viewport s height console log window innerHeight Please note the value of the window innerHeight property will include the horizontal scrollbar s height The window innerWidth and window innerHeight properties are compatible with most browsers but of course except for IE Who uses IE these days anyway Alright now that you know what window innerHeight and window innerWidth is Let s move on to the second scenario Get viewport width without the vertical scrollbarSometimes you don t want the vertical horizontal scrolls to be included in the viewport height and width In that case you should use the Element clientWidth and Element clientHeight on your document s html element You can access the root html element via document documentElement And here s how to get the layout viewport width in JavaScript without the scrollbar console log document documentElement clientWidth And for the viewport height console log document documentElement clientHeight If you get a ReferenceError when accessing the document check this quick guide on fixing document is not defined error Alright I think that does it I hope you found this quick guide helpful Thanks for reading 2023-02-05 15:22:16
海外TECH DEV Community About “__dirname is not defined in ES module scope” in JavaScript https://dev.to/lavary/about-dirname-is-not-defined-in-es-module-scope-in-javascript-eo3 About “ dirname is not defined in ES module scope in JavaScriptUpdate This post was originally published on my blog decodingweb dev where you can read the latest version for a user experience rezaThe error dirname is not defined in ES module scope means you re using dirname global variable in an ES ECMAScript module Here s what the error look like file dwd sandbox utils js return dirname ReferenceError dirname is not defined in ES module scopeThis file is being treated as an ES module because it has a js file extension and home dwd sandbox package json contains type module To treat it as a CommonJS script rename it to use the cjs file extension What does dirname mean in Node You may ask The dirname global variable contains the path to the current module s directory The global variables dirname and filename only exist in CommonJS modules and aren t available in ES modules So if you ve enabled ES modules in Node js via type module in package json or using ES modules through a module bundler like Webpack you ll no longer have access to these global variables This error is one of the most common errors developers face when switching from CommonJS modules to ES modules The workaround is quite easy though Here s how it s done Get the module file URL from the import meta objectConvert the URL to a path by fileUrlToPath Get the module s directory by using the path dirname methodimport fileURLToPath from url import path from path const filename fileURLToPath import meta url const dirname dirname filename The import meta object exposes context specific metadata to a JavaScript module including the module s URL Whenever you need the dirname value you ll have to repeat the above instructions It s better to create a helper function Create a helper function to emulate dirname functionalityYou can create a helper function which you can call anytime you need the dirname value utils jsimport path from path import fileURLToPath from url const getDirName function moduleUrl const filename fileURLToPath moduleUrl return path dirname filename export getDirName And use it like so ModuleA jsimport getDirName from libs utils Getting the dirname of moduleA jsconst dirName getDirName import meta url console log dirName output home dwd sandbox modulesPlease note you ll have to provide the import meta url when calling the getDirName function If you refer to it from inside the lib js module it ll return the utils js directory name home dwd sandbox libs I hope this guide was helpful Thanks for reading ️You might like Cannot find module error in Node js Fixed TypeError map is not a function in JavaScript in JavaScript Fixed SyntaxError Unexpected end of JSON input in JavaScript Fixed How to fix ReferenceError document is not defined in JavaScript 2023-02-05 15:11:19
海外TECH DEV Community How to get yesterday’s date in JavaScript without a library https://dev.to/lavary/how-to-get-yesterdays-date-in-javascript-without-a-library-1oj8 How to get yesterday s date in JavaScript without a libraryUpdate This post was originally published on my blog decodingweb dev where you can read the latest version for a user experience reza How to get yesterday s date using JavaScript To get yesterday s date in JavaScript you need to get today s date and use setDate of the Date object to subtract a day from it It s quite easy to implement You can do it in four steps Get the current date by Date constructorGet the day of the month via Date prototype getDate Subtract day from itUse Date prototype setDate to set the result as the day of the monthLet s write the code let currentDate new Date Instantiate another object based on the current so we won t mutate the currentDate objectlet yesterday new Date currentDate yesterday setDate yesterday getDate console log yesterday In the above example we get the current date today in this case Then we instantiate another date object to avoid mutating the currentDate object The getDate method returns the day of the month for our date object The return value is an integer number between and Next we subtract from the value returned by getDate and pass it to setDate as an argument If the result is outside the acceptable range for the respective month setDate will update the Date object accordingly by changing it to the next or previous month respectively For instance if we re on the first day of the month and we subtract a day the result would be the last day of the previous month instead of How do I get yesterday s timestamp To get the yesterday s date in Unix Timestamp first you need to call Date prototype valueOf on your Date object And since the returned value is in milliseconds you ll have to divide it by let currentDate new Date Instantiate another object based on the current so we won t mutate the currentDate objectlet yesterday new Date currentDate yesterday setDate yesterday getDate console log Math floor yesterday valueOf It s important to return only elapsed seconds as an integer value That s why we used Math floor and not Math round And that s how you get yesterday s date in JavaScripts hope you found this quick guide helpful Thanks for reading ️You might like Cannot find module error in Node js Fixed Add commas to numbers in JavaScript Explained with examples How to fix ReferenceError document is not defined in JavaScriptLabel htmlFor Property Explained 2023-02-05 15:01:38
Apple AppleInsider - Frontpage News Mac Studio may never get updated, because new Mac Pro is coming https://appleinsider.com/articles/23/02/05/mac-pro-with-apple-silicon-could-delay-mac-studio-refresh-to-m3-chip-generation?utm_medium=rss Mac Studio may never get updated because new Mac Pro is comingA refresh of the Mac Studio with an M Ultra may not happen soon or at all because of the Mac Pro Mac StudioApple s introduction of the M Pro and M Max in January as well as a spec bump upgrade to the Mac mini may not necessarily be followed by similar updates to the Mac Studio With Apple keen to bring out an Apple Silicon Mac Pro it is reckoned the Mac Studio s refresh with an M Ultra chip may be delayed or even stopped from being released Read more 2023-02-05 15:38:37
Apple AppleInsider - Frontpage News New super high-end iPhone could arrive by 2024 https://appleinsider.com/articles/23/02/05/new-pro-beating-iphone-ultra-model-could-arrive-by-2024?utm_medium=rss New super high end iPhone could arrive by Apple is thinking about extending the Pro line of iPhone even farther upwards with a report from a reliable leaker insisting it could arrive in An iPhone Ultra could be on the wayRumors since the middle of have put forward the notion that Apple could rebrand the iPhone Pro Max as the Ultra model as part of a bigger upgrade cycle If one report is to be believed Apple may save the Ultra name for an entirely new model instead Read more 2023-02-05 15:36:39
ニュース BBC News - Home Situation in east Ukraine getting tougher, says Zelensky https://www.bbc.co.uk/news/world-europe-64528580?at_medium=RSS&at_campaign=KARANGA country 2023-02-05 15:46:58
ニュース BBC News - Home Union boss Sharon Graham calls on Sunak to intervene on NHS pay https://www.bbc.co.uk/news/uk-politics-64529438?at_medium=RSS&at_campaign=KARANGA graham 2023-02-05 15:34:51
ニュース BBC News - Home IBSF World Championships 2023: Great Britain win joint silver in four-man bobsleigh https://www.bbc.co.uk/sport/winter-sports/64531183?at_medium=RSS&at_campaign=KARANGA IBSF World Championships Great Britain win joint silver in four man bobsleighBrad Hall Taylor Lawrence Greg Cackett and Arran Gulliver finish joint second to claim Britain s first four man medal at the World Championships since 2023-02-05 15:37:16

コメント

このブログの人気の投稿

投稿時間:2021-06-17 22:08:45 RSSフィード2021-06-17 22:00 分まとめ(2089件)

投稿時間:2021-06-20 02:06:12 RSSフィード2021-06-20 02:00 分まとめ(3871件)

投稿時間:2021-06-17 05:05:34 RSSフィード2021-06-17 05:00 分まとめ(1274件)