最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

在 webpack 中将类导出为模块

网站源码admin44浏览0评论

在 webpack 中将类导出为模块

在 webpack 中将类导出为模块

我正在使用 Webpack 导入一个只有一个类的 javascript 文件。

my_class.js

console.log('hello from my_class');

class myClass {
    // ...
}

index.js

import './my_class.js';

webpack.config.js

const path = require('path')

module.exports = {
    entry: './index.js',
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'bundle.js'
    }
}

我正在尝试在页面上使用此类。

index.html

<script src="./dist/bundle.js"></script>
<script>
    
    const myClass = new myClass();

</script>

我可以查看我的控制台日志(“来自 my_class 的你好”)但是

myClass
显示为未定义。

Uncaught ReferenceError: myClass is not defined

我需要做什么才能导出

myClass
并在标记中可用?

回答如下:

首先你应该导出类。

export class myClass {
    // ...
}

对于浏览器,您应该使用 IIFE 或 UMD 格式:

output: {
  library: 'someLibName',
  libraryTarget: 'umd',
  filename: 'bundle.js'
}

2021 和 webpack 认为联邦应用程序比添加 ES 模块支持优先级更高

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论