-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Error: Cannot find module with dynamic import #6680
Comments
What is the version of webpack used here? |
It's written in the description 😄 |
It's incomprehensible 😢 If i write this it work import( '/Users/hubert_i/Emodyz/launcher-ezgames.eu/modules/test/index.js')
.then((m) => {
console.log(m.name)
})
.catch(err => {
console.error('Error during loading module: ' + err)
callback()
}) but when i write this don't work const test = '/Users/hubert_i/Emodyz/launcher-ezgames.eu/modules/test/index.js'
import(test)
.then((m) => {
console.log(m.name)
})
.catch(err => {
console.error('Error during loading module: ' + err)
callback()
}) |
Webpack performs a static analyse at build time. It doesn't try to infer variables which that If you need truly dynamic imports, you have to restrict it to a known path: import("./locales/" + locale + ".js") In the above example, webpack will create a chunk for each JS file in |
I would like to load module located in %appdata% in windows or Application Support on macOS how i can do that ? |
@MrDarkSkil I needed to do something similar. Please explain how you solved it. I want to read some configs present in application.conf in individual boxes. |
Would this also work for loading a remote module (over http(s)). I currently am trying to load modules located on a remove server (owned by me). When I import them locally it works fine:
However when I try to import over http it fails (no request reaches the backend at all):
Error: Unhandled Rejection (Error): Cannot find module 'http://localhost:3001/api/uicomponents/one/[name].js'. |
Also noteworthy, The behavior is different for named and default exports , which isnt only limited to webpack. You can export as both using ‘export { mymodule as default, mymodule}’ |
what @mattb290 said would be a useful addition now that modules are natively supported in browsers with <script type="module"> and people are going to release/load them all over the internet any progress? |
This isn't dynamic import if we can load dynamically files depending on our variables otherwise why would I even use this I could just import all the files at the top!! Seriously @ooflorent ? |
@meteorplus you can import files dynamically. You only need a static prefix.
Because it will reduce the main bundle size. |
@ooflorent, what if I don't want to reduce bundle size, but load another webpack packed bundle with all dependencies (even with duplicate dependencies) from absolute path? |
Just in case this helps somebody else who finds this issue, I got the behavior I wanted by adding a rule to my Webpack config to load the files I wanted with
then getting a reference to the output path and dynamically importing it with native
This means that all the files matching |
I have the following code : function parse (fileName, callback) {
var path = "./relative/path/to/" + fileName + ".json";
var cb = process.bind(this, fileName, callback);
if (typeof webpackJsonp !== "undefined") { // <-- Test if run as Webpack bundle
// Do dynamic import
import(path).then(cb);
} else {
// Do Ajax call
request(Config.toUrlFromRoot(path)).then(cb);
}
} The It breaks in my Angular demo (which uses Webpack 4.28). My Angular demo has the following Webpack config : module.exports = {
node: { fs: 'empty' }
}; It produces the following error at runtime : Unhandled Promise rejection: Cannot find module './resources/symbology/labelTemplates/labelTemplates.json' ; Zone: <root> ; Task: Promise.then ; Value: Error: Cannot find module './resources/symbology/labelTemplates/labelTemplates.json'
at symbology lazy namespace object:5
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:391)
at Zone.push../node_modules/zone.js/dist/zone.js.Zone.run (zone.js:150)
at zone.js:889
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423)
at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:195)
at drainMicroTaskQueue (zone.js:601) Error: Cannot find module './resources/symbology/labelTemplates/labelTemplates.json'
... Is there anything I'm doing wrong? How can I fix this? |
I don't think the current import method is ideal. I think it should load modules from arbitrary urls like is done in |
* get names of files in directory use reuire.context to get * dynamic import the file content IMORTANT: the first parameter in import method should be a constant prefix! Ref: webpack/webpack#6680 (comment) ==== Tried but failed method: // 1.fs failed, in webpack fs cannot be use // const fs = require("fs"); // console.warn("content=>", fileContent); // fs.readFile(filePath, "utf8", (err, data) => { // if (err) { // console.warn("err=>", err); // } else console.warn("data=>", data); // }); // 2.fileReader failed // var reader = new FileReader(); // reader.readAsText(filePath); // 3.require raw-loader failed, the require expression not figured out yet // var test = require("raw-loader!./static/" + name); // console.log("content=>", test); // import * failed! // import * as txtFiles from "../../public/lyrics";
If you develop a node project and use webpack to build your node project, when you meet the webpack.config.js {
target: 'node',
node: {
__dirname: false,
__filename: false,
}
} eg : import module from 'module';
const test = '/Users/hubert_i/Emodyz/launcher-ezgames.eu/modules/test/index.js'
module.createRequire(__dirname)(test)
.then((m) => {
console.log(m.name)
})
.catch(err => {
console.error('Error during loading module: ' + err)
callback()
}) |
I solved this problem by simply removing the opening slash from the dynamic url. this might work for you.
|
The @thw0rted solution was inconsistent because it depends on your webpack configuration but I found this very clean solution: What they do is simply call Just make sure that your electron configuration is not sandboxed and node is enabled. |
Dynamic |
@MrDarkSkil did you found a solution to that ? |
Yep, many alternatives. Or: /**
* Load custom module with simple require and absolute path
*
* @param {string} path
*/
private requireDynamically(path: string) {
path = path.split('\\').join('/');
return eval(`require('${path}');`);
} |
you can try async-await,I have the same problem solved
|
you can try async-await,I have the same problem solved
|
Your solution does not use dynamic |
Hi, If I import each npm package individually with React.Lazy, it's not a problem:
but if I iterate the paths to create lazy components, webpack cannot find the module:
|
@rubenberna That's because webpack uses a simple logic for building its package bundles. It can't predict what will happen when the code executes. It pre-packs everything it sees within the import() call. If you call |
This is the BEST solution I came across |
@Yawhnie Be careful 😊: #4175 (comment) |
Is there any specific webpack config required for this? Reason: Error: Cannot find module '@/views/branches/create.vue' Update |
I wanted to use dynamic imports to choose which module to import. I used require as a work around (posting in case this helps someone trying to do the same): export const keys = (process.env.NODE_ENV === 'development' ? require('./dev') : require('./prod')).default; |
It seems that Next.js needs to address this issue more seriously. This question reports a strange behavior from Next.js. |
Is that possible to import conditionally a node module ? It's work great with local path like : const { i18n } = await import(`./i18n/${lang}`) But when i try to import module like this : const myModule = await import(`@library-${myVar}`) But the module is missing from the bundle Error: Cannot find module '/Users/hubert_i/Emodyz/launcher-ezgames.eu/modules/test/index.js'. |
Have you tried a relative (vs absolute) path specifier? |
Thanks! |
Guys, if you want really dynamic imports with complete control over how/when/what is imported, use SystemJS: https://github.com/systemjs/systemjs If you want imports that depend on very simple rules, use what webpack comes with by default. Unsubscribes to issue |
For me a solution that worked is: // Absolute path:
const somePath = 'file:C:/somefiles/config.js';
// Or relative:
const somePath = '../config.js';
var someUserProvidedConfigFile = import(
/* webpackIgnore: true */
somePath
); By using |
i am using async await which delays the import statement export async function registerLazyLoadedStuff(): Promise { and wherever you need the lazyloaded stuff just call the function in ngIf (wrapping it up with rxjs from) this does not statically check the import and not load the lazyloaded stuff at runtime till we do not require it. Hope this helps !! |
Thanks for this! |
Do you want to request a feature or report a bug?
bug
What is the current behavior?
When I try to load dynamic module with
import('/path/to/my/module.js').then()
it work, but when i try to import module withimport(rootPath + '/' + myModuleName + '/index.js').then()
it doesn't work.I got:
If the current behavior is a bug, please provide the steps to reproduce.
What is the expected behavior?
Dynamic import with variable
Please mention other relevant information such as the browser version, Node.js version, webpack version, and Operating System.
webpack => 3.10.0
npm => 5.6.0
yarn => 1.5.1
Node.js => v9.6.1
Operating System => macOs High Sierra
The text was updated successfully, but these errors were encountered: