[英]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.