Does an imported file inherit the scope of its importer? - javascript

When a file is imported in JavaScript, does that action cause the scope of variables in the imported file become that of the importer file, thus negating the necessity to add import declarations in the second imported file since they are declared in the importer file?
For example, if this is loaded first:
/* Config.js */
import { ImportantVar, OkayVar, LastVar } from 'first/file/path.js';
import DataObject from 'second/file/path.js';
and then this is loaded:
/* Second File */
export const DataObject = function( param1, param2 ) {
return new ImportantVar( param1, param2 );
}
Should this line be added to the top of the second file?
import ImportantVar from 'first/file/path.js';
I don't care if the second file is broken should that it be run independently, i.e. not as an import from config.js.

No. Every module has its own scope.
You're not "importing a file" or "importing the code to be run", you are importing the exported bindings of the module; the module stands on its own, and its exports can be imported in multiple places (while the code is only evaluated once). Inheriting scope wouldn't work with that.
So yes, you'll need to import { ImportantVar } from 'first/file/path.js' in your example.

Related

How to programmatical import module to local scope of nodejs?

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;

js bundles and scope confusion

I'm trying to better understand scoping within a webpacked bundle with node components and other js.
Suppose my entry imports eight files to be bundled:
// entry point
import './components/file1';
import './components/file2';
...
import './components/file8';
And suppose in file1.js I have:
// file1.js
let bubbles = () => {
console.log('likes cats');
};
// or
function bubbles() {
console.log('likes cats');
}
Why then, if I have this in files8 (imported last), does it throw an undefined error? How do I call functions declared in other imports?
// file8.js
bubbles(); // fails in any file other than file1.js where it's declared.
You need to use export explicitly on functions/primitives you're intending to access from the outside:
https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export

Webpack global variable from multiple files

I'm trying to rewrite bunch of legacy JS files into module structure. I have obfuscated plugin which contains out of few files, which in turn work with single global variable. The order of execution of these files matters.
Example:
file1.js
var myModule = {someStuff};
file2.js
myModule.someProperty = someValue;
What i want to achieve is to import them all somehow and get this global variable myModule.
Possible implementation:
myModule.js
import myModule from "file1.js";
import myModule from "file2.js"; // ofc i know it does not work this way
export default class myProgramm {
constructor(){
myModule.run({options});
}
}
What i tried so far is webpack provide plugin (https://webpack.js.org/plugins/provide-plugin/), but it doesn't work with multiple files. Also i tried to use provide-multiple-plugin (adopted to webpack 4) from this gist :https://gist.github.com/shellscape/a7461022503f019598be93a512a1901a. But it seems to include files in nearly random order, so it can happen that myModule is not defined, while file2.js is executed first.

Meteor: importing whole module doesn't work

I am trying to make my Meteor code ES6 compatible. I had a file called /both/global.js containing functions and constants that I wanted to be accessible globally. For ES6 purposes, I moved it to /both/imports/global.js and prefaced all the functions and constants with export const.
I haven't changed the whole directory structure yet. The template javascript files are still in /client/controller/. I have added to them import statements for the exported functions and constants. When I write the import statements in the form:
import { fn1, fn2, ... } from '../../both/imports/global.js';
they work fine.
I would rather import all the functions and constants with a single:
import from '../../both/imports/global.js';
but that doesn't seem to do anything.
What am I doing wrong?
It's to do with the way imports and exports work.
What you need is
import * from '/both/imports/global.js'
Alternatively...
import something from '/both/imports/global.js'
Will look for the default export, and assign it to the variable called something.
import { fn1, fn2, ... } ...
Will import the named variables into your namespace
Another way is to do this:
import globalFunctions from '/both/imports/global.js'
Then your functions are callable like this:
globalFunctions.fn1()
globalFunctions.fn2()

How do we declare import types from NPM library that has no declaration files?

For example, if I have the following in my app,
import Node from 'infamous/motor/Node'
console.log(Node)
that works just fine. But the moment I actually do something with it,
import Node from 'infamous/motor/Node'
console.log(new Node)
then TypeScript will complain because there's no type definition for Node. How do I define the type of Node?
The library has no type declarations of it's own. I tried something like
import MotorNode from 'infamous/motor/Node'
declare class MotorNode {}
console.log(' --- ', new MotorNode)
but I get the error
./src/app.tsx(6,8): error TS2440: Import declaration conflicts with local declaration of 'MotorNode'
When I need to do what you are trying to do, I create an externals.d.ts file in which I put module augmentations for my project and make sure that my tsconfig.json includes it in the compilation.
In your case the augmentation might look something like this:
declare module "infamous/motor/Node" {
class Node {
// Whatever you need here...
}
export default Node;
}
I put it in a separate file because a module augmentation like this has to be global (must be outside any module), and a file that contains a a top-level import or export is a module. (See this comment from a TypeScript contributor.)

Categories

Resources