如何从我的 webpack 2 配置创建/生成/导出文件以在我的 React 代码中使用? [英] How to create/generate/export a file from my webpack 2 config to be used inside of my React code?

查看:29
本文介绍了如何从我的 webpack 2 配置创建/生成/导出文件以在我的 React 代码中使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 NODE_ENV 变量从 package.json 传入我的 webpack.config 以返回一个包含 API 端点的对象用于本地主机或生产.

I am passing in NODE_ENV variables into my webpack.config from package.json in order to return an object that either contains API endpoints for localhost or production.

"scripts": {
    "dev": "NODE_ENV=development webpack-dev-server --history-api-fallback",
    "prod": "NODE_ENV=production webpack -p",
    "build": "NODE_ENV=production webpack -p"
}

2) endpoints.js

function endpoints(env) {
    let prefix = env === 'development' ? 'http://localhost' : '';

    return {
        "login": `${prefix}/app/api/login`
    }
}

module.exports = endpoints;

3) webpack.config

const webpack = require('webpack')
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const path = require("path");
const dist = path.resolve(__dirname, "dist");
const src = path.resolve(__dirname, "src");
const endpoints = require("./src/endpoints");
const api = endpoints(process.env.NODE_ENV);

console.log('webpack api', api);

module.exports = {
  context: src,
  entry: [
    "./index.js"
  ],
  output: {
    path: dist,
    // ....


在下面我可以看到const apiconsole.log.

现在我的问题是,我现在如何生成或导出实际文件 api 以在我的 src/services/api 文件中使用:

Now my question is, how do I now generate or export out an actual file api to be used inside of my src/services/api file:

import axios from 'axios'
// import api from '../../webpack.config' <-- ?
// import api from '../../api.js <-- ?

const log = (method, err) => {
    console.error(`%c${method}`, 'background: #393939; color: #F25A43', err);
    return null;
};

export const userLogin = (username, password) => {
    const post_data = { username, password };
    return axios.post('http://localhost/app/api/login', post_data)  // <-- api to be used here
        .then(res => res)
        .catch((err) => log('api.userLogin', err));
};

推荐答案

我认为这是一个XY 问题.您可以使用一些 Node 生成文件(类似于 fs.writeFileSync('api.js', contents),或者您可以使用一些 shell 脚本来完成,但您也可以只在您的代码中使用 env 使用 DefinePlugin(示例:new webpack.DefinePlugin({ env: JSON.stringify(process.env.NODE_ENV) }).然后你就可以直接在你的代码中访问env.

I think this is an XY problem. You could generate the files with a bit of Node (something like fs.writeFileSync('api.js', contents), or you could do it with a bit of shell scripting, but you could also just use env in your code using DefinePlugin (example: new webpack.DefinePlugin({ env: JSON.stringify(process.env.NODE_ENV) }). Then you'd be able to access env in your code directly.

这篇关于如何从我的 webpack 2 配置创建/生成/导出文件以在我的 React 代码中使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆