[英]Import external static file in webpack bundle
如何從 webpack 包中導入外部文件 ( config.js
)?
我有以下本地開發的文件結構:
/dist/
/index.html
/plugin.js
/src/
/index.ts
/config.js # This config is only for local dev, will be different in prod
/ ...
plugin.js
將被移動到第三方網站並由第三方網站執行。 我想在我的plugin.js
中導入config.js
(將在生產中由第三方網站提供)。
我像這樣在index.ts
中導入config.js
:
import config from "../config.js";
我已經設法從plugin.js
中排除config.js
,方法是在webpack.config.js
的externals
字段中指定它,該字段目前有效:
module.exports = {
...
externals: [
"../config.js"
]
}
但是,當我打開index.html
時,來自../config.js
的import
語句沒有出錯,但是config
-object 文件是undefined
。
prod中第三方服務器的文件結構如下:
/ ... /
/plugins/
/other-plugin/... # A bunch of other plugins. Each has its own folder in plugins
/my-plugin/
plugin.js # This is my plugin
/config.js # This is the global config file of the server for all plugins
索引.ts :
import config from "../config.js";
console.log(config);
配置.js :
module.exports = {
foo: "bar"
}
externals
意味着config.js
文件導出的任何內容都將在運行時可用。 因此,對於瀏覽器,這意味着您可能已經通過script
標簽或 Node.js 注入了它,它已經通過globalThis
或其他等效項導入。 您的導入行 - import config from "../config.js";
捆綁代碼時就消失了。 external
並不意味着它會在代碼運行時重新導入config.js
另外,一般的做法是使用外部對象配置而不是數組配置,例如:
module.exports = {
// ...
externals: {
"../config.js": "AppConfig"
}
};
這告訴 Webpack config.js
文件導出的任何內容都應該在運行時作為AppConfig
對象可用。 使用數組語法適用於有副作用的代碼。
現在回到可能的解決方案。 推薦的選項是使用環境變量來傳遞環境特定的值。 假設您的插件是一個庫,當它被使用並通過 Webpack 作為應用程序的一部分捆綁時,您可以使用DefinePlugin
將這些值注入您的代碼中。 然后,您可以以process.env.foo
的形式訪問代碼中的那些。 您不應該在任何地方的代碼中導入config.js
。
第二個選項是使用外部對象配置,如上所示。 將config.js
文件更改為 UMD 或等效文件:
// config.js file
const config = {
foo: "bar"
};
// Make it available globally
window.AppConfig = config;
// Since `module` is not available in browser.
if (module && module.exports) {
module.exports = config;
}
最后,在加載捆綁腳本之前將config.js
導入index.html
文件。
<head>
<script src="/path/to/config.js>"></script>
<script src="/path/to/bundle.js>"></script>
</head>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.