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

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

    I was able to do this with webpack by essentially doing an end-run around loading it as a module.

    This is basically a hack though, Foundation really needs to update its JS to be loadable as a commonJS module.

    The problem stems from Foundation's JS referencing dependencies in erratic ways from within nested IFFEs in the souce code. Sometimes jQuery is the local jQuery parameter, sometimes it's $, sometimes it's window.jQuery. It's really a mixed-bag. The combination of all the different mechanisms means there's no single shimming solution other than to just load the thing non-modularly.

    Honestly it's pretty much amateur hour in there, but as of this writing they just released the thing last week, so hopefully it'll be fixed soon.

    Anyhoo... to the hack:

    I make a separate vendor bundle and load all the amateur-hour 3rd party npm libraries there because I just get tired of fighting with all the various shimming mechanisms necessary to wrap poorly-shipped open-source npm package code.

    My vendor bundle is a separate entry point that I register with webpack, and it contains all the libraries that do not play nice as modules.

    require('!!script!jquery/dist/jquery.min.js');
    
    require('!!script!uglify!foundation-sites/js/foundation.core.js');
    require('!!script!uglify!foundation-sites/js/foundation.accordion.js');
    require('!!script!uglify!foundation-sites/js/foundation.util.keyboard.js');
    require('!!script!uglify!foundation-sites/js/foundation.util.motion.js');
    // etc.
    

    Make sure you have script-loader installed

    npm install script-loader -D
    

    The !! means "Ignore all the other rules I already defined in the config". Using the script-loader tells webpack to load and execute the file in the window scope essentially the same as if you had just included a script tag on your page. (But it doesn't, obviously.)

    You could get fancier and write your own resolve rules so that it checks just stuff in the foundation-library, but I didn't bother because I hope a library as pervasive as Foundation gets their act together in the near future so I can just delete this hack.

    Also... in your main webpack configuration you will want to reference jQuery and any other global window variables loaded in this way as externals.

    var webpackConfig = {
        entry: { // blah },
        output: { // blah },
        loaders: [ // blah ],
        externals: {
            jquery: "jQuery"
        }
    };
    
    0 讨论(0)
  • 2020-12-23 18:23

    Here is how I am using the hack. I put foundation and jquery in a separate entry point called vendor and loaded them with the script-loader. The only relevant bits are in the vendor entry point.

    var path = require('path');
    var webpack = require('webpack');
    var hotMiddlewareScript = 'webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000&reload=true';
    var autoprefixer = require('autoprefixer');
    
    module.exports = {
      name: 'main',
    
      devtool: 'eval',
    
      entry: {
        client: [
          path.resolve(__dirname, 'client', 'index.js'),
          hotMiddlewareScript
        ],
        vendor: [
          'font-awesome/css/font-awesome.css',
          'foundation-sites/dist/foundation-flex.css',
          '!!script!jquery/dist/jquery.min.js',
          '!!script!foundation-sites/dist/foundation.min.js',
        ]
      },
    
      output: {
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].js',
        publicPath: '/dist/'
      },
    
      resolve: {
        modulesDirectories: ['node_modules', './client'],
        extensions: ['', '.js', '.jsx']
      },
    
      plugins: [
        new webpack.optimize.OccurenceOrderPlugin(),
        new webpack.HotModuleReplacementPlugin(),
        new webpack.NoErrorsPlugin(),
        new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.bundle.js'),
        new webpack.ProvidePlugin({'$': 'jquery', jQuery: 'jquery'})
      ],
    
      module: {
        loaders: [
          { test: /\.(js|jsx)$/, loaders: ['react-hot', 'babel-loader'], exclude: /node_modules/, include: path.resolve(__dirname, 'client') },
          { test: /\.scss$/, loader: "style!css!autoprefixer-loader?browsers=last 2 versions!sass" },
          { test: /\.css$/, loader: "style!css" },
          // { test: /\.(png|jpg|jpeg|gif)$/, loader: 'file-loader?name=images/[name].[ext]' },
          { test: /\.(webm|mp4|mov|m4v|ogg)$/, loader: 'file-loader?name=videos/[name].[ext]' },
          { test: /\.(eot|svg|ttf|woff|woff2)/, loader: 'file-loader?name=fonts/[name].[ext]' }
        ]
      }
    };
    
    0 讨论(0)
  • 2020-12-23 18:24

    I have same problem, but I don't want have two .js files (vendor and app)!

    For me, everything need be on a single file, so, I make this:

    In webpack.conf.js, use externals (maybe have another way without external, but for me, this is sufficient):

    externals: {
        jQuery: 'jQuery',
        foundation: 'Foundation'
    },
    

    create a file in your source folder (any name, like /libs/foundation.js):

    // jQuery
    var $ = require('jquery');
    global.jQuery = $;
    
    // if you want all features of foundation
    require('./node_modules_folder/foundation-sites/dist/foundation.js');
    
    // if you want only some features
    // require('./node_modules/what-input/what-input');
    // require('./node_modules/foundation-sites/js/foundation.core');
    // require('./node_modules/foundation-sites/js/....');
    
    export default Foundation;
    

    now, you can use Foundation in any js using following syntax:

    import Foundation from './libs/foundation';
    
    0 讨论(0)
  • 2020-12-23 18:26

    Just use the script-loader (npm i script-loader) and prefix your imports with a script!. Then it will be evaluated in the global scope.

    To load all js files from foundation use this

    import 'script!jquery'
    import 'script!what-input'
    import 'script!foundation-sites'
    

    Like I do it in my entry point

    You can check out my boilerplate project to try it out: https://github.com/timaschew/r3-foundation-boilerplate

    0 讨论(0)
  • 2020-12-23 18:26

    It works fine for webpack if you can tell it to ignore the define test for the troublesome code below:

      if (typeof module !== 'undefined' && typeof module.exports !== 'undefined')
         module.exports = Reveal;
      if (typeof define === 'function')
         define(['foundation'], function() {
         return Reveal;
      });
    

    The best way to do that is to use the imports-loader and set define to false.

    require('foundation-sites/js/foundation.core.js');
    require('foundation-sites/js/foundation.util.keyboard.js');
    require('foundation-sites/js/foundation.util.box.js');
    require('foundation-sites/js/foundation.util.triggers.js');
    require('foundation-sites/js/foundation.util.mediaQuery.js');
    require('foundation-sites/js/foundation.util.motion.js');
    require('imports?define=>false!foundation-sites/js/foundation.reveal.js');
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题