如何在Ember项目中读取VERSION文件内容到environment.js?
Hey there! I get where you're coming from—your Node.js approach makes total sense, but the issue with your jQuery attempt is a classic "wrong environment" problem. Let's fix this step by step.
Why your current approach fails
The $.getJSON call throws an error because environment.js runs during the build process in a Node.js context, not in the browser. jQuery isn't available here (it's a browser-side library), so $ is undefined—hence the "unexpected identifier" error.
The correct way (using Node.js modules, just like your intuition)
Since Ember CLI is built on Node.js, you can directly use Node's core fs and path modules in environment.js—just like you would in a regular Node script. Here's how to do it properly:
- First, import the required Node modules at the top of
client/config/environment.js:
const fs = require('fs'); const path = require('path');
- Then, in your
ENVobject, add the version usingfs.readFileSync, with a safe path constructed viapath.join(to avoid cross-OS path separator issues):
module.exports = function(environment) { const ENV = { // ... other environment variables ... version: fs.readFileSync(path.join(__dirname, '../../VERSION'), 'utf8').trim() }; // ... other environment-specific config ... return ENV; };
Key notes:
path.join(__dirname, '../../VERSION')ensures the path to your root-level VERSION file is correct, no matter what OS you're working on.- The
'utf8'argument tellsreadFileSyncto return a string instead of a buffer, so you don't need to call.toString()explicitly (though it still works if you do). .trim()removes any extra newlines or whitespace from the VERSION file content—super useful if the file has a trailing newline.- Remember: this reads the VERSION file at build time. If you update the VERSION file later, you'll need to restart your Ember dev server or run a new build to pick up the change.
That's it! This should work exactly like your Node.js approach, but tailored to Ember's build process.
内容的提问来源于stack exchange,提问作者Will Daniels

