NPM + Zurb Foundation + WebPack: Cannot resolve module 'foundation'

前端 未结 10 2230
挽巷
挽巷 2020-12-23 17:59

I am working on using Zurb Foundation with WebPack and NPM, without Bower.

The problem I am encountering is the same as this below:

https://github.c

10条回答
  •  被撕碎了的回忆
    2020-12-23 18:29

    I'll post my complete workaround based on Mason Houtz and pharmakon's great answers in case it helps someone, since I struggled with it a bit, learning Webpack in the process.

    In my case I had an added complication, because other jQuery plugins were somehow working only inside their own module, while outside their properties were undefined. Apparently they were using a local, duplicate jQuery object.

    Anyway, here's what you need to do:

    1. Install scripts-loader: npm install --save-dev script-loader

    2. In Webpack's config:

      • Add new entry, let's call it vendor. This will compile a new vendor.js whenever Webpack runs.

        entry: {
            ...,
            "vendor": [
                "!!script!jquery/dist/jquery.min.js",
                "!!script!foundation-sites/dist/foundation.min.js"
            ]
        },
        
      • Add jquery to externals. This makes sure any references to jquery inside your main JS will be replaced with a reference to global jQuery variable, which is made available by vendor.js above.

        entry : {
            // ...
        },
        externals: {
            jquery: "jQuery"
        }
        
    3. Make sure every module that uses jQuery imports it:

      var $ = require('jquery');
      

    The externals config above will replace it with a reference to global jQuery variable, instead of re-importing duplicate jQuery "properly". Optionally you could make use of ProvidePlugin, which will automatically do the above whenever it encounters jQuery in a module, saving you a few keystrokes. If you want that, put the following in Webpack's config:

    plugins: [
        // ...,
        new webpack.ProvidePlugin({
          '$': 'jquery', 
          jQuery: 'jquery'
        })
    ]
    
    1. Include the new vendor.js to your page, obviously before the main JS.

    It's quite possible there's an easier or more elegant way to do this, but I just wanted a quick, working solution, until Foundation hopefully fixes the issue soon.

提交回复
热议问题