I want to have the current commit hash on both my dev and prod env which can getable with /version
path.
My webpack config:
//webpack.config.js
...
const commitHash = require('child_process').execSync('cd .. && git rev-parse --short HEAD', {encoding: 'utf8'}).trim();
module.exports = {
mode: 'production',
target: 'node',
...
plugins: [
new webpack.DefinePlugin({
'COMMIT_HASH': commitHash,
})
]
};
My nodejs server:
//server.js
...
fastify.get('/version', function (request, reply) {
const version = process.env.NODE_ENV === "dev" ?
require('child_process').execSync('cd .. && git rev-parse --short HEAD', {encoding: 'utf8'}).trim() : COMMIT_HASH;
reply.send(version);
})
...
And my problem is that when i build it with webpack i get the SyntaxError: Identifier directly after number
and
server.js from Terser plugin
Invalid syntax: 3511a4a [webpack://./server.js:214,104]
where the line 214 is the require('child_process')...
.
BUT
if i change the webpack config to const commitHash = 'a3511a4a';
everything is fine and the build is successful. And if i change it to const commitHash = '3511a4a';
the error comes again.
Webpack version is 5.64.2
CodePudding user response:
Because the plugin does a direct text replacement, the value given to it must include actual quotes inside of the string itself. Typically, this is done either with alternate quotes, such as '"3511a4a"', or by using JSON.stringify('3511a4a').