How can you use Require.context in Webpack to import all .js files from a directory except those ending in `_test.js`?

My objective was to develop a script that accomplishes the following tasks:

  1. Import all JS files from a directory excluding those ending in _test.js
  2. Set up a module.exports containing an array of module names extracted from those imported files.

Initially, I believed I had succeeded with the code below:

// This script scans through the directory, identifies all javascript files within any subdirectory,
// excludes test files, imports the list of files, and assigns the exported module names as dependencies to the myApp.demoApp.views module.
var context = require.context('.', true, /\/.*\/.*\.js$/);
var moduleNames = _.chain(context.keys())
  .filter(function(key) {
      console.log(key, key.indexOf('_test.js') == -1);
    return key.indexOf('_test.js') == -1;
  })
  .map(function(key) {
      console.log("KEY", key);
    return context(key)
  })
  .value();
module.exports = angular.module('myApp.demoApp.views', moduleNames).name;

#2 functions as intended

#1 Unfortunately, I made the mistake of overlooking a crucial detail. Despite successfully filtering out the module names, it still imports all files with _test, resulting in test files being included in my final code.

I attempted to resolve this by adjusting the regex pattern, but JavaScript does not support negative lookbehind in regex, and my regex skills are not advanced enough to work around this limitation.

Answer №1

After reading Slava.K's comment, I was able to successfully implement the solution to my query. Below is the finalized code which now includes the (?!.*index) in the regex to prevent index.views.js from being included.

var context = require.context('.', true, /^(?!.*index).*\/(?!.*test).*\.js$/);

var moduleNames = _.chain(context.keys())
  .map(function(key) {
    return context(key)
  })
  .value();

module.exports = angular.module('myApp.demoApp.views', moduleNames).name;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue: The type 'void' cannot be assigned to the type 'ReactNode' in the array.map() function

Having trouble with my function call error within the practice setup in App.tsx. My expectation of array.map() being compatible with TypeScript seems to be incorrect. The generated HTMLElement from this map is not displaying on screen. Any suggestions on ...

How can we integrate information from a local JSON file onto our website?

My role is with a small publishing company that has an internal website featuring a static HTML table showcasing our published products. We are looking to dynamically list and sort our products (with about 1-2 items published daily) based on data from an ...

Can Socket.IO link to a source tag that doesn't actually exist?

As I was following the 'Get started thing' tutorial on Socket.IO, I encountered a step that required me to add the socket.io.js script to my HTML page. The instruction provided was: /socket.io/socket.io.js However, when I checked my folders, I ...

AngularJS - Smoothly navigate to the top of the page by swiping left or right

I'm currently working on a project in angularJS and ionic that involves a slidebox with three slides, each containing different content. My goal is to scroll back to the top every time I switch between slides. Initially, I thought using on-swipe-left ...

Aggregate the data entered into input fields on one page and display them on a separate page

Can you help me with this task? - I have 2 pages set up (page 1 has input fields & page 2 is where the entered data should be displayed) - I want to retrieve all the text input from the first field and insert it into the "content" tag on the second page. ...

How to trigger a function when clicking on a TableRow in React using MaterialUI

Can someone help me understand how to add an onClick listener to my TableRow in React? I noticed that simply giving an onClick prop like this seemed to work: <TableRow onClick = {()=> console.log("clicked")}> <TableCell> Content </Ta ...

Avoid generating `.d.ts` definition files during the onstorybook build process in a Vite React library project

I am currently developing a component library using react and typescript. I have integrated Vite into my workflow, and every time I build Storybook, the dts plugin is triggered. This has two undesired effects: It generates numerous unnecessary folders an ...

How to programmatically unselect an ng-checkbox in AngularJS when it is removed from an array

Utilizing checkboxes to gather values and store them in an array for dataset filtering purposes. The objectives are as follows: Show child filters when parent category is selected. Unselect all children if parent is unselected (otherwise they will ...

Different ways to use jquery to move to the top of an overflow div

$('.lb').click(function() { $('#modal').hide(); var id = $(this).attr('id'); var dir = '/lightbox/' + id + '.php'; $('#lightbox').find('#modal').load(dir, function() { ...

The jQuery.addClass() function seems to be malfunctioning

I'm encountering an issue with the addClass() method. For some reason, it's not functioning properly in this scenario: https://jsfiddle.net/0g1Lvk2j/20/ If you scroll to the end and close the last box by clicking on the orange box, the orange b ...

Removing value from an AngularJS checkbox when it is unchecked

Our shopping portal project has a feature where checking a checkbox adds the item to the cart. However, we encountered an issue - even when we uncheck the checkbox, the item still gets added. And if we check it again, another value is added. https://i.sta ...

AngularJS UI router allows for the creation of sticky states, where each state maintains its own instance of the controller even when

Currently, I am in the process of developing a CMS with a tabular structure using AngularJS. The main functionality is to allow users to open and edit multiple articles within tabs. Each article is handled by the articleController and has different URL par ...

The resume button is failing to activate any functions

I recently encountered an issue with a JS file that is associated with a Wordpress Plugin, specifically a Quiz plugin featuring a timer. I successfully added a Pause and resume button to the quiz, which effectively pauses and resumes the timer. However, I ...

Tabulator now maintains the position of the rightmost column when adjusting the width of table columns

Is there a way to keep the right most column in a fixed position when adjusting column sizes? Whenever I try to resize a column, the right most column moves along with it, causing a gap or horizontal scroll bar to appear. How can I adjust all the columns ...

Issue with bundling project arises post upgrading node version from v6.10 to v10.x

My project uses webpack 2 and awesome-typescript-loader for bundling in nodejs. Recently, I upgraded my node version from 6.10 to 10.16. However, after bundling the project, I encountered a Runtime.ImportModuleError: Error: Cannot find module 'config ...

Unable to retrieve props from server-side page to client-side component in a Next.js application router

Currently, I am utilizing app router alongside Next.js version 13.5. Within my /dashboard page (which is a server component), there is an ApiKeyOptions client component embedded. However, when attempting to pass props from the dashboard page to the ApiKeyO ...

Is there a way to prevent the window.on('beforeUnload') event from triggering when using the <a> tag?

For my project, I require a user confirmation alert to appear when the user attempts to close the window or tab using the X button. However, the window.on('beforeUnload') function also triggers for hyperlinks. How can I prevent the leave page al ...

Activating Unsplash API to initiate download

I am currently following the triggering guidelines found in the Unsplash documentation. The endpoint I am focusing on is: GET /photos/:id/download This is an example response for the photo: { "id": "LBI7cgq3pbM", "width": ...

Tips for removing alert notifications from Pusher

I have integrated PUSHER into my website for notifications. The codes are successfully added and it is working fine. However, the issue arises when the alert is triggered as I am receiving messages that are not what I expected. The message received from t ...

Transform Objects Array from AJAX Response into a Distinct JSON Entity

I am encountering a problem with a sample endpoint that is returning [object Object] for JSON data, and I can't figure out why. Mock API Initially, my code was a bit confusing, but fortunately, I found a clearer solution in another answer. functio ...