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

javascript - Export class as a module in webpack - Stack Overflow

programmeradmin1浏览0评论

I'm using Webpack to import a javascript file that has a single class.

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'
    }
}

I'm trying to use this class on a page.

index.html

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

</script>

I am able to seem my console log ("hello from my_class") but myClass is showing up as undefined.

Uncaught ReferenceError: myClass is not defined

What do I need to do such that myClass is exported and available in the markup?

I'm using Webpack to import a javascript file that has a single class.

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'
    }
}

I'm trying to use this class on a page.

index.html

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

</script>

I am able to seem my console log ("hello from my_class") but myClass is showing up as undefined.

Uncaught ReferenceError: myClass is not defined

What do I need to do such that myClass is exported and available in the markup?

Share Improve this question edited Feb 18, 2021 at 3:22 Melissa Diaz asked Feb 18, 2021 at 3:18 Melissa DiazMelissa Diaz 3782 silver badges8 bronze badges 2
  • Does this answer your question? How to use Javascript "export" and "import" functions properly? – Randy Casburn Commented Feb 18, 2021 at 3:21
  • Not really. I tried using exports.myClass = myClass at the bottom of my_class.js but myClass was still undefined on the front end. Im thinking its because exports is in the node environment and Im trying to use it on front end, but I though webpack would take care of all that? – Melissa Diaz Commented Feb 18, 2021 at 3:26
Add a ment  | 

3 Answers 3

Reset to default 4

Firstly you should export the class.

export class myClass {
    // ...
}

And for browsers you should use IIFE or UMD format:

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

2021 and webpack thinks federated apps are higher priority than adding ES module support

发布评论

评论列表(0)

  1. 暂无评论