簡體   English   中英

在 webpack 包中導入外部靜態文件

[英]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.jsexternals字段中指定它,該字段目前有效:

module.exports = {
    ...
    externals: [
        "../config.js"    
    ]

}

但是,當我打開index.html時,來自../config.jsimport語句沒有出錯,但是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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM