我在尝试使用webpack的DefinePlugin
时遇到了困难。也就是说,npx webpack
命令可以正常运行,但是输出的js文件中未替换定义的token。以下是我最简单的(非)工作示例:
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'),
})
],
}
Index.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当作一个黑盒子来使用。
index.ts
示例的第1行中,您有var DUMMYVARIABLE:string;
。这将在作用域中创建一个名为DUMMYVARIABLE
的变量。当Webpack看到定义了DUMMYVARIABLE
,它决定不替换它。相反,如果您使用declare var DUMMYVARIABLE:string;
,则告诉TypeScript它是什么类型的变量,但不告诉Webpack。因此,当Webpack浏览您的代码并未找到定义的DUMMYVARIABLE
时,它将使用您在webpack.DefinePlugin
中指定的内容进行替换。---回复有点啰嗦,但希望能帮到您。 - Swivel