我经常发现自己想做这样的事情:
import React from 'react'
const helperFunction = () => "Hello world"
const MyComponent = () => {
render () {
return (
<h3> {helperFunction()} </h3>
)
}
}
export default MyComponent
当webpack捆绑所有文件时,此功能定义是否可用于其他文件?
有更好的方法吗?
答案 0 :(得分:1)
此功能定义是否可用于其他文件?
不,此功能只能从此文件访问,因为您没有导出它。只有在默认情况下导出该功能或命名导出时,它才可用。
像这样:
export helperFunction
export default MyComponent
答案 1 :(得分:0)
如果你使用像browserify这样的东西,那么你可以导出你的功能并在导入它的任何地方使用它。
我通常在我的react项目中为我的实用程序函数创建一个文件。它看起来像
export let foo=()=>{...}
然后在我的文件中我只是做
import foo from ‘.utility.js’
答案 2 :(得分:0)
此功能定义是否可用于其他文件?
不可用于其他文件。 Webpack仅在您export
时才可用。
如果要在多个文件中使用相同的功能,则需要创建一个新文件utils.js
或helpers.js
并将此功能放入其中:
export const helperFunction = () => "Hello world"
然后,如果你想在某个文件中使用这个功能,只需导入它:
import {helperFunction} from 'utils';