[英]Is it possible to use ES6 import without creating a variable and execute in a single line, similar to CommonJS?
只是想知道,我是否能夠在不創建“占位符”變量的情況下導入 ES6 模塊並立即運行它?
例如,而不是 ES6 的 import 創建一個未使用的express
變量:
import express from 'express'
const app = express();
在 CommonJS 中,沒有它我也可以做到:
const app = require("express")();
這對於一次性導入特別有用,例如dotenv
:
require("dotenv").config();
代替
import dotenv from 'dotenv'
dotenv.config();
//or
import {} from 'dotenv/config'
config()
我認為 CommonJS 語法更簡潔,但似乎 ES6 導入是未來。
謝謝
在 ES6 中沒有辦法做到這一點,但是有一個完成的(第 4 階段)提案可以做到這一點:
(await import('dotenv')).config()
或者,如果目標模塊不提供命名導出:
(await import('dotenv')).default.config()
但是,您應該注意await
只能在異步 function 中使用(直到另一個提議得到實施):
(async ()=>{
(await import('dotenv'))/*.default*/.config()
})()
不,除了提到占位符(默認導出或導出名稱)來導入 ES6 模塊外,別無他法。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.