使用Webpack解决React中的相对路径无法正常工作

时间:2017-03-09 17:28:21

标签: reactjs webpack

我有一个反应项目,我正在使用webpack。我在frontend / app / components / editor / index.js中有一个组件,我希望将其包含在另一个组件中。目前为了引用该组件,我必须使用相对路径(../../../../app/components/editor)。但是,这非常不容易使用,并且只想使用&组件/编辑器'例如。我的Webpack配置文件位于fronted / webpack.config.js。

我已在此帖子中添加了解析设置(Resolving require paths with webpack),但它仍无效。

distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-3.4.1-all.zip

这些是我在解决方案块中尝试过的所有设置,但没有任何效果。

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,
        },
      })),
    ])
  });
};

1 个答案:

答案 0 :(得分: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