I was reading a node.js cli module documentation and it has one line like this. I know that we can include external modules like this but dont know what is the use of '.' while requiring a module;
const foo = require('.');
Can anyone tell me what is use of it or why its used that way.
It will import index file in the folder where you are running your file will empty require statement. Javascript require module will try to find index.js file if you do not specify any file name(only provide folder reference) in the require() argument.
Basically it's an alias for const foo = require('./index.js');
index.js
module.exports = 1;
foo.js
const foo = require('.');
console.log({ foo });
If both files are in the same folder then it will print
{ foo: 1 }
In require('.'), '.' represent the current directory, and ".." means parent directory.
-- parent
-- child1
-- grandchild1
-- grandchild2
-- child2
Now, suppose you are at child1 and want to import files from grandchild1 or inside the subfolder, Then you have to start from the current location (".") to the grandchild location.
require('./grandchild1/filename')
and, if need to import from the parent or outside your current directory, then you have to start backward that is from parent location (".."):
require('../parent/filename')
// here '..' take you one folder back (parent folder) and if you want to go one more folder back (parent of parent folder) then add one more pair of dots : '../../some_folder'
Related
I have two files, one is my main js file called app.js and I have a file where I store all my js functions, called functions.js. As you can see on the image below.
But I want to include the functions.js file into the app.js file. So I googled on how to do it and this is what people said:
But my npm run dev says the file doesn't exist. But the path is correct. What am I doing wrong here, is there a other way to do it?
You can simply just create the file wherever you want to create it, and then export some properties or methods, and then import them in your app.js file, or in whatever file you need. Something like this :
//new_file.js
export const jokes = function() {
return ['funny', 'not really funny', 'boring']
}
export const heading = 'some global heading to be reused.'
And in your app.js file :
import { jokes, heading } from 'new_file.js'//specify actual path here .
console.log(jokes) // ['funny', 'not really funny', 'boring']
console.log(heading)//some global heading to be reused.
This tutorial might be helpful too .
http://www.2ality.com/2014/09/es6-modules-final.html
The code environment is browser. bundle tool is webpack. I have a router.js file like:
import foo from './views/foo.vue'
import bar from './views/bar.vue'
import zoo from './views/zoo.vue'
//use foo, bar, zoo variables
I've many '.vue' files to import like this under views folder. Is there a programmatical way to auto import all [name].vue as local variable [name]? So when I add or remove a vue file in views, I don't need to manually edit router.js file. this one seems a little dirty.
for (let name of ['foo', 'bar', 'zoo']) {
global[name] = require(`./views/${name}.vue`)
}
Nope, that's it. You have a choice between dynamic import and automation, or explicit coding and type-checking / linting.
Unfortunately, it's one or the other. The only other way to do it is meta-programming, where you write code to write your code.
So you generate the import statements in a loop like that, and write the string into the source file, and use delimiting comment blocks in the source file to identify and update it.
The following works for me with webpack and vue.
I actually use it for vuex and namespaces. Hope it helps you as well.
// imports all .vue files from the views folder (first parameter is the path to your views)
const requireModule = require.context('./views', false, /\.vue$/);
// create empty modules object
const modules = {};
// travers through your imports
requireModule.keys().forEach(item => {
// replace extension with nothing
const moduleName = item.replace(/(\.\/|\.vue)/g, '');
// add item to modules object
modules[moduleName] = requireModule(item).default;
});
//export modules object
export default modules;
I'm making a command-based class and adding a unload function where it basically deletes the file's require cache, e.g. I have foo.js and that has a class that extends off of the class inside of Command.js, when I run the unload function for foo.js, it basically forgets foo.js with delete require.cache[require.resolve("DIR/TO/foo.js")], BUT here is the catch, I do not know the directory to foo.js. I don't want the user (basically me) to have to write down the file directory to unload like this:
var dir = "./dir/to/foo.js"
var { Command } = require("./../../Essentials/Command.js")
class foo extends Command {
// data...
}
foo.unload(dir)
because that wouldn't make sense, I'd prefer the code would run like foo.unload() and it would unload the file.
Here's what my class basically is
class Command {
constructor(client, info) {
//code
}
unload() {
delete require.cache[require.resolve('dir')]
}
}
Is there a variable or a built in package that can tell me the dir of the file it's in? E.g. If I use the class in Foo.js it tells me the dir to Foo.js.
If you plan to allow the whole path until the file, your safest bet is to use process.cwd().
process.cwd() returns the location of where the Node.js process has been invoked, that normally would be the root of your directory, so then you will only need to build the path to the file.
I'm trying to add dynamic import into my code to have a better performance on the client-side. So I have a webpack config where is bundling js files. On SFCC the bundled files are in the static folder where the path to that files is something like this: /en/v1569517927607/js/app.js)
I have a function where I'm using dynamic import of es6 to call a module when the user clicks on a button. The problem is that when we call for that module, the browser doesn't find it because the path is wrong.
/en/lazyLoad.js net::ERR_ABORTED 404 (Not Found)
This is normal because the file is on /en/v1569517927607/js/lazyLoad.js.
There is a way to get it from the right path? Here is my code.
window.onload = () => {
const lazyAlertBtn = document.querySelector("#lazyLoad");
lazyAlertBtn.addEventListener("click", () => {
import(/* webpackChunkName: "lazyLoad" */ '../modules/lazyLoad').then(module => {
module.lazyLoad();
});
});
};
I had the same problem and solved it using the Merchant Tools > SEO > Dynamic Mapping module in Business Manager.
There you can use a rule like the following to redirect the request to the static folder:
**/*.bundle.js i s,,,,,/js/{0}.bundle.js
All my chunk files are named with the <module>.bundle pattern.
Here you can find more info :
https://documentation.b2c.commercecloud.salesforce.com/DOC1/topic/com.demandware.dochelp/content/b2c_commerce/topics/search_engine_optimization/b2c_dynamic_mappings.html
Hope this helps.
I believe you'll likely need to do some path.resolve() magic in either your import statement or your webpack.config.js file as is shown in the accepted answer to this question: Set correct path to lazy-load component using Webpack - ES6
We did it in a different way. That required two steps
From within the template file add a script tag that creates a global variable for the static path. Something like
// inside .isml template
<script>
// help webpack know about the path of js scripts -> used for lazy loading
window.__staticPath__ = "${URLUtils.httpsStatic('/')}";
</script>
Then you need to instruct webpack to know where to find chunks by changing __webpack_public_path__ at runtime
// somewhere in your main .js file
// eslint-disable-next-line
__webpack_public_path__ = window.__staticPath__ + 'js/';
Optional step:
You might also want to remove code version from your __staticPath__ using replace (at least we had to do that)
__webpack_public_path__ = window.__staticPath__.replace('{YOUR_CODE_VERSION_GOES_HERE}', '') + 'js/';
My .cTags is working fine in mostly cases. However in a scenario mentioned below it's not working as expected.
Directory Structure
root
- a
- foo.js
- bar.js
- index.js
- b
- current-file.js
current-file.js
import { foo } from './a'
foo()
index.js
export { default as foo } from './foo'
foo.js
const foo = () => 'foo'
export default foo
When i am trying to jump in definition of foo from current-file.js its navigating to a/index.js instead of a/foo.js
I think this is not a limitation about the cTags, but about the ES6 language itself.
The curly braces import will first lookup for the file named a, if not found, it will look for the directory named 'a' with its index.js file (auto-resolved, e.g: a/index.js). It won't look for a file into a directory.
The curly braces are only looking for the non-default exports from a file, and it's not looking through directories.
Example (NOTE: the directory a has been renamed to c as codesandbox reserved the name a in his engine)
You can try to remove the /c.js file to load the c/index.js file instead.
Also, I suggest you this thread which can give you more tips on curly brackets in js
You might be able to do a read through a directory with the fs.readDir api and automatically require/export the files in your index.js; But the index.js will be loaded.