iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 7
0
Modern Web

從Stack Overflow學前端系列 第 7

從StackOverflow上學CODING(7)如何在 JS 檔案中導入另一個 JS 檔案

  • 分享至 

  • xImage
  •  

How do I include a JavaScript file in another JavaScript file?

Is there something in JavaScript similar to @import in CSS that allows you to include a JavaScript file inside another JavaScript file?
Javascript有沒有任何語法可以像CSS @import一樣能允許你將JS 檔案導入另一個 JS 檔案呢?

原本問答區有許多精彩問答後來發現JS ES6就已經包括了這項新功能,不過還是提一下 以前其他框架與瀏覽器自帶的解決方法:
1.ES6 Modules

// module.mjs
export function hello() {
  return "Hello";
}
// main.mjs
import { hello } from 'module'; // or './module'
let val = hello();  // val is "Hello";

2.ECMAScript modules in browsers
Browsers have had support for loading ECMAScript modules directly (no tools like Webpack required) since Safari 10.1, Chrome 61, Firefox 60, and Edge 16. Check the current support at caniuse.
很多瀏覽器會自帶支持此語法 Safari 10.1, Chrome 61, Firefox 60, and Edge 16

<script type="module">
  import { hello } from './hello.mjs';
  hello('world');
</script>
// hello.mjs
export function hello(text) {
  const div = document.createElement('div');
  div.textContent = `Hello ${text}`;
  document.body.appendChild(div);
}

3.Dynamic imports in browsers

<script type="module">
  import('hello.mjs').then(module => {
      module.hello('world');
    });
</script>

4.Node.js require
The old style of importing modules, still widely used in Node.js, is the module.exports/require system.
比較古早的方法,但還是在Node.js內被廣泛運用

// mymodule.js
module.exports = {
   hello: function() {
      return "Hello";
   }
}
// server.js
const myModule = require('./mymodule');
let val = myModule.hello(); // val is "Hello"   

5.AJAX Loading

You could load an additional script with an AJAX call and then use eval to run it. This is the most straightforward way, but it is limited to your domain because of the JavaScript sandbox security model. Using eval also opens the door to bugs, hacks and security issues.

你可以在AJAX call中讀取一個js scrupt然後使用eval去啟動,這是一個很直接的方法,但是被限制在自己的domain內,因為JS沙盒安全模組(JavaScript sandbox security model)的限制,使用eval也很容易出資安漏洞

6.Fetch Loading
Like Dynamic Imports you can load one or many scripts with a fetch call using promises to control order of execution for script dependencies using the Fetch Inject library:

如同Dynamic Imports你也可讀取被包含在一個fetch內一或數個的script,然後用promises去控制或執行

fetchInject([
  'https://cdn.jsdelivr.net/momentjs/2.17.1/moment.min.js'
]).then(() => {
  console.log(`Finish in less than ${moment().endOf('year').fromNow(true)}`)
})

7.jQuery Loading
The jQuery library provides loading functionality in one line:

在jQuery框架內就有包含此功能:

$.getScript("my_lovely_script.js", function() {
   alert("Script loaded but not necessarily executed.");
});

上一篇
從StackOverflow上學CODING(6)宣告一個變數並賦予一個函式值與建立一個函示並命名的差別
下一篇
從StackOverflow上學CODING(8) 使用"let"與"var"的區別?
系列文
從Stack Overflow學前端30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言