我有这个代码
import('./myfile.js')
.then(m=>console.log(m.default))
.catch(err=>console.error(err))
webpack 捆绑“myfile.js”,但我想将此文件复制到“dist”并动态导入它,即我想避免编译此
import()
语句。
请注意,此代码是函数的一部分,文件“myfile.js”由函数参数提供,因此我无法将路径添加到 webpack 的外部数组。
我尝试了以下方法:
/* webpackIgnore: true, webpackMode: "lazy" */
let file = 'myfile.js'
import('./' + file)
let getPath = path=>path
import(getPath('./myfile.js'))
function load(path){
return import('./' + path)
}
load('myfile.js')
将
import()
调用放入评估的字符串中是最通用的解决方案:
const dynamicImport = new Function('url', 'return import(url)')
dynamicImport('./myfile.js')
.then(m=>console.log(m.default))
.catch(err=>console.error(err))
缺点是它需要
'unsafe-eval'
CSP 规则才能允许 script-src
。