You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Webpack 5搭配dotenv遇解析错误:@字符无法正常处理

解决方案

问题出在webpack.DefinePlugin的配置逻辑上:你直接将dotenv.parsed赋值给process.env,但DefinePlugin本质是文本替换工具,它会把代码中的process.env.MY_SECRET直接替换成变量的原始值,不会自动添加字符串引号。这就导致模板字符串被替换后变成${@2022@89aou43i76h3rg5b2a9e235670fc0},而@不能作为JavaScript标识符的开头,最终触发语法错误。

修正Webpack配置

需要将每个环境变量的值用JSON.stringify()包裹,确保替换后的内容是合法的字符串字面量:

const path = require("path")
const webpack = require('webpack')
const dotenv = require('dotenv').config({
    path: path.join(__dirname, '.env')
})

// 处理环境变量,将每个值转为JSON格式的字符串
const envKeys = Object.keys(dotenv.parsed).reduce((prev, next) => {
  prev[`process.env.${next}`] = JSON.stringify(dotenv.parsed[next]);
  return prev;
}, {});

module.exports = {
    entry: {
        content: "./src/js/content-main.js",
        worker: "./src/js/worker-main.js"
    },
    mode: "production",
    resolve: {
        extensions: ['.js', '.jsx'],
    },
    module: {
        rules: [
        {
            test: /\.js?$/,
            exclude: /(node_modules)/,
            include: path.resolve(__dirname, "src"),
            use: {
            loader: "babel-loader"
            }
        },
        ]
    },
    plugins: [
        new webpack.DefinePlugin(envKeys),
    ],
}

原理说明

经过JSON.stringify()处理后,process.env.MY_SECRET会被替换为"@2022@89aou43i76h3rg5b2a9e235670fc0"(带双引号的合法字符串),模板字符串最终会变成console.log(${"@2022@89aou43i76h3rg5b2a9e235670fc0"}),符合JavaScript语法规范,Webpack和Babel就能正常解析。

额外提示

  • .env文件中变量值无需额外加引号,直接写MY_SECRET=@2022@89aou43i76h3rg5b2a9e235670fc0即可,dotenv会自动解析为字符串。
  • 可以为dotenv.config()添加错误检查,避免配置文件加载失败:
    if (dotenv.error) {
      throw dotenv.error;
    }
    

内容的提问来源于stack exchange,提问作者César Rodríguez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 08:27:39