2017-06-21 43 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

希望它有幫助。