use*_*023 9 javascript ecmascript-6 webpack
TLDR:如何创建一个模块(通过ES6语法导入)全局作用域(或引用另一个类中的导入类)?
我正在从一个未正确实现的包中导入模块(没有导出等)但是遇到了一些问题.
我正在做的是使用var将模块设置为全局(不是很好),例如
var Example = require('./node_modules/example/long_path_to_file.js');
Run Code Online (Sandbox Code Playgroud)
因为我需要在我的类中使用它(模块控制this并且类实例在全局范围内不可用所以我不能像通常那样使用我的类):
new window.Example(...)
Run Code Online (Sandbox Code Playgroud)
这可行,但它不是很好,因为我使用webpack并且更喜欢使用正确的es6语法
import Example from './example';
Run Code Online (Sandbox Code Playgroud)
然后在 example.js
export default Example = require('./node_modules/example/long_path_to_file.js');
Run Code Online (Sandbox Code Playgroud)
但是这意味着它不再是全局范围的,我无法找到修复方法.
我尝试了类似的东西,window.Example = Example但它不起作用.
The*_*son 11
如果您使用webpack它很容易设置它.所以这是一个如何实现它的简单示例.
webpack.config.js
module.exports = {
entry: 'test.js',
output: {
filename: 'bundle.js',
path: 'home',
library: 'home' // it assigns this module to the global (window) object
}
...
}
Run Code Online (Sandbox Code Playgroud)
some.html
<script>console.log(home)</script>
Run Code Online (Sandbox Code Playgroud)
此外,如果您打开bundle.js文件,您将看到webpack是如何为您完成的.
var home = // main point
/*****/ (function(modules) blablabla)
...
Run Code Online (Sandbox Code Playgroud)
另外我建议看一下webpack库配置.
我希望它会对你有所帮助.
谢谢
我做了一些测试,这是正常的:
import './middleman';
// './middleman.js'
window.Example = require('./example.js').default
// OR
window.Example = require('./example.js').Example
// './example.js'
export function Example() {
this.name = 'Example'
}
export { Example as default }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16495 次 |
| 最近记录: |