Vue.js使用webpack.DefinePlugin时遇"Invalid or unexpected token"错误求助
Hey there! Since you're new to Node and process.env, let's walk through why you're hitting that "Invalid or unexpected token" error and how to fix it so you can use your login credentials in store.js.
First: Check Your env.js File Syntax
That error almost always points to a syntax mistake in your env file. Make sure your env.js is exporting variables correctly—no missing commas, mismatched quotes, or invalid syntax. Here's the right way to structure it:
// env.js module.exports = { loginEmail: "your-username@example.com", loginPassword: "your-secure-password" };
Double-check for typos here—even a missing comma after loginEmail can throw that token error.
Second: Correctly Configure Webpack's DefinePlugin
Next, let's make sure your webpack.base.conf.js is properly injecting these variables into process.env. You need to use webpack's built-in DefinePlugin to expose the env variables globally. Here's how to set it up:
// webpack.base.conf.js const webpack = require('webpack'); // Import your env config (adjust the path if your env.js is in a different folder) const envVariables = require('./env.js'); module.exports = { // ... your existing webpack config (entry, output, module rules, etc.) plugins: [ // Add this plugin to inject env variables into process.env new webpack.DefinePlugin({ 'process.env': JSON.stringify(envVariables) }) ] };
Important note: JSON.stringify is crucial here. Without it, webpack will try to inject the raw object code, which causes syntax errors—this is probably the main issue you're facing!
Third: Verify No Other Syntax Errors in Webpack Config
Scan your webpack.base.conf.js for any missing brackets, commas, or misplaced code. For example, if you forgot a comma after an existing plugin, that could trigger the same token error.
Fourth: Test the Setup
Once you've fixed the above, restart your dev server. Now you should be able to access the variables in store.js or your components like this:
// store.js console.log(process.env.loginEmail); // Should log your email // Use the variables for authentication logic const validateCredentials = (email, password) => { return email === process.env.loginEmail && password === process.env.loginPassword; };
Quick Security Reminder
Don't forget to add env.js to your .gitignore file! You never want to commit sensitive credentials like passwords to version control.
内容的提问来源于stack exchange,提问作者Terje Nygård

