2017-06-21 24 views
0

当我传递一个字符串文件加载需要计算性能的方法,它工作正常,像这样Vuejs:找不到模块“。”

computedProp() { 
    return require('../path/to/file'); 
} 

,但如果我尝试一些变量传递到它,它会抛出错误

computedProp() { 
    const l = '../path/to/file'; 
    return require(l); 
} 

错误:Error: Cannot find module "."

我该如何解决这个问题?我想创建基于某些条件的相对路径,然后想要将它传递给需要获取绝对路径的方法。

回答

1

非常相似的答案已经张贴在堆栈:

Since Webpack is running in build-time, it can't figure out which modules to bundle when the name is a dynamic variable. You can give it hints by specifying part of the path (for example, if you know all the modules are in a single directory).

Using require('...') with a variable vs. using a string in webpack

所以,对于工作,你可以测试:

computedProp() { 
    const path = '../path/to' 
    const file = 'file'; 
    return require(path + '/' + file); 
} 

更多信息HereHere

希望它有帮助。