如何config.js從 webpack 包中匯入外部檔案 ( )?
我有以下本地開發的檔案結構:
/dist/
/index.html
/plugin.js
/src/
/index.ts
/config.js # This config is only for local dev, will be different in prod
/ ...
將plugin.js被移至第三方網站并由第三方網站執行。我想config.js在我的plugin.js.
config.js我像這樣匯入index.ts:
import config from "../config.js";
我已經設法通過在目前作業的 -欄位中指定它來config.js排除plugin.js它:externalswebpack.config.js
module.exports = {
...
externals: [
"../config.js"
]
}
但是,當我打開index.html時,來自的陳述句import沒有出錯,但-object 檔案是.../config.jsconfigundefined
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"
}
uj5u.com熱心網友回復:
這externals意味著config.js檔案匯出的任何內容都將在運行時可用。因此,對于瀏覽器,這意味著您可能已經通過script標簽或 Node.js 注入了它,它已經通過globalThis或其他等價物匯入。您的匯入行 -import config from "../config.js";捆綁代碼時就消失了。這external并不意味著它會config.js在代碼運行時重新匯入此外,一般做法是使用外部物件配置而不是陣列配置,例如:
module.exports = {
// ...
externals: {
"../config.js": "AppConfig"
}
};
這告訴 Webpackconfig.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.jsin檔案。index.html
<head>
<script src="/path/to/config.js>"></script>
<script src="/path/to/bundle.js>"></script>
</head>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/488867.html
標籤:javascript 打字稿 网页包 webpack-5 ecmascript-2016
