Dynamic import in different folder

帅比萌擦擦* 提交于 2019-12-13 03:56:35

问题


I have some trouble to import dynamicaly a class.

I use alias for this projet :

config.resolve.alias = {
    App: path.resolve('./src/'),
    Reactive: path.resolve('./app/')
}

I want to import a list of class :

const classes = {
    foo: 'App/Foo',
    bar: 'App/Bar'
};
let list = {};
for(var c in classes) {
    (async (k, v, list) => {
        const m = await import(`${v}`);
        list[k] = new m.default();
    })(c, classes[c], list);
}

This script is called in app, and all imported classes in src.

The error is simple : Cannot find module 'App/Foo'.

When I check the last entry of error's log :

var map = {
    "./OtherClass1": [
        "./app/OtherClass1.js"
    ],
    "./OtherClass1.js": [
        "./app/OtherClass1.js"
    ],
    "./OtherClass2": [
        "./app/OtherClass2.js"
    ],
    "./OtherClass2.js": [
        "./app/OtherClass2.js"
    ]
};
function webpackAsyncContext(req) {
    var ids = map[req];
    if(!ids)
        return Promise.reject(new Error("Cannot find module '" + req + "'."));
    return Promise.all(ids.slice(1).map(__webpack_require__.e)).then(function() {
        return __webpack_require__(ids[0]);
    });
};
webpackAsyncContext.keys = function webpackAsyncContextKeys() {
    return Object.keys(map);
};
webpackAsyncContext.id = "./app lazy recursive ^.*$";
module.exports = webpackAsyncContext;

So, the error is legit, because the map does not contain Foo and Bar classes in src, only those in app.

How can I specify to Webpack to check in both folders, recursively?

But, when I test this, it's work fine :

for(var c in classes) {
    (async (k, v, list) => {
        const m = await import(`${"App/Foo"}`);
        list[k] = new m.default();
    })(c, classes[c], list);
}

回答1:


use react import to import your file and use file.classname to call them

eg import claases from '/src';

and use it link

app = classes.myfile



来源:https://stackoverflow.com/questions/51500557/dynamic-import-in-different-folder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!