Browserify 需要具有动态路径的文件失败,但在使用硬编码路径时有效
Browserify require file with dynamic path fails, but works when using hard-coded path
我正在开始使用 Browserify,我正在尝试根据名为 components.coffee
的配置文件请求一组文件。我将 React 与 CoffeeScript 一起使用,但我怀疑它与问题本身有关。
index.cjsx
path = require 'path'
componentList = require '../commons/components'
components = componentList.map (component) ->
console.log path.relative(__dirname, component)
console.log '../commons/button/button.doc.js'
console.log '../commons/button/button.doc.js' is path.relative(__dirname, component)
console.log require(path.relative(__dirname, component))
console.log require '../commons/button/button.doc.js'
require(path.relative(__dirname, component))
commons/components.咖啡
module.exports = [
"../commons/button/button.doc.js"
]
输出:
删除行console.log require '../commons/button/button.doc.js'
时的输出:
如果我不需要使用硬编码路径的文件,它将失败。我不解释为什么,因为硬编码路径和动态路径是相等的。
我猜这与 Browserify 有关,可能是缓存问题,当通过硬编码字符串需要模块时已解决。但是我真的一点头绪都没有。
同时我将使用一种解决方法,但我想了解这里发生了什么! :)
我的解决方案是改变我的设计。它不再是 components.coffee
返回一个字符串数组,而是 returns 一个加载文件数组。
commons/components.咖啡
module.exports = [
require "../commons/button/button.doc.js"
]
然后,在我的 index.cjsx 中,我只是加载它:
components = require '../commons/components'
我正在开始使用 Browserify,我正在尝试根据名为 components.coffee
的配置文件请求一组文件。我将 React 与 CoffeeScript 一起使用,但我怀疑它与问题本身有关。
index.cjsx
path = require 'path'
componentList = require '../commons/components'
components = componentList.map (component) ->
console.log path.relative(__dirname, component)
console.log '../commons/button/button.doc.js'
console.log '../commons/button/button.doc.js' is path.relative(__dirname, component)
console.log require(path.relative(__dirname, component))
console.log require '../commons/button/button.doc.js'
require(path.relative(__dirname, component))
commons/components.咖啡
module.exports = [
"../commons/button/button.doc.js"
]
输出:
删除行console.log require '../commons/button/button.doc.js'
时的输出:
如果我不需要使用硬编码路径的文件,它将失败。我不解释为什么,因为硬编码路径和动态路径是相等的。
我猜这与 Browserify 有关,可能是缓存问题,当通过硬编码字符串需要模块时已解决。但是我真的一点头绪都没有。
同时我将使用一种解决方法,但我想了解这里发生了什么! :)
我的解决方案是改变我的设计。它不再是 components.coffee
返回一个字符串数组,而是 returns 一个加载文件数组。
commons/components.咖啡
module.exports = [
require "../commons/button/button.doc.js"
]
然后,在我的 index.cjsx 中,我只是加载它:
components = require '../commons/components'