typescript - Webpack DefinePlugin 不替换输出中的文本

标签 typescript webpack

我什至很难得到 webpack 的一个 token 示例 DefinePlugin在职的。即,npx webpack运行得很好,但输出 js 文件没有替换定义的标记。这是我的最小(非)工作示例:

const webpack = require('webpack');

module.exports = {
    // bundling mode
    mode: "development",
    devtool: 'source-map',

    // input file
    entry: "./Index.ts",

    // loaders (e.g. run tsc on *.tsx?)
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                exclude: /node_modules/,
                use: {
                    loader: "ts-loader",
                }
            },
        ]
    },

    plugins: [
        new webpack.DefinePlugin({
            DUMMYVARIABLE: JSON.stringify('helloworld'),
        })
    ],
}
索引.ts
var DUMMYVARIABLE: string;

export class IndexModel {
    public static GetDummyVariable(): string {
        return DUMMYVARIABLE;
    }
}
输出 js 文件(注意 DUMMYVARIABLE 仍然存在,而不是像预期的那样被 'helloworld' 替换):
/******/ (() => { // webpackBootstrap
/******/    "use strict";
var __webpack_exports__ = {};
// This entry need to be wrapped in an IIFE because it uses a non-standard name for the exports (exports).
(() => {
var exports = __webpack_exports__;
/*!******************!*\
  !*** ./Index.ts ***!
  \******************/

exports.__esModule = true;
exports.IndexModel = void 0;
var DUMMYVARIABLE;
var IndexModel = /** @class */ (function () {
    function IndexModel() {
    }
    IndexModel.GetDummyVariable = function () {
        return DUMMYVARIABLE;
    };
    return IndexModel;
}());
exports.IndexModel = IndexModel;

})();

/******/ })()
;
//# sourceMappingURL=main.js.map
据我所知,拥有一个名为 tsconfig.json 的文件很重要,但它的内容并不重要——目前我只有 {}在那里。
有人可以帮助我了解我哪里出错以及如何获得 DefinePlugin为我工作?
希望你能原谅我的 webpack 新手,我以前已经能够将 webpack 视为一个黑匣子。

最佳答案

Webpack 不会取代 DUMMYVARIABLE带有“helloworld”的变量,因为您没有将其定义为 global variable .为了使您的示例工作,您需要添加 declare :

declare var DUMMYVARIABLE: string;

export class IndexModel {
    public static GetDummyVariable(): string {
        return DUMMYVARIABLE;
    }
}
现在webpack.DefinePlugin将替换这样的事件:
var IndexModel = /** @class */ (function () {
    function IndexModel() {
    }
    IndexModel.GetDummyVariable = function () {
        return "helloworld";
    };
    return IndexModel;
}());

关于typescript - Webpack DefinePlugin 不替换输出中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66753073/

相关文章:

angularjs - Npm 测试抛出错误,但应用程序运行没有错误

带有 sass-loader 和 resolve-url-loader 的 Webpack 4 - 找不到图像路径

docker - 让webpack-dev-server在docker下工作

javascript - 从 HTML 文件中的 TypeScript (.ts) 获取值。

angular - 如果 '<x>' 是一个 Angular 组件,那么验证它是这个模块的一部分

javascript - typescript 和 Redux : Why do I need to add ` | undefined` to my Reducer state type?

javascript - ESLint 在 src 文件中寻找配置(以默认方式配置)

javascript - 无法使用 Vue 打包库加载 CSS 文件(npm)

ReactJs 中的 CSS Modules + Ant 设计不起作用

angular - 在 Angular 组件之间共享字符串