2017-03-09 164 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创建了没有被更新以适应的重大更改。 –