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

如何编写适配Webpack的Node Modules路径正则表达式

Webpack正则匹配@ng-select/ng-option-highlight路径报错解决方案

问题描述

我的node_modules目录下存在路径为C:\myProject\node_modules\@ng-select\ng-option-highlight的库,需要编写适配Webpack的正则表达式指向该路径。目前我使用的正则是/node_modules\/@ng-select/,但尝试添加ng-option-highlight时触发Webpack报错:

发生未处理的异常:无效的正则表达式标志

我的Webpack配置文件如下:

const webpack = require('webpack');
const TerserPlugin = require("terser-webpack-plugin");
const linkerPlugin = require("@angular/compiler-cli/linker/babel");
const path = require('path');
module.exports = {
    /**
     * 移除所有未使用的MomentJS本地化文件
     * 问题详情见此文章
     * https://medium.jonasbandi.net/angular-cli-and-moment-js-a-recipe-for-disaster-and-how-to-fix-it-163a79180173
     */
    plugins: [
        new webpack.ContextReplacementPlugin(/moment[/\\]locale$/, /de|en|fr|it/),
    ],
    module: {
        rules: [
            {
                include: /node_modules/,
                test: /\.mjs$/,
                type: 'javascript/auto'
            }
        ]
    },
    plugins: [
        new webpack.DefinePlugin({
            ngDevMode: true,
        }),
        new webpack.LoaderOptionsPlugin({
            options: {
                rules: [
                    {
                      test: /.*\.d.ts$/,
                      include: /node_modules\/@ng-select/,
                      use: {
                        loader: 'babel-loader',
                        options: {
                          configFile: false,
                          plugins: [linkerPlugin],
                        }
                      }
                    }
                ]
            }
        })
    ],
}

正确正则写法

报错是因为修改正则时格式出错(比如误把逗号写到正则内部,或者未正确处理路径分隔符),针对目标路径,推荐两种正确写法:

  • 写法1(简洁,适配Webpack默认路径格式):

    include: /node_modules\/@ng-select\/ng-option-highlight/
    
  • 写法2(兼容Windows反斜杠和Unix正斜杠,更严谨):

    include: /node_modules[/\\]@ng-select[/\\]ng-option-highlight/
    

修改后的完整规则

把配置中LoaderOptionsPlugin内的对应规则替换为以下内容即可:

{
  test: /.*\.d.ts$/,
  include: /node_modules[/\\]@ng-select[/\\]ng-option-highlight/,
  use: {
    loader: 'babel-loader',
    options: {
      configFile: false,
      plugins: [linkerPlugin],
    }
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 22:40:29