Node.js 从使用module.exports的文件导入网页包
我有React应用程序和一个文件,我想在其中存储与api相关的内容Node.js 从使用module.exports的文件导入网页包,node.js,reactjs,webpack,ecmascript-6,commonjs,Node.js,Reactjs,Webpack,Ecmascript 6,Commonjs,我有React应用程序和一个文件,我想在其中存储与api相关的内容 const proxy = require('http-proxy-middleware'); const path = require('path'); //..... const targetApi = (objectWithUrlEntries) => { Object.keys(objectWithUrlEntries).forEach((key) => { objectWithUrlEntr
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本身使用,一些将在应用程序内部使用(以正确地针对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
导出失败,但如果我使用es6export
语法,Node
就会失败。我遇到了一个类似的问题:我有一个javascript类,其中包含一些我想在Node JS和客户端代码中使用的验证规则。对我有效的是converting将所有内容添加到Common JS、共享代码、节点代码和客户端代码。但我仍然存在一些问题。然后我将“模块”:“commonjs”
添加到导入共享代码的文件夹的my.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选项,查看必须在不同模块系统中公开库的选项。然后在节点和客户端代码中导入共享库