Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to require parts of jquery with webpack

I am using this article to import only the parts of jquery that I would need.

However, I am running into an issue when doing using this code:

let $ = require('jquery/src/core');
require('jquery/src/core/init');
require('jquery/src/css');
console.log($);

I get this error:

ERROR in ./~/jquery/src/selector-sizzle.js
Module not found: Error: Cannot resolve 'file' or 'directory' ../external/sizzle/dist/sizzle in /home/vamsi/Do/highland-fun/bacon-form/node_modules/jquery/src
 @ ./~/jquery/src/selector-sizzle.js 1:0-14:3

This is my webpack.config.js file:

module.exports = {
    entry:'./app',
    output:{
      filename:'./bundle'
    },
    modules:{
      loaders:[
        {
           test:/jquery[\\\/]src[\\\/]selector\.js$/,
           loaders:['amd-define-factory-patcher-loader']
        }
      ]
    }
}

I have tried to use a resolve.alias to fix this:

resolve:{                                                                
  alias:{                                                                
   '../external/sizzle/dist/sizzle':'./node_modules/sizzle/dist/sizzle.js'
  }                                                                      
}

But it still throws the same error as before.

like image 688
vamsiampolu Avatar asked Dec 14 '22 08:12

vamsiampolu


1 Answers

The Problem

I am using this article to import only the parts of jquery that I would need.

This article was written before jquery 2.2.0 was released.

In jquery 2.1.x:

// jquery/src/selector-sizzle.js

define([
    "./core",
    "sizzle"
], function( jQuery, Sizzle ) {
  //...
})

So sizzle is resolved as <base-dir>/node_modules/sizzle

However in jquery 2.2.x:

// jquery/src/selector-sizzle.js

define([
    "./core",
    "../external/sizzle/dist/sizzle" // <- missing
], function( jQuery, Sizzle ) {
  //...
})

If you look in <base-dir>/node_modules/jquery you'll see that <base-dir>/node_modules/jquery/external is missing. This directory exists in the jquery repo, but ignored within the jquery npm package.

Solutions

Unfortunately, I didn't manage to solve this with webpack's resolve.alias in any way. Alternatively, one of these solutions will work for you:

  • Use jquery 2.1.4 -> "jquery": "~2.1.4"
  • Stay with jquery 2.2.x and use string-replace-loader as a pre-loader to replace "../external/sizzle/dist/sizzle" with "sizzle":

npm i string-replace-loader --save-dev

// webpack.config.js

module.exports = {
    //...
    module: {
        preLoaders: [{
            test: /jquery[\\\/]src[\\\/]selector-sizzle\.js$/,
            loader: 'string-replace',
            query: {
                search: '../external/sizzle/dist/sizzle',
                replace: 'sizzle'
            }
        }]
    }
    //...
};

Note: In both solutions you will have to npm i sizzle --save

like image 183
Ramy Ben Aroya Avatar answered Dec 17 '22 00:12

Ramy Ben Aroya