【问题标题】:String confusion in Javascript with regard to dynamically loading a pathJavascript中关于动态加载路径的字符串混淆
【发布时间】:2020-05-31 03:15:40
【问题描述】:

我在 Javascript 中遇到了一些非常奇怪的东西,我无法解释。简而言之,我在 React 中构建了一个动态 Button 组件,其中可以选择传入图标文件的路径。

这种方法效果很好:

const image = require('../styling/assets/images/search-icon.svg');

<button className='button' onClick={props.handleButtonClick}>
  <img className='button-icon' src={image} />
  <p>{props.label}</p>
</button>

但是如果我把第一行改成这两行就会失败:

const path = '../styling/assets/images/search-icon.svg';
const image = require(path);

在第二种情况下,我收到此错误:Error: Cannot find module '../styling/assets/images/search-icon.svg'

从根本上说,这两种方法对我来说似乎是等价的,但显然不是。

为什么第二种方法会失败?

【问题讨论】:

    标签: javascript dynamic-import


    【解决方案1】:

    根据互联网:“要求在打包期间解决,而不是在运行时解决”。

    https://github.com/facebook/react-native/issues/6391

    【讨论】:

      【解决方案2】:

      根据 MDN 文档:

      import 语句不能在嵌入脚本中使用,除非这样 脚本有一个 type="module"。导入的绑定称为实时绑定 因为它们是由导出绑定的模块更新的。

      更多信息在这里https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-07-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多