2016-11-29 48 views
2

我在這個ReactJS項目中工作,並且我有一個讀取子文件夾package.json的要求,將它們全部安裝到node_modules中,之後安裝所有依賴項將它們添加到全局變量,以便它們可以在代碼中的任何地方使用。Webpack:在不使用ProvidePlugin和Expos-loader的情況下公開全局變量

問題是,我沒有訪問到由於來自webpack.config.js(我需要動態地添加它們)的語法的公開加載器上的jsons,所以相反,我創建了一個加載器測試package.json,獲取依賴關係並嘗試複製expose-loader行爲。

這是

var toCamelCase = function(str) { 
    return str.toLowerCase() 
    .replace(/[-_]+/g, ' ') 
    .replace(/[^\w\s]/g, '') 
    .replace(/ (.)/g, function($1) { return $1.toUpperCase(); }) 
    .replace(/ /g, ''); 
} 

var returning_string = function(dependencies_object){ 
    var final_string = ""; 
    Object.keys(dependencies_object).map(function(dependency){ 
     var location = require.resolve(dependency); 
     var export_dependency = 'module.exports = global["'+toCamelCase(dependency)+'"] = require("-!'+ location+'");'; 
     final_string += export_dependency; 
    }) 
    return final_string; 
}; 

module.exports = function() {}; 
module.exports.pitch = function(e){ 
    if(this.cacheable) {this.cacheable();} 
    var dependencies = require(e).dependencies; 
    return returning_string(dependencies); 
}; 

的問題是,即使輸出是完全一樣的一些原因,那麼在使用時暴露裝載它的工作庫添加到全球範圍內。在做這兩件事情時,我手動添加了依賴項以提供插件,我將稍後需要以某種方式進行復制。

有沒有更好的方法來做到這一點?或者我做對了,但我失去了一些東西?

+0

您是否找到解決方案?我有着同樣的問題。你最終使用不同的打包機? – user1828780

回答

0

研究後,我發現了following中的WebPack 2.x的(我用的WebPack 1.x的,但我想的是哲學史的有效期爲我的版本)有關配置文件說:

寫和執行函數來生成配置的一部分

所以我對這個問題的方法是不使用新的插件,但重用應該工作的。基本上我寫了一個新的JavaScript文件,以webpack.config的方式創建我需要的所有加載器。

這是文件:

dependencies_loader.js https://gist.github.com/abenitoc/b4bdc02d3c7cf287de2c92793d0a0b43

這是aproximately我叫它方式:

var webpack = require('webpack'); 
var dependency_loader = require('./webpack_plugins/dependencies_loader.js'); 


module.exports = { 
    devtool: 'source-map', 
    entry: {/* Preloading */ }, 
    module: {preLoaders: [/*Preloading*/], 
    loaders: [/* Call all the loaders */].concat(dependency_loader.getExposeString()), 
    plugins: [ 
    new webpack.ContextReplacementPlugin(/package\.json$/, "./plugins/"), 
    new webpack.HotModuleReplacementPlugin(), 
    new webpack.ProvidePlugin(Object.assign({ 
     '$': 'jquery', 
     'jQuery': 'jquery', 
     'window.jQuery': 'jquery' 
    }, dependency_loader.getPluginProvider())), // Wraps module with variable and injects wherever it's needed 
    new ZipBundlePlugin() // Compile automatically zips 
] 

請注意,我Concat的裝載機的陣列加入以下需要的getExposeString()加載器,並使用getPluginProvider將對象與pluginProvider中的新全局元素重新分配。 也因爲我使用jsHint我排除全局名稱,這是爲什麼其他方法。

這隻能解決node_modules依賴關係,如果您需要本地庫,則有不同的方法。

相關問題