Avoiding node_modules in Webpack 2 with babel-loader

After updating to Webpack 2, I've run into an issue with the "exclude" property in my "rules". It seems I can no longer pass "exclude" into "options". What is the correct approach to handling this now?

Previously:

{
  test: /\.js$/,
  loader: 'babel-loader',
  exclude: /node_modules/,
}

Presently:

{
  test: /\.js$/,
  use: [{ loader: 'babel-loader' }]
  ???
}

The complete configuration:

const path = require('path');
    //const autoprefixer = require('autoprefixer');
    const postcssImport = require('postcss-import');
    const merge = require('webpack-merge');
    const CommonsChunkPlugin = require('webpack/lib/optimize/CommonsChunkPlugin');

    const development = require('./dev.config.js');
    const demo = require('./demo.config.js');
    const test = require('./test.config.js');
    const staging = require('./staging.config.js');
    const production = require('./prod.config.js');

    const TARGET = process.env.npm_lifecycle_event;

    const PATHS = {
      app: path.join(__dirname, '../src'),
      build: path.join(__dirname, '../dist'),
    };

    process.env.BABEL_ENV = TARGET;

    const common = {
      entry: [
        PATHS.app,
      ],

      output: {
        path: PATHS.build,
        filename: 'bundle.js',
        chunkFilename: '[name]-[hash].js',
      },

      resolve: {
        alias: {
          config: path.join(PATHS.app + '/config', process.env.NODE_ENV || 'development'),
          soundmanager2: 'soundmanager2/script/soundmanager2-nodebug-jsmin.js',
        },
        extensions: ['.jsx', '.js', '.json', '.scss'],
        modules: ['node_modules', PATHS.app],
      },

      module: {
        rules: [{
          test: /bootstrap-sass\/assets\/javascripts\//,
          use: [{ loader: 'imports-loader', options: { jQuery: 'jquery' } }]
        }, {
          test: /\.woff(\?v=\d+\.\d+\.\d+)?$/,
          use: [{ loader: 'url-loader', options: { limit: '10000', mimetype: 'application/font-woff' } }]
        }, {
          test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/,
          use: [{ loader: 'url-loader', options: { limit: '10000', mimetype: 'application/font-woff' } }]
        }, {
          test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
          use: [{ loader: 'url-loader', options: { limit: '10000', mimetype: 'application/octet-stream' } }]
        }, {
          test: /\.otf(\?v=\d+\.\d+\.\d+)?$/,
          use: [{ loader: 'url-loader', options: { limit: '10000', mimetype: 'application/font-otf' } }]
        }, {
          test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
          use: [{ loader: 'file-loader' }]
        }, {
          test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
          use: [{ loader: 'url-loader', options: { limit: '10000', mimetype: 'image/svg+xml' } }]
        }, {
          test: /\.js$/,
          //loader: 'babel-loader',
          //exclude: /node_modules/,
          //use: [{ loader: 'babel-loader', options: { exclude: '/node_modules/' } }]
          use: [{ loader: 'babel-loader' }]
          //use: [{ loader: 'babel-loader', options: { cacheDirectory: true } }]
        }, {
          test: /\.png$/,
          use: [{ loader: 'file-loader', options: { name: '[name].[ext]' } }]
        }, {
          test: /\.jpg$/,
          use: [{ loader: 'file-loader', options: { name: '[name].[ext]' } }]
        }, {
          test: /\.gif$/,
          use: [{ loader: 'file-loader', options: { name: '[name].[ext]' } }]
        }],
      },
    };

    if (TARGET === 'start' || !TARGET) {
      module.exports = merge(development, common);
    }

    if (TARGET === 'build' || !TARGET) {
      module.exports = merge(production, common);
    }

    if (TARGET === 'lint' || !TARGET) {
      module.exports = merge(production, common);
    }

Answer №1

Just implement the following in your code:

module: {
    rules: [
        {
             test: /\.jsx?$/,
             include: [
                path.resolve(__dirname, "app")
              ],
             exclude: [
                path.resolve(__dirname, "app/demo-files")
             ]
        }
    ]
}

For more information, check out: https://webpack.js.org/configuration/

Answer №2

Here's how we overcame the identical issue

{
  condition: /\.js$/,        
  use: [{
    script: 'babel-script',
    options: {
      ignore: '/modules/node/'        
    }
  }]
}

source: https://babeljs.io/docs/usage/api/

Answer №3

The exclude parameter in webpack 2 remains the same as demonstrated, although it has not been tested, it is designed to function in that manner.

module: {
        loaders: [
        {
            test: /\.jsx?/,
            loader: 'babel-loader',
            exclude: [/node_modules/]
        },
    {
        test: /\.(jpg|png|gif|eot|woff2|woff|ttf|ico|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: 'url-loader'
    },
    {
        test: /\.(js)$/,
        loader: `babel-loader`,
        exclude: [/node_modules/]
    }]
}

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

Prevent the onClick event in the parent container div from triggering when clicking on a child element

Having trouble with event bubbling and onClick functions within a card element. The card has a heart icon that triggers an onClick function to unlike the card, but it also triggers the onClick function for the entire card which leads to a different page wi ...

Update the text for the filter search placeholder in the Ant Table component

Is there a way to alter the default placeholder text in the Ant Table? I've set up a functioning example in documentation but couldn't find any prop for customization besides the customized filter dropdown, which I didn't want to implement. ...

Dealing with browser timeouts for HTTP requests using JavaScript

Managing time out situations in a web application when calling a REST API is crucial. Below is the code snippet I am using to make the API call with jQuery ajax. $.ajax({ type: "POST", url: endpoint, data: payload, ...

Steps for embedding a function within another function

One method I know is by using this hack: function executeFunction(func){ setInterval(func,0); } executeFunction("newFunction()"); However, I am searching for a more elegant solution. ...

Saving $routeParam in a variable within a factory service in AngularJS Store

Recently I started working with Angular and now I'm attempting to extract the project ID from the URL and use it as a variable within a service. Here's my current code snippet: app.config( ['$routeProvider', function($routeProvi ...

Transform a string into a property of a JSON object

One of my challenges involves extracting a value from a JSON object called Task, which contains various properties. Along with this, I have a string assigned to var customId = Custom_x005f_f3e0e66125c74ee785e8ec6965446416". My goal is to retrieve the value ...

Issue: Error occurs when using _.sample on an array containing nested arrays

I am working with an array of arrays that looks like this: [[0,0], [0,1], [0,2], [0,3]...] My goal is to randomly select N elements from the array using Underscore's _.sample method: exampleArr = [[0,0], [0,1], [0,2], [0,3]...] _.sample(exampleArr, ...

Following my ajax submission, the functionality of my bootstrap drop-down menu seems to have been compromised

I'm having an issue with my login page. After implementing Ajax code for the reset password feature, the dropdown menu on the login page doesn't work properly when wrong details are entered and the page reloads. I've tried using the $(' ...

In Material-UI, what is the reason behind setting this variable equal to its own value?

Currently, I'm struggling to understand the reasoning behind Material-UI setting a variable equal to itself for its Popover component. Take a look at the snippet of code and pay attention to the two if blocks before the return statement. I'm cu ...

Issue: missing proper invocation of `next` after an `await` in a `catch`

I had a simple route that was functioning well until I refactored it using catch. Suddenly, it stopped working and threw an UnhandledPromiseRejectionWarning: router.get('/', async (req, res, next) => { const allEmployees = await employees.fi ...

An error occurred while trying to serialize the `.res` response received from the `getServerSideProps` function in

I encountered the following issue while utilizing the getServerSideProps function to fetch data from Binance API. import binance from "../config/binance-config"; export async function getServerSideProps() { const res = await binance.balance(( ...

Inject JavaScript Object Information into Bootstrap Modal

After iterating through each object and assigning its data to an individual div along with a button, I encountered an issue. When testing the buttons, I noticed that only the last object's data was displayed in all of the modal windows. Any suggestion ...

"Unfortunately, the JavaScript external function failed to function properly, but miraculously the inline function

Struggling to create a fullscreen image modal on the web? I was able to get it working fine when embedding the script directly into my HTML file, but as soon as I moved it to an external JS file, things fell apart. I've double-checked all the variable ...

Struggling with implementing React routing in version 4.0

Struggling to route multiple pages using BrowserRouter in Reactv4. Many online guides are outdated and not working with the latest version. Here is my setup: Index.js: import React from 'react'; import ReactDOM from 'react-dom'; impo ...

When utilizing JavaScript within an Electron application file that is linked with a script tag in an HTML document, there may be limitations on using node modules with

While working on my Electron application, I encountered an issue with referencing a node module using require within an HTML form that includes JavaScript. Specifically, I am having trouble integrating the 'knex' node module into my code. Here i ...

Sorting a Javascript table performs effectively, however, the results may vary when iterating through all the indexes

I'm currently using a function to sort a table I have: function ReorderSupplyGP(table){ table.find('tr:not(.kn-table_summary)').sort(function (a, b) { var tda = $(a).find('td:eq(1)').text().trim(); var tdb = $(b).find(&a ...

Tips for retrieving the ajax results for multiple deferred calls using jQuery

I am struggling to utilize the jQuery deferred function as illustrated in the following code snippet. <script type="text/javascript"> var appUrls = { GetDataUrl : '@Url.Action("GetData")' }; ...

Exploring the Difference Between $onChanges and $onInit in Angular Components

What sets apart the use of Controller1 compared to Controller2? angular.module('app', []) .component('foo', { templateUrl: 'foo.html', bindings: { user: '<', }, controller: Controller1, ...

When attempting to showcase an MUI icon that was imported, I encounter the following issues: Invalid hook call and the <ForwardRef(SvgIcon)> component

Encountering issues while trying to display an imported MUI icon leads to the following errors: Error: https://i.stack.imgur.com/USdEx.png Sample Code: import React from 'react' import ThreeDRotation from '@mui/icons-material/ThreeDRotati ...

Why won't both routes for Sequelize model querying work simultaneously?

Currently, I am experimenting with different routes in Express while utilizing Sequelize to create my models. I have established two models that function independently of one another. However, I am aiming to have them both operational simultaneously. A sea ...