【问题标题】:Including NPM module in React file: Webpack can't resolve在 React 文件中包含 NPM 模块:Webpack 无法解析
【发布时间】:2017-04-05 12:03:13
【问题描述】:

根据我汇总阅读herehere 的内容,将react 模块发布到NPM,然后在组件本身位于node_modules 导向器中时在另一个项目中使用它的方式应该看起来像这个

  1. 编写一个模块,然后导出它
  2. 用脚本的名称填写package.jsonmain 属性,在我的例子中是dist/index.js
  3. npm install它来自您想要包含它的项目
  4. 从服务器静态提供脚本。
    • 我有一些看起来像这样的东西来提供 js 文件: app.use('public/componentA', express.static(path.join('node_modules', 'componentA'));
    • 这不是完全真实的代码,但它可以工作,如果我加载它,我可以在浏览器中看到 JS。
  5. 需要组件

index.js

var React = require('react');
var Component = require('../public/componentA/');
var hook = document.getElementById('hook');
React.render(Component, hook);

但是,当我尝试 webpack 时,我得到了错误

./lib/index.js 中的错误 未找到模块:错误:无法解析 /Users/me/Documents/tests/reactcomponenttest/lib 中的目录“./public/componentA”

是什么阻止我使用我的模块?我假设public 目录在除特定端口之外的任何地方都不可用。如果是这种情况,我们如何使用我的第二个链接中的节点 use 建议?

【问题讨论】:

标签: javascript node.js reactjs npm webpack


【解决方案1】:

你必须通过它的名字来 require 模块。如果您发布了名为 componentA 的模块,请编写如下内容: var Component = require('componentA');

步骤 4. 根本不需要。 Webpack 将所有 JavaScript 文件捆绑到一个文件中。所以如果你require(‘componentA')它基本上会将componentA的dist/index.js的内容复制到最终的bundle.js中。

最后,您只需发送 bundle.js 即可。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-10
    • 2016-12-18
    • 2021-07-21
    • 2020-12-19
    • 2016-03-25
    • 1970-01-01
    • 1970-01-01
    • 2016-11-04
    相关资源
    最近更新 更多