I'm having difficulty getting even a token example of webpack's DefinePlugin
working. That is, npx webpack
runs just fine, but the output js files don't have the defined tokens replaced. Here's my minimal (non-)working example:
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;
}
}
The output js file (note that DUMMYVARIABLE is still present, rather than being replaced by 'helloworld'
as expected):
/******/ (() => { // 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
As far as I can tell, it's critical to have a file called tsconfig.json, but its contents matter less – at the moment I just have {}
in there.
Can someone help me understand where I'm going wrong and how to get DefinePlugin
to work for me?
Hope you'll forgive my rookie webpack-ness, I've been able to treat webpack as a black box previously.
Webpack doesn't replace the DUMMYVARIABLE
variable with "helloworld" because you didn't defined it as global variable . To make your example work you need to add a declare
:
declare var DUMMYVARIABLE: string;
export class IndexModel {
public static GetDummyVariable(): string {
return DUMMYVARIABLE;
}
}
Now the webpack.DefinePlugin
would replace the occurences like so:
var IndexModel = /** @class */ (function () {
function IndexModel() {
}
IndexModel.GetDummyVariable = function () {
return "helloworld";
};
return IndexModel;
}());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.