2017-03-09 58 views
1

我有一個反應項目,我正在使用webpack。我在frontend/app/components/editor/index.js中有一個組件,我想將其包含在另一個組件中。目前爲了引用這個組件,我不得不使用相對路徑(../../../../app/components/editor)。但是,這非常不易使用,並且希望簡單地使用「組件/編輯器」。我的Webpack配置文件位於/ webpack.config.js前端。解決與Webpack不起作用的React中的相對路徑

我已經添加了一個解決方案設置(Resolving require paths with webpack),但它仍然無法正常工作。

const {resolve} = require('path'); 
const path = require('path'); 
const webpack = require('webpack'); 
const validate = require('webpack-validator'); 
const {getIfUtils, removeEmpty} = require('webpack-config-utils'); 

module.exports = env => { 
    const {ifProd, ifNotProd} = getIfUtils(env) 

    return validate({ 
    entry: './index.js', 
    context: __dirname, 
    output: { 
     path: resolve(__dirname, './build'), 
     filename: 'bundle.js', 
     publicPath: '/build/', 
     pathinfo: ifNotProd(), 
    }, 
    devtool: ifProd('source-map', 'eval'), 
    devServer: { 
     port: 8080, 
     historyApiFallback: true 
    }, 
    module: { 
     loaders: [ 
     {test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader'}, 
     {test: /\.css$/, loader: 'style-loader!css-loader'}, 
     {test: /(\.eot|\.woff2|\.woff|\.ttf|\.svg)/, loader: 'file-loader'}, 
     ], 
    }, 
    resolve: {  
     root: path.resolve('./app'), 
    }, 
    plugins: removeEmpty([ 
     ifProd(new webpack.optimize.DedupePlugin()), 
     ifProd(new webpack.LoaderOptionsPlugin({ 
     minimize: true, 
     debug: false, 
     quiet: true, 
     })), 
     ifProd(new webpack.DefinePlugin({ 
     'process.env': { 
      NODE_ENV: '"production"', 
     }, 
     })), 
     ifProd(new webpack.optimize.UglifyJsPlugin({ 
     sourceMap: true, 
     compress: { 
      screw_ie8: true, // eslint-disable-line 
      warnings: false, 
     }, 
     })), 
    ]) 
    }); 
}; 

這些都是我在解析塊中試過的所有設置,但沒有任何效果。

resolve: {  
    alias: { 
    shared: path.resolve(__dirname, 'app') 
}, 

resolve: {  
    root: path.resolve('./app') 
}, 

resolve: {  
    modules: ['app'] 
}, 

resolve: {  
    modulesDirectories: ['app'] 
}, 

回答

1

其實,它必須是

model.exports = env => { 
    ..., 
    resolve: { 
     modules: ['app', 'node_modules'] 
    }, 
    ... 
} 

所以modulesresolve對象本身是全局配置對象的屬性的屬性。此外,我還包括node_modules,因爲在覆蓋默認設置(僅爲[ 'node_modules' ])後,您可能也想引用這些設置。 See docs瞭解更多信息。

更新基於評論

您是從webpack-validator,這是不是要去,因爲內置的WebPack驗證的保持收到一個錯誤。詳見SO answerwebpack-validator npm。所以錯誤[1] "modules" is not allowed是不正確的。要修復它,你需要刪除/卸載webpack-validator

+0

是的,我嘗試瞭解決方案對象(只是沒有澄清,在我的問題),但是當我使用模塊webpack拋出這個錯誤:[1]「模塊」是不允許的。 – dpst

+0

@dpst我已經更新了我的答案。這個錯誤是因爲'webpack-validator'實際上不再被維護,並且webpack2創建了沒有被更新以適應的重大更改。 –