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

前端 未结 10 2234
挽巷
挽巷 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:39

    While @roberto's answer looks great, I wanted to provide a simpler solution (in which it does not require any extra vendor/foundation files).

    In your webpack config use this:

    // this will force the export of the jQuery 'foundation' function, 
    // which we'll use later on
    loaders: [
      {
        test: /(foundation\.core)/,
        loader: 'exports?foundation=jQuery.fn.foundation'
      }
    ],
    
    // this makes sure that every module can resolve define(['foundation']) calls
    resolve: {
      extensions: ['', '.js'],
      alias: {
        foundation: 'foundation-sites/js/foundation.core'
      }
    },
    
    // this makes sure 'jQuery' is available to any jQuery plugin you might want 
    // to load (including Foundation files) regardless of how they are written
    plugins: [
      new webpack.ProvidePlugin({
        $: 'jquery',
        jQuery: 'jquery',
        'window.jQuery': 'jquery'
      })
    ]
    

    And in your index.js:

    // thanks to the ProvidePlugin we don't need to
    // > import $ from 'jquery';
    
    // required core foundation files
    import { foundation } from 'foundation-sites/js/foundation.core';
    import 'foundation-sites/js/foundation.util.mediaQuery';
    
    /* import here any additional module */
    
    // we need to attach the function we force-exported in the config
    // above to the jQuery object in use in this file
    $.fn.foundation = foundation;
    
    // ready to go
    $(document).ready(function() {
      $(document).foundation();
      …
    });
    

    NOTE #1 (thank you @mtyson)
    You need to use the exports loader: $ npm install --save exports-loader or $ npm install --save-dev exports-loader

    NOTE #2
    Since jQuery is not global inside single modules (or for some other reason that is beyond my understanding), there might be problems relying on data- attributes for Foundation JS components. If that is the case, you can always use the pure javascript way as documented in Foundation docs.

提交回复
热议问题