我什至无法获得 webpack 的 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 视为一个黑匣子。
答案 0 :(得分:2)
Webpack 不会用 "helloworld" 替换 DUMMYVARIABLE
变量,因为您没有将其定义为 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;
}());