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

Preact无法加载preact.config.js文件的问题求助

Preact CLI 3.5.0构建及配置加载问题解决思路

问题背景

使用Preact开发应用,package.json脚本配置如下:

"scripts": {
    "build": "cross-env NODE_OPTIONS=--openssl-legacy-provider preact build",
    "serve": "sirv build --cors --single",
    "dev": "cross-env NODE_OPTIONS=--openssl-legacy-provider preact watch",
    "lint": "eslint src",
    "test": "jest"
  },

此前npm run dev运行正常,首次执行npm run build时出现以下警告:

WARN Failed to load preact-cli config file, using default!
Function.prototype.apply was called on undefined, which is a undefined and not a function

preact.config.js存放路径正确,之前watch模式可正常识别该配置,但build模式无法加载;重装依赖后watch模式也失效,已在配置中添加的OTF文件加载器无法生效,Preact无法解析OTF文件。

preact.config.js内容如下:

/* eslint-disable @typescript-eslint/no-var-requires */
const path = require('path');

export default function (config, env, helpers) {
    // Add a new rule for .otf fonts
    config.module.rules.push({
      test: /\.otf$/,
      loader: 'file-loader',
      options: {
        name: '[name].[ext]',
        outputPath: 'fonts/',
        publicPath: '/fonts/',
      },
    });

    // Add an alias for 'phaser' to point to the non-ESM build
    config.resolve.alias['phaser'] = path.resolve(__dirname, 'node_modules/phaser/dist/phaser.js');
    config.resolve.alias['@legion/shared'] = path.resolve(__dirname, '../shared/');


    let babelLoader = helpers.getLoadersByName(config, 'babel-loader')[0].rule;
    babelLoader.exclude = /node_modules\/phaser/;
}

当前使用的Preact CLI版本为3.5.0。

解决思路

  • 修正配置文件导出方式:Preact CLI 3.x版本不支持ES模块的export default语法,需改用CommonJS规范的module.exports。将export default function (...)替换为module.exports = function (...),解决配置文件加载失败问题。
  • 完善babel-loader获取逻辑:helpers.getLoadersByName(config, 'babel-loader')[0]可能返回undefined,导致后续访问.rule触发报错。添加判断逻辑确保获取到有效loader后再修改配置:
    const babelLoaderEntry = helpers.getLoadersByName(config, 'babel-loader')[0];
    if (babelLoaderEntry) {
      babelLoaderEntry.rule.exclude = /node_modules\/phaser/;
    }
    
  • 确认file-loader依赖存在:重装依赖后可能丢失file-loader,执行npm install file-loader --save-dev确保该依赖已安装。
  • 调整Node.js版本或OpenSSL配置:使用NODE_OPTIONS=--openssl-legacy-provider说明当前Node.js版本(v17+)的OpenSSL与Preact CLI 3.5.0存在兼容性问题,可尝试降级Node.js到v16或更低版本,规避legacy provider带来的潜在异常。
  • 清理构建缓存:执行npx preact clean清理旧构建缓存,再运行npm run build,避免缓存导致的配置不生效问题。

内容的提问来源于stack exchange,提问作者jerorx

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 12:22:26