How to create/generate/export a file from my webpack 2 config to be used inside of my React code?

╄→гoц情女王★ 提交于 2019-12-11 05:44:44

问题


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.

1) package.json

"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,
    // ....

Here below I can see the console.log of the const 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));
};

回答1:


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.



来源:https://stackoverflow.com/questions/44371162/how-to-create-generate-export-a-file-from-my-webpack-2-config-to-be-used-inside

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!