在客户端 React 组件中导入 npm 模块

stu*_*oid 5 meteor ecmascript-6 reactjs

在 Meteor 中,如果我在 react 组件中像这样从 npm 导入 lodash,并且在以下位置的 console.log “lodash” 中,它将始终在组件中显示为未定义。同样的事情也发生在瞬间。我不知所措,因为根据文档的说法,我认为这是可能的。这是可能的,如果是的话,我在这里遗漏了什么吗?任何帮助深表感谢。

import React from 'react'
import lodash from 'lodash'

console.log(lodash) // lodash is found just fine

export default class SomeComponent extends React.Component {
    constructor(props) {
        super(props)
        this.someFunction = this.someFunction.bind(this)
    }
    someFunction() {
        console.log(lodash) // Throws error that lodash is undefined.
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 2

我将你的组件放入流星示例中,并且运行良好。

例如

git clone https://github.com/meteor/simple-todos-react
cd simple-todos-react
npm i
npm i --save lodash
meteor
Run Code Online (Sandbox Code Playgroud)

然后将以下内容添加/imports/ui/App.jsx到此差异中:

 import { Tasks } from '../api/tasks.js';                        
 import Task from './Task.jsx';                                                  
 import AccountsUIWrapper from './AccountsUIWrapper.jsx';                        

+import lodash from 'lodash'                                                     
+console.log(lodash) // lodash is found just fine                                
+                                                                                
+export default class SomeComponent extends React.Component {                    
+    constructor(props) {                                                        
+        super(props)                                                            
+        this.someFunction = this.someFunction.bind(this)                        
+    }                                                                           
+    someFunction() {                                                            
+        console.log(lodash) // Throws error that lodash is undefined.      
+    }                                                                           
+    render() {                                                                  
+      this.someFunction()                                                       
+      return (                                                                  
+        <h2>SomeComponent</h2>                                                  
+      )                                                                         
+    }                                                                           
+}                                                                               

....

class App extends Component {
....
   render() {
     return (
       <div className="container">
         <header>
+          <SomeComponent />
           <h1>Todo List ({this.props.incompleteCount})</h1>

....
Run Code Online (Sandbox Code Playgroud)

在浏览器中打开站点,然后检查控制台日志:

控制台日志