首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >React:从外部文件读取配置

React:从外部文件读取配置
EN

Stack Overflow用户
提问于 2019-08-29 14:20:51
回答 4查看 4.1K关注 0票数 4

我试图实现一个从我的react应用程序中的某个文件中读取配置的解决方案.不知道什么是最佳实践,但我调整了以下方法并尝试实现它:

1)在我的应用程序根目录下(与webpack.config.js并行),我创建了一个名为: config.dev.json的文件,内容如下:

{“协议”:"http",“主机”:"localhost","port“:"8080”}

2) webpack.config.js添加了我的代码(TODO部分在末尾):

代码语言:javascript
复制
 const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const rtlcss = require('rtlcss');
const webpack = require("webpack");

const useExternalCss =
  process.env.CARBON_REACT_STORYBOOK_USE_EXTERNAL_CSS === 'true';

const useStyleSourceMap =
  process.env.CARBON_REACT_STORYBOOK_USE_STYLE_SOURCEMAP === 'true';

const useRtl = process.env.CARBON_REACT_STORYBOOK_USE_RTL === 'true';

const styleLoaders = [
  {
    loader: 'css-loader',
    options: {
      importLoaders: 2,
      sourceMap: useStyleSourceMap,
    },
  },
  {
    loader: 'postcss-loader',
    options: {
      plugins: () => {
        const autoPrefixer = require('autoprefixer')({
          browsers: ['last 1 version', 'ie >= 11'],
        });
        return !useRtl ? [autoPrefixer] : [autoPrefixer, rtlcss];
      },
      sourceMap: useStyleSourceMap,
    },
  },
  {
    loader: 'sass-loader',
    options: {
      includePaths: [path.resolve(__dirname, '..', 'node_modules')],
      data: `
        $feature-flags: (
          ui-shell: true,
        );
      `,
      sourceMap: useStyleSourceMap,
    },
  },
];

module.exports = (baseConfig, env, defaultConfig) => {
  defaultConfig.devtool = useStyleSourceMap ? 'source-map' : '';
  defaultConfig.optimization = {
    ...defaultConfig.optimization,
    minimizer: [
      new TerserPlugin({
        sourceMap: true,
        terserOptions: {
          mangle: false,
        },
      }),
    ],
  };

  defaultConfig.module.rules.push({
    test: /-story\.jsx?$/,
    loaders: [
      {
        loader: require.resolve('@storybook/addon-storysource/loader'),
        options: {
          prettierConfig: {
            parser: 'babylon',
            printWidth: 80,
            tabWidth: 2,
            bracketSpacing: true,
            trailingComma: 'es5',
            singleQuote: true,
          },
        },
      },
    ],
    enforce: 'pre',
  });

  defaultConfig.module.rules.push({
    test: /\.scss$/,
    sideEffects: true,
    use: [
      { loader: useExternalCss ? MiniCssExtractPlugin.loader : 'style-loader' },
      ...styleLoaders,
    ],
  });

  if (useExternalCss) {
    defaultConfig.plugins.push(
      new MiniCssExtractPlugin({
        filename: '[name].[contenthash].css',
      })
    );
  }

  //TODO
  if (!defaultConfig.resolve) {
    defaultConfig.resolve = {};
  }
  if (!defaultConfig.resolve.alias) {
    defaultConfig.resolve.alias = {};
  }
  defaultConfig.resolve.alias.Config = process.env.NODE_ENV === 'production'
      ? path.resolve('./config.prod.json')
      : path.resolve('./config.dev.json');


  return defaultConfig;
};

module.exports = {
  plugins: [
    new webpack.DefinePlugin({
      'process.env': {
        'NODE_ENV': JSON.stringify('development'),
        'BASE_URL': JSON.stringify('http://localhost:3000/')
      }
    })
  ],

//   externals: {
//     'Config': JSON.stringify(process.env.NODE_ENV === 'production' ? require('./config.prod.json') : require('./config.dev.json'))
//   }
//
//   // externals: {
//   //   'Config': JSON.stringify(process.env.NODE_ENV === 'production' ? {
//   //     serverUrl: "http://test.com:8080"
//   //   } : {
//   //     serverUrl: "http://localhost:8080"
//   //   })
//   // }
//

}

( 3)并试图以这种方式从某些组件中使用它:

代码语言:javascript
复制
let Config = require('Config')

但我得到了:

./src/store/RestService.js模块未找到:无法解析C中的“Config”:

EN

回答 4

Stack Overflow用户

发布于 2019-08-29 15:35:37

如果您想在没有webpack的情况下设置配置(例如,在使用create app时),我建议如下:

创建配置文件夹(或任意命名),并添加配置文件和索引文件:

  • config.dev.json
  • config.prod.json
  • index.js

然后在config/index.js文件中:

代码语言:javascript
复制
if (process.env.NODE_ENV === 'development') {
    module.exports = require('./config.dev.json')
} else {
    module.exports = require('./config.prod.json')
}

import config from './config';一起使用

票数 4
EN

Stack Overflow用户

发布于 2019-08-29 14:34:44

为什么不这样用呢?

  1. 在你的package.json
代码语言:javascript
复制
"scripts": {
    "develop": "PORT=8080 HOST=localhost PROTOCOL=http node ."
    "production": "Your config here"
}
  1. 创建config/app.js
代码语言:javascript
复制
    const config = process.env
    module.export = {
         port: config.PORT,
         protocol: config.PROTOCOL,
         host: config.HOST,
    }
  1. 在你的webpack (实际上,我不知道你为什么要导入配置在你的webpack和再导出它。如果您希望jsx或js文件能够读取端口、主机和本地主机,您只需遵循步骤2,就可以在任何app.js文件中自由获取配置文件)
代码语言:javascript
复制
const config = require('./path/to/config/app.js')

module.exports = {
     externals: {
          config: config,
     }
}
票数 1
EN

Stack Overflow用户

发布于 2019-08-29 14:42:07

首先,您需要包中的配置文件,它不是外部文件(因此我们只需要删除外部部分)。

然后,您需要根据环境将配置文件解析为一个不同的文件(prod或dev,使用resolve.alias)。

也要小心工作目录,要么从项目的文件夹中运行webpack,要么使用上下文配置选项。

webpack建议配置(最后相关部分):

代码语言:javascript
复制
module.exports = (baseConfig, env, defaultConfig) => {
  defaultConfig.devtool = useStyleSourceMap ? 'source-map' : '';
  defaultConfig.optimization = {
    ...defaultConfig.optimization,
    minimizer: [
      new TerserPlugin({
        sourceMap: true,
        terserOptions: {
          mangle: false,
        },
      }),
    ],
  };

  defaultConfig.module.rules.push({
    test: /-story\.jsx?$/,
    loaders: [
      {
        loader: require.resolve('@storybook/addon-storysource/loader'),
        options: {
          prettierConfig: {
            parser: 'babylon',
            printWidth: 80,
            tabWidth: 2,
            bracketSpacing: true,
            trailingComma: 'es5',
            singleQuote: true,
          },
        },
      },
    ],
    enforce: 'pre',
  });

  defaultConfig.module.rules.push({
    test: /\.scss$/,
    sideEffects: true,
    use: [
      { loader: useExternalCss ? MiniCssExtractPlugin.loader : 'style-loader' },
      ...styleLoaders,
    ],
  });

  defaultConfig.module.rules.push({
    test: /\.json$/,
    use: [
      { loader: useExternalCss ? MiniCssExtractPlugin.loader : 'style-loader' },
      ...styleLoaders,
    ],
  });


  if (useExternalCss) {
    defaultConfig.plugins.push(
      new MiniCssExtractPlugin({
        filename: '[name].[contenthash].css',
      })
    );
  }
  // ensure resolve alias present in the config
  if (!defaultConfig.resolve) {
      defaultConfig.resolve = {};
  }
  if (!defaultConfig.resolve.alias) {
      defaultConfig.resolve.alias = {};
  }
  // resolve the alias to the right config file according to NODE_ENV
  // you'll have to correctly set <relative path to your config>
  defaultConfig.resolve.alias.Config = process.env.NODE_ENV === 'production'
      ? path.resolve(__dirname, '<relative path to your config>/config.prod.json')
      : path.resolve(__dirname, '<relative path to your config>/config.dev.json');


  return defaultConfig;
};

别忘了移除这个:

代码语言:javascript
复制
module.exports = {
  externals: {
    'Config': JSON.stringify(process.env.NODE_ENV === 'production' ? require('./config.prod.json') : require('./config.dev.json'))
  }

  // externals: {
  //   'Config': JSON.stringify(process.env.NODE_ENV === 'production' ? {
  //     serverUrl: "http://test.test.com:8080"
  //   } : {
  //     serverUrl: "http://localhost:8080"
  //   })
  // }

}

因为这将阻止webpack将文件捆绑起来。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57712237

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档