Home > Article > Web Front-end > Two ways to import js files in Javascript
In order to avoid displaying a large amount of code in HTML
, we generally choose to put the js script
into a separate file, and then js file
is imported into HTML
, which can make the HTML
file more concise. This article mainly introduces two ways to import js script
: : Traditional import, module import.
First confirm the location of the js script
that needs to be imported. This article is in the same path as the HTML
file.
1. Traditional import:
JS script content:
//文件名:example.js let a="呵呵姑娘";
HTML content:
<!-- example.html --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script src="./example.js"></script> <script> console.log(a); </script> </body> </html>
2. Module import:
JS script content:
//文件名:example.js let a="呵呵姑娘"; export {a};
HTML content:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script type="module"> import {a} from './example.js'; console.log(a); </script> </body> </html>
Recommended: "2021 js interview questions and answers (large summary)"《js tutorial》
The above is the detailed content of Two ways to import js files in Javascript. For more information, please follow other related articles on the PHP Chinese website!