【问题标题】:Access TypeScript global variables with webpack使用 webpack 访问 TypeScript 全局变量
【发布时间】:2018-07-23 13:30:55
【问题描述】:

我是 webpack 的新手,正在将一个中型 TypeScript 应用程序(无框架)转换为使用它。我的main.ts 文件中有一些无法访问的全局变量。

// Global variables
let templates;
let router;
let config;

$(document).ready(() => {
    $.get("/config", (data) => {

        // Create our config object
        config = new Config(data);

        // Load all templates
        templates = new Templates();

        templates.ready(() => {
            router = new Router();
            router.initialize();
        });
    }
}

当我尝试从Router 类访问templates 时,它是未定义的。 我的Router.ts 文件中有declare var templates。我尝试了this answerthis answer 中的建议(将它们放在globals.ts/globals.js 文件中,并使用ProvidePlugin 但没有成功)

webpack.config.js -

plugins: [
        new webpack.ProvidePlugin({
            $: "jquery",
            jQuery: "jquery",
            globals: path.resolve(__dirname, "./globals"),
        }),
    ],

main.ts -

$(document).ready(() => {
        $.get("/config", (data) => {

            // Create our config object
            globals.config = new Config(data);

            // Load all templates
            globals.templates = new Templates();

            globals.templates.ready(() => {
                globals.router = new Router();
                globals.router.initialize();
            });
        }
    }

globals.ts/js -

export let templates, pageManager, config;

我收到错误TS2304: Cannot find name 'globals'.

如果我随后添加 import * as globals from "./globals" 它会编译但我在浏览器控制台中收到以下错误 - Uncaught TypeError: Cannot set property config of #<Object> which has only a getter

我现在有点迷茫。访问这些全局对象的最佳方式是什么?

【问题讨论】:

    标签: typescript webpack


    【解决方案1】:

    您可以将您的应用程序编写为 Node.js 应用程序,然后使用 WebPack 创建一个包。

    这是一个简单的例子。我假设所有输入文件都在一个目录中。 应该安装webpackwebpack-clits-loadertypescript 包。

    globals.ts

    export let foo = null;
    export let bar = null;
    

    index.ts

    import * as globals from "./globals";
    
    globals.foo = "foo";
    globals.bar = "bar";
    
    console.log(globals);
    

    tsconfig.json

    {
       "compilerOptions": {
          "target": "esnext",
          "module": "commonjs"
       }
    }
    

    webpack.config.js

    let path = require("path");
    
    module.exports = {
        entry: "./index.ts",
        module: {
          rules: [
            {
              test: /\.tsx?$/,
              use: "ts-loader",
              exclude: /node_modules/
            }
          ]
        },
        resolve: {
          extensions: [".tsx", ".ts", ".js"]
        },
        output: {
          path: path.resolve(__dirname, "scripts"),
          filename: "bundle.js"
        },
        mode: "development"
    };
    

    【讨论】:

      猜你喜欢
      • 2017-12-16
      • 1970-01-01
      • 2018-12-23
      • 1970-01-01
      • 2012-10-11
      • 1970-01-01
      • 1970-01-01
      • 2016-10-06
      相关资源
      最近更新 更多