2017-10-16 112 views
0

我有React应用程序和一个文件,我想存储与api相关的东西。从使用module.exports的文件导入Webpack

const proxy = require('http-proxy-middleware'); 
const path = require('path'); 

//..... 

const targetApi = (objectWithUrlEntries) => { 
    Object.keys(objectWithUrlEntries).forEach((key) => { 
    objectWithUrlEntries[key] = path.join('/api/', objectWithUrlEntries[key]); 
    }); 
}; 

module.exports.proxyExpressCalls = proxyExpressCalls; 
module.exports.devServerProxyConfig = devServerProxyConfig; 
module.exports.targetApi = targetApi; 

这些东西中的一部分将被webpack本身使用,其中一些将被用于app内部(正确地定位api调用)。

然而,当我试图导入我的应用程序的东西:

// @flow 
import { buildUrl } from 'data/utils'; 
import type { Axios } from './flow.types'; 
import { targetApi } from './api'; 

console.log(targetApi()); 

我得到的错误。在终端:

警告在./src/data/redux/api/user.js 6:12-21“出口 'targetApi' 未在 './api'

发现在浏览器:

api.js?d669:39 Uncaught TypeError: Cannot set property 'proxyExpressCalls' of undefined 
    at Object.eval (api.js?d669:39) 
    at eval (api.js:60) 
    at Object../src/data/redux/api/api.js (client.bundle.js:11620) 
    at __webpack_require__ (client.bundle.js:708) 
    at fn (client.bundle.js:113) 
    at eval (user.js:15) 
    at Object../src/data/redux/api/user.js (client.bundle.js:11668) 
    at __webpack_require__ (client.bundle.js:708) 
    at fn (client.bundle.js:113) 
    at eval (user.js:18) 

所以问题是,应用程序被捆绑时commonjs出口失败,但如果我会用ES6 export语法然后Node会失败

回答

1

我有一个类似的问题:我有一个JavaScript类,有一些验证规则,我想在Node JS和客户端代码中使用。对我而言,所有工作都转换为Common JS,共享代码,节点代码和客户端代码。但我仍然有一些问题。然后,我将"module": "commonjs"添加到导入共享代码的文件夹的我的.babelrc文件中,并最终生效。这是我的.babelrc文件:(!未测试)

{ 
    "presets": [ 
     "react", 
     [ 
      "env", 
      { 
       "debug": true, 
       "modules": "commonjs", 
       "targets": { 
        "browsers": [ 
         "last 2 versions", 
         "safari >= 7" 
        ], 
       } 
      } 
     ], 
    ], 
    "plugins": [ 
     "transform-object-rest-spread", 
     "transform-es2015-arrow-functions", 
     "transform-class-properties" 
    ] 
} 

另一种可能的解决方案是创建一个库出你的共享代码,使用的WebPack。检查output.library和output.libraryTarget选项以查看您必须在不同模块系统中公开库的选项。然后在节点和客户端代码中导入共享库。