【问题标题】:Webpack import from files that use module.exports从使用 module.exports 的文件导入 Webpack
【发布时间】:2018-03-27 18:51:09
【问题描述】:

我有 React 应用程序和一个文件,我想在其中存储与 api 相关的内容。

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 "export '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 将失败。

【问题讨论】:

    标签: node.js reactjs webpack ecmascript-6 commonjs


    【解决方案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 选项以查看您必须在不同模块系统中公开库的选项。然后在您的节点和客户端代码中导入您的共享库。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-26
      • 2021-09-28
      • 2021-08-23
      • 2019-05-22
      • 2020-06-28
      • 2021-05-19
      • 2017-10-28
      • 2016-12-25
      相关资源
      最近更新 更多