2014-10-07 4 views
3

Я использую webpack для сборки моих файлов javascript.Webpack и modernizr вызывает TypeError: document is undefined error

Моего Webpack конфигурация (который передается WebPack с помощью глотка) выглядит следующим образом:

var webpackConfig = { 
     context: __dirname, 
     entry: { 
      "app": "./js/app.js" 
     }, 
     output: { 
      path: path.join(__dirname, ".."), 
      filename: "/js/[name].js", 
      chunkFilename: "/js/[id].js" 
     }, 
     plugins: [ 
      new webpack.ResolverPlugin(
       new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin("bower.json", ["main"]) 
      ) 
     ], 
     resolve: { 
      modulesDirectories: ['js', 'bower_components', 'node_modules'] 
     } 
    }; 

My app.js простые требуется:

require('modernizr/modernizr.js'); 

Webpack строит файл без каких-либо проблем и Сгенерированный файл содержит modernizr.

Проблема заключается в том, что, когда я включаю файл на странице и проверить его, Modernizr ошибки вне:

TypeError: document is undefined 

docElement = document.documentElement, 

Связанный файл из WebPack выглядит следующим образом:

/******/ (function(modules) { // webpackBootstrap 
/******/ // The module cache 
/******/ var installedModules = {}; 
/******/ 
/******/ // The require function 
/******/ function __webpack_require__(moduleId) { 
/******/ 
/******/  // Check if module is in cache 
/******/  if(installedModules[moduleId]) 
/******/   return installedModules[moduleId].exports; 
/******/ 
/******/  // Create a new module (and put it into the cache) 
/******/  var module = installedModules[moduleId] = { 
/******/   exports: {}, 
/******/   id: moduleId, 
/******/   loaded: false 
/******/  }; 
/******/ 
/******/  // Execute the module function 
/******/  modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); 
/******/ 
/******/  // Flag the module as loaded 
/******/  module.loaded = true; 
/******/ 
/******/  // Return the exports of the module 
/******/  return module.exports; 
/******/ } 
/******/ 
/******/ 
/******/ // expose the modules object (__webpack_modules__) 
/******/ __webpack_require__.m = modules; 
/******/ 
/******/ // expose the module cache 
/******/ __webpack_require__.c = installedModules; 
/******/ 
/******/ // __webpack_public_path__ 
/******/ __webpack_require__.p = ""; 
/******/ 
/******/ // Load entry module and return exports 
/******/ return __webpack_require__(0); 
/******/ }) 
/************************************************************************/ 
/******/ ([ 
/* 0 */ 
/***/ function(module, exports, __webpack_require__) { 

    __webpack_require__(1); 

/***/ }, 
/* 1 */ 
/***/ function(module, exports, __webpack_require__) { 

    /*! 
    * Modernizr v2.8.3 
    * www.modernizr.com 
    * 
    * Copyright (c) Faruk Ates, Paul Irish, Alex Sexton 
    * Available under the BSD and MIT licenses: www.modernizr.com/license/ 
    */ 

    /* 
    * Modernizr tests which native CSS3 and HTML5 features are available in 
    * the current UA and makes the results available to you in two ways: 
    * as properties on a global Modernizr object, and as classes on the 
    * <html> element. This information allows you to progressively enhance 
    * your pages with a granular level of control over the experience. 
    * 
    * Modernizr has an optional (not included) conditional resource loader 
    * called Modernizr.load(), based on Yepnope.js (yepnopejs.com). 
    * To get a build that includes Modernizr.load(), as well as choosing 
    * which tests to include, go to www.modernizr.com/download/ 
    * 
    * Authors  Faruk Ates, Paul Irish, Alex Sexton 
    * Contributors Ryan Seddon, Ben Alman 
    */ 

    window.Modernizr = (function(window, document, undefined) { 

     var version = '2.8.3', 

     Modernizr = {}, 

     /*>>cssclasses*/ 
     // option for enabling the HTML classes to be added 
     enableClasses = true, 
     /*>>cssclasses*/ 

     docElement = document.documentElement, 

     /** rest of modernizr code here **/ 

     return Modernizr; 

    })(this, this.document); 


/***/ } 
/******/ ]) 

Что вызывает это проблема?

+0

У меня такая же проблема с browserify + debowerify. Вы когда-нибудь это решали? – Ilkka

+0

@Ilkka Посмотрите ответ, который я разместил. – F21

ответ

1

Эта проблема вызвана тем, что Modernizr проходит this.document к закрытию, которое он создает. К сожалению, webpack обертывает все это еще одним закрытием, вызывая this.document, чтобы вернуть null.

Проблема может быть решена путем установки this с помощью imports loader когда требует:

require('imports?this=>window!modernizr/modernizr.js'); 
+1

В моем проекте modernizr требуется довольно много, поэтому не хочу менять везде. Могу ли я добавить что-то в загрузчик, чтобы по умолчанию у каждого требуемого файла '' 'this = window'''? –

1

Я была такая же проблема, но не требует Modernizr непосредственно. Мне нужна библиотека, в которой был упакован «Модернир». Предыдущее решение не работает в этом сценарии. В конце концов я в конечном итоге с помощью script-loader:

require('script!package/vendor-bundle.js);