An easy tutorial on how to import one JS file into another using ES6
Until some years ago, it was not possible to import one js file or block of code from one file into another but since 2015, ES6 has introduced useful ES6 modules.
With the module
standard, we can use import
and export
keyword and syntax given to include and export the module in JS respectively.
The static import
statement is used to import bindings which are exported by another module. Imported modules are in strict mode whether you declare them as such or not. The import statement
cannot be used in embedded scripts unless such script has a type="module".
There is also a function-like dynamic import[]
, which does not require scripts of type="module".
Backward compatibility can be ensured using attribute nomodule on the script tag.
How we include the js files:
index.html
script1.js
export default function Hello[] { return "Hello buddy!"; }
script2.js
import { Hello } from './script1.js'; let val = Hello; console.log[val];
Run the above sample code blocks in your local system/local server, you will get the console output as: Hello buddy!
Code and Syntax Explanation of the code above:
In script1.js, we exported the module with the syntax of : export module
Similarly, in our case, we exported the function Hello
by writing the export
keyword in the function definition [line
number 1 in script1.js]. In script2.js, we imported that module by writing the following code/syntax :
import { Hello } from './script1.js';
Right now in script1.js, we have only one module to export but what if we had multiple modules to export? That is also possible with a similar syntax but with a slight modification:
Sample Code for multiple modules:
script1.js
export let Name = [name] => {return "My name is " + name;} export let Address = [address] => {return "i live in " + address;} export let Age = [age] => {return "my age is "+ age;}
script2.js
import { Name, Address, Age} from './script1.js'; let val = Name["John"]; let age = Age[26]; console.log[val + " and " + age];
In script1.js, we have three modules named Name, Address, and Age. In Script2.js, we imported those modules with similar but little different syntax.
import { Name, Address, Age} from './script1.js';
Note: we didn’t have { } in earlier import code because that was default export [ remember one file can have only one default export].
When we remove that default keyword in previous code of script1.js, we get an error in the console and that error looks like this:
Infact there are two types of exports:
- Named Exports [Zero or more exports per module]
- Default Exports [One per module]
This is only a quick explanation, you can fond more examples at MDN web docs:
Import Statement Reference at MDN
Export Statement Reference at MDN
WEB DEVELOPER CONSOLE TRICKS
Loading an external script directly from the console can be tricky. Here is how to import JavaScript without a
tag directly from Firefox or Chrome’s development console.
Let’s say you’re working on a project, and you are considering adding an external library to manipulate the page or add additional functionality. You might want to load up the latest version of jQuery, for example.
Usually, you would just add a tag to the HTML, which will load the external JavaScript file. For example, to load jQuery, you would add:
But what if you want to just load the external script using the command line from the DevTools console? Doing so is especially useful when prototyping or when you are trying to tweak pages that you don’t own — like if you want to use jQuery to quickly process data on someone else’s site.
This article will explain how you can load an external JavaScript file directly from the browser’s console window as part of your prototyping workflow.
You don’t need to know jQuery or any other external library in order to be able to use the methods discussed in this article. Thankfully, JavaScript has built-in tools to import external JavaScript files from the console.
The quick & dirty way
The shortest and most-straightforward way to import an external script file from the console is to use document.write[]
, literally writing the tag to the loaded page. Here is a code example:
Note the use of template literals for the HTML in the code snippet.
This method will work fine if you just need the script to work in the console, but it is no good if you want to work with the currently open document — the current page will disappear instantly as soon as you run this code.
“Note: as
document.write
writes to the document stream, callingdocument.write
on a closed [loaded] document automatically callsdocument.open
, which will clear the document.” — MDN Docs
Let’s explore two other options that won’t clear the loaded document.
A better way
Using appendChild[]
is a more useful way to load an external script file. Instead of overwriting the loaded page with document.write[]
, appendChild[]
will add a new tag directly to the
page.
Let’s take a look at a code example:
Note the use of eval[]
to execute the code is not needed in most instances. You actually only need
eval[]
if your code is a string containing the tag, like in the
document.write[]
example:
eval[`
If you have a string containing the tag loading the file, the string won’t actually be run without
eval[]
. But if your script is an external JavaScript file [like loading jQuery, as we’ll see later], you don’t need eval[]
. Just callingNode.appendChild[script]
will load the script for you.
You should be aware that
eval[]
has some security risks. I’ll explain later why you would use Function[]
instead, but for demonstration purposes eval[]
will work fine. Using eval[]
to
evaluate a string is similar to doing so with document.write[]
: something you can do, but shouldn’t.
Since I included eval[]
in the examples for comparison and discussion, please be aware that it’s not necessary in modern browsers.
Another way: fetch
Using fetch[]
is going to be another way to load an external JavaScript file from the command line.
Here is an example of using fetch[]
with multiple .then[]
calls:
Alternatively, you can achieve the same functionality using async
/ await
instead of
chaining the Promise returned by fetch[]
:
Again, you probably want to substitute Function[]
for eval[]
if you need to evaluate a string, as I will be discussing later in the article. That will only apply if you’re loading a string that includes a tag that needs to be executed; otherwise, you don’t need either command.
Next, let’s look at a working example of each method using jQuery.
Loading jQuery in the console
This section will provide code examples for each method discussed above. You will be loading the jQuery library and then using it to apply a CSS border style to every Please be aware that you
might get a TypeError “ The TypeError occurs because JavaScript
actually has a built-in dollar sign method Finally, these demonstrations may only work on certain
pages: for me, they work in the browser console on the Google homepage, but not while looking at a GitHub Gist, because of the message: Your mileage may vary. In this case, This method works great, without overwriting the loaded page. Calling As mentioned, you don’t actually need to Depending on your personal preference, there are two equivalent options for using Second, you can use Either of these methods would be considered a way of loading an external JavaScript file directly from the console window. Just remember that you don’t need As I mentioned in passing previously, “ Put simply, you should use Using Syntax-wise, there is no difference — just swap But using “ I should add thee caveat that I find
that Typically, appendChild[] will load the script just fine and will be the preferred method — with better performance and less security risk. If you try the code examples yourself using jQuery, please keep in mind that there is a
built-in dollar sign method You have many other options if you’re interested in loading multiple external files or tools using JavaScript. For example, if you already have jQuery loaded on a page, you can use jQuery’s helper function
Some other potentially useful options for loading
external scripts are: Of these,
jspm.io is especially interesting because it allows you to use a simple One thing to watch out for here is “namespace pollution” — the script you are importing may overwrite global variables already defined on that
page. The previously-mentioned dollar sign method If namespace pollution is a concern, a tool like Tampermonkey may be helpful. Tampermonkey is a browser extension that can easily handle multiple running scripts on the same page without namespace collisions. You might also consider RunKit, which is a website linked on every npm package
[such as jQuery] that lets you try out any Node.js package in the browser, with no setup required. Here is the RunKit for jQuery. [I never have any luck using jQuery inside RunKit, but you may be able to make it work]. Similarly,
CodeSandbox lets you easily sandbox any individual npm package or combination of npm packages without needing to install anything locally, as does CodePen via SkyPack. It is common that a developer might want to test an external library or
other JavaScript file using the browser’s development console. For example, you might want to load jQuery, either for the purpose of manipulating the current page or just to practice syntax in the console. Whether prototyping, learning, testing, or modifying an existing page, it can be very useful to load an external library from the developer console. This article discussed three methods of loading an external JavaScript file from the console:
I provided an example using each method showing how to load jQuery from the browser’s console environment. Alternatively, you might try other tools — like SystemJS, ModuleLoader,
jspm.io, Tampermonkey, RunKit, or CodeSandbox — depending on your exact needs and personal preferences. Hopefully, this article helps you unlock the full power of
Chrome DevTools or Firefox’s Web Console. Happy coding! 👏👍💯😄🧠️🏎$[...].css is not a function
” with any of these examples if you enter all the commands at the same time. You need to wait for a second between loading the script and actually using it. So enter the commands necessary to load the external script first, then enter commands using the script.$[]
that you are trying to overwrite with jQuery. The built-in dollar sign method does not have a .css[]
function — that’s jQuery. So you have to wait for eval[] to finish loading the script before you can actually call the $["div"].css[]
function.Refused to load the script '//code.jquery.com/jquery-3.5.0.js' because it violates the following Content Security Policy directive: "script-src github.githubassets.com".
Method 1:
document.write[]
document.write[]
overwrites the loaded page, so there is nothing to actually apply the CSS styles to. But, jQuery will be loaded into the console window, for what it’s worth.Method 2:
appendChild[]
document.head.appendChild[script]
loads the script into the element of the page.
eval[]
here — but you do need to wait for the appendChild[]
command to execute on the browser window before jQuery is available for use.Method 3:
fetch[]
fetch[]
. First is using fetch[]
with Promise chaining:async
& await
to handle the Promise returned by fetch[]
:eval[]
unless you’re loading a string containing a tag, like in the
document.write[]
example.But wait —
never use
eval[]
!eval[]
has security risks associated with it, as the MDN Docs explain well:eval[]
is a dangerous function, which executes the code it's passed with the privileges of the caller. If you run eval[]
with a string that
could be affected by a malicious party, you may end up running malicious code on the user's machine with the permissions of your webpage / extension. More importantly, a third-party code can see the scope in which eval[]
was invoked, which can lead to possible attacks in ways to which the similar Function
is not susceptible.” — MDN
Docs
Function[]
instead of eval[]
— but eval[]
is commonly used, so don’t be surprised if you see it around.Function[]
would look like the following code example:Function[]
for eval[]
.Function[]
will improve the security and performance of your website or application, even when just loading an external library from the developer console.Function[]
Creates a new Function
object. Calling the constructor directly can create functions dynamically but suffers from security and similar [but far less significant] performance issues to eval
. However, unlike eval, the Function
constructor creates functions that execute in the global scope only.” — MDN Docseval[]
sometimes work for me when Function[]
doesn’t — for example, Function[]
seems to be blocked on some websites where eval[]
is not blocked, for whatever reason.$[]
that jQuery will overwrite.Other options
$.getScript[]
:import[]
statement directly from the console window.$[]
is an example of a namespace conflict with jQuery. You could also run into namespace issues if your version of jQuery conflicts with a version of jQuery already loaded on the website.Conclusion
document.write[]
, appendChild[]
, and fetch[]
.How do I load a script into JavaScript?
How do I import a file into a JavaScript file?
Where do I put scripts in JavaScript?
How do you write a JavaScript script?
Chủ Đề