简体   繁体   English

通过Webpack从打字稿中导出对象并在JS中使用它

[英]Export object from typescript through webpack and use it in JS

What I'm trying to do is to bundle a library that I've wrote in Typescript with Webpack 2 and to be able to use this library even with vanilla JS. 我想要做的是将我在Typescript中编写的库与Webpack 2捆绑在一起,甚至可以在香草JS中使用该库。 The building goes fine and without errors, but when it comes to use the exported object it appears like an empty object {} . 建筑物运行良好且没有错误,但是在使用导出的对象时,它看起来像一个空对象{}

So what I've tried to do is the following: 因此,我尝试执行以下操作:

  • Bundle the library in a bundle.js file 将库捆绑在bundle.js文件中
  • Create a my-js-script.js file that logs to the console the object exported by the .ts file 创建一个my-js-script.js文件,该文件将.ts文件导出的对象记录到控制台
  • Create a index.html file 创建一个index.html文件
  • Import both the bundle.js and my-js-script.js files 导入bundle.jsmy-js-script.js文件
  • Serve the index.html file and see the object in the console. 服务index.html文件,然后在控制台中查看该对象。

Typescript file 打字稿文件

import {SomeStuff} from 'some-stuff';

export class ClassA {
    constructor(){
        // Does other stuff with SomeStuff
    }
}

// What I want to achieve is something like this
export const myModule = new ClassA();

I thought that creating an html file that imports the bundle and my-js-script file were enough in order to have access to the myModule constant. 我认为创建一个导入捆绑包和my-js-script文件的html文件足以访问myModule常量。 But unfortunately it wasn't enough. 但是不幸的是,这还不够。

index.html index.html

<html>
    <head>
        <script src="./bundle.js"></script>
        <script src="./my-js-script.js"></script>
    </head>
    <body>
    </body>
</html>

Javascript file Javascript文件

myModule.doSomething();

What am I missing? 我想念什么? Or there's simply non chances to do that? 还是根本没有机会这样做? The webpack configuration is dead simple Webpack配置非常简单

var path = require("path");

module.exports = {
    entry: "./src/web-onion.ts",
    output: {
        path: path.resolve(__dirname, 'dist/'),
        filename: "bundle.js"
    },
    resolve: {
        extensions: [".webpack.js", ".web.js", ".ts", ".tsx", ".js"]
    },
    module: {
        loaders: [
            { test: /\.tsx?$/, loader: "ts-loader" }
        ]
    }
}

You can't do that this way. 你不能这样子。 myModule won't be exported as a global. myModule不会作为全局导出。 If you want to export something globally, use in the TypeScript file: 如果要全局导出某些内容,请在TypeScript文件中使用:

window.something = myModule

Note: you will have to either extend Window interface or use (window as any) . 注意:您将不得不扩展Window界面或使用(window as any)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM