如何在Webpack中使用从TypeScript生成的JS文件中的类?

huangapple go评论76阅读模式
英文:

How to use a class within a generated JS file (generated from Typescript) in Webpack?

问题

  1. 还有其他方法吗?
  2. 如何访问该类,而不是MyLibrary.TheClass()
  3. libraryTarget: 'umd' 有什么作用?
英文:

I'm working on some Typescript project which the output (JS) will be used in a Javascript project (like a plugin). Like this:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
    </head>
    <body>
        <script src="../dist/bundled.js"></script>
        <script>
            new TheClass()
        </script>
    </body>
</html>

TheClass is defined in the Typescript file which is converted to Javascript (bundled.js) by Webpack. The target in the tsconfig.js is ES5 and the module item is set to ES6.

Now, it throws this error: Uncaught ReferenceError: TheClass is not defined.

So, I tried to add library options to the output section of webpack.config.js:

const path = require("path")

module.exports = {
    mode: "development",
    entry: "./src/main.ts",
    devtool: "inline-source-map",
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                include: path.resolve(__dirname, "src"),
                use: "ts-loader",
                exclude: /node_modules/,
            },
        ],
    },
    resolve: {
        extensions: [".tsx", ".ts", ".js"],
    },
    output: {
        libraryTarget: 'umd', ///////////////////////////////// added this.
        library: 'MyLibrary', ///////////////////////////////// added this.
        filename: "bundled.js",
        path: path.resolve(__dirname, "dist"),
    },
}

Now I can access the class like this:

new MyLibrary.TheClass()

I also need to mention that the class is defined like this (it is exported):

export class TheClass {}

Ok, now there 3 questions:

  1. Is there another way for doing this?
  2. How can I access the class like: TheClass() (And not MyLibrary.TheClass())
  3. How does libraryTarget: 'umd' help?

I also tried export default:

export default class TheClass {}

So, I can use the class like:

new MyLibrary()

It didn't work.

答案1

得分: 2

以下是翻译好的部分:

Is there another way for doing this?
没有,我认为这是将您的模块代码导出到外部库的唯一方法。

How can I access the class like: TheClass() (And not MyLibrary.TheClass())
您可以查看类型,可以使用 windowglobal,如此处所述:https://webpack.js.org/configuration/output/#type-window,这可能适用于您的情况:

library: {
   name: 'TheClass',
   type: 'window', // 或 `global`
},

How does libraryTarget: 'umd' help?
umd 是一个拟议的模块,旨在适用于许多环境,如浏览器和节点,因此它应该在这两种环境中都能作为模块工作。

英文:

Good question. Here are answers on each question based on what I know:

> Is there another way for doing this?

No, I think this is the only way to export your module code to an external library.

> How can I access the class like: TheClass() (And not MyLibrary.TheClass())

You can check out the type either window or global as addressed here https://webpack.js.org/configuration/output/#type-window which is likely to work for your case:

library: {
   name: 'TheClass',
   type: 'window', // or `global`
},

> How does libraryTarget: 'umd' help?

umd is an proposed module which is designed to work for many environments such as browser and node so it should work on as module on both envs

答案2

得分: 0

找到了!我将这部分更改为:

libraryTarget: 'umd',
library: 'MyLibrary',

改成了:

libraryExport: 'default',
library: 'TheClass',

我还在我的TypeScript文件中使用了export default

export default class TheClass {}

现在,我可以做我想做的事情了:

new TheClass()

尽管从逻辑上讲,库的名称必须与类的名称相同。所以,如果你更改了类的名称,请记得同时更改库的名称。


如果有人知道如何防止库和类名称之间的冲突,请在此答案上评论或私信我。谢谢。

英文:

Found it! I changed this:

libraryTarget: 'umd',
library: 'MyLibrary',

Into this:

libraryExport: 'default',
library: 'TheClass',

I also used export default in my Typescript file:

export default class TheClass {}

Now, I can do what I wanted to:

new TheClass()

Although, logically speaking, the name of our library has to be the same with the name of our class. So, if you change your class name, remember to change the library's name too.


If anyone knows how to prevent this conflict between the library and the class name, please comment on this answer or message me. Thanks.

huangapple
  • 本文由 发表于 2023年6月22日 14:28:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/76529105.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定