如何从Webpack构建中删除.test.js文件

huangapple go评论133阅读模式
英文:

How to remove .test.js files from webpack build

问题

I need to remove all the .test.js files from my React project.
I am getting errors after building the app.

> 模块解析失败:意外的标记 <br />
> 你可能需要一个适当的加载器来处理这种文件类型,目前没有配置加载器来处理这个文件。
<br /> 如果我移除 rules 并将其改为只有 exclude: /node_modules/,错误就会消失,但 BundleAnalyzerPlugin 仍然显示 .test.js 文件,所以我认为 webpack 没有将它们移除。

<h4>当前的 Webpack 配置</h4>

module.exports = {
  devtool: false,
  mode: 'production',
  entry: {
    app: [path.join(config.srcDir, 'index.js')],
  },
  optimization: {
    moduleIds: 'named',
    chunkIds: 'named',
    minimize: true,
    nodeEnv: 'production',
    mangleWasmImports: true,
    removeEmptyChunks: false,
    mergeDuplicateChunks: false,
    flagIncludedChunks: true,
    minimizer: [`...`, 
    new CssMinimizerPlugin({
      minimizerOptions: {
        preset: [
          "default",
          {
            calc: false,
            discardComments: { removeAll: true },
          },
        ],
      },
    }),
    '...'],
    emitOnErrors: true,
    splitChunks: {
      chunks: 'all',
      minSize: 20000,
      minRemainingSize: 0,
      minChunks: 1,
      maxAsyncRequests: 30,
      maxInitialRequests: 30,
      enforceSizeThreshold: 50000,
      cacheGroups: {
        defaultVendors: {
          test: /[\\/]node_modules[\\/]/,
          priority: -10,
          reuseExistingChunk: true,
        },
        default: {
          minChunks: 2,
          priority: -20,
          reuseExistingChunk: true,
        },
      },
    },
  },
  output: {
    filename: '[name].bundle.js',
    chunkFilename: '[name].chunk.js',
    path: config.distDir,
    publicPath: BASE_PATH,
  },
  resolve: {
    fallback: { "querystring": false },
    modules: ['node_modules', config.srcDir],
    alias: {
      path: require.resolve('path-browserify'),
      Components: path.resolve(__dirname, '../app/components'),
      Context: path.resolve(__dirname, '../app/context'),
      Images: path.resolve(__dirname, '../app/images'),
      Plugins: path.resolve(__dirname, '../plugins'),
      Redux: path.resolve(__dirname, '../app/redux'),
      Routes: path.resolve(__dirname, '../app/routes'),
      Styles: path.resolve(__dirname, '../app/styles'),
      Utils: path.resolve(__dirname, '../app/utils'),
    },
  },
  plugins: [
    new CircularDependencyPlugin({
      exclude: /a\.js|node_modules/,
      failOnError: true,
      allowAsyncCycles: false,
      cwd: process.cwd(),
    }),
    new HtmlWebpackPlugin({
      template: config.srcHtmlLayout,
      inject: 'body',
      title: 'AdminUI',
    }),
    new MiniCssExtractPlugin(),
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify('production'),
        BASE_PATH: JSON.stringify(BASE_PATH),
        API_BASE_URL: JSON.stringify(API_BASE_URL),
        CONFIG_API_BASE_URL: JSON.stringify(CONFIG_API_BASE_URL),
        SESSION_TIMEOUT_IN_MINUTES: JSON.stringify(SESSION_TIMEOUT_IN_MINUTES),
      },
    }),
    new PurgeCSSPlugin({ paths: glob.sync(`${PATHS.src}/**/*`,  { nodir: true }) }),
    new webpack.IgnorePlugin({
      resourceRegExp: /\.test\.js$/,
    }),
    new BundleAnalyzerPlugin(),
  ],
  module: {
    rules: [
      {
        test: /\.js$/,
        include: [config.srcDir, config.pluginsDir],
        exclude: /(node_modules|\.test\.js$)/,
        use: 'babel-loader',
        sideEffects: false,
      },
      // 模块化样式
      {
        test: /\.css$/i,
        use: [MiniCssExtractPlugin.loader, "style-loader", "css-loader", "postcss-loader"]
      },
      {
        test: /\.scss$/,
        use: [
          MiniCssExtractPlugin.loader,
          {
            loader: 'css-loader',
            options: {
              modules: true,
            },
          },
          { loader: 'postcss-loader' },
          'sass-loader',
        ],
        exclude: [path.resolve(config.srcDir, 'styles')],
        include: [config.srcDir],
      },
      {
        test: /\.scss$/,
        use: [
          MiniCssExtractPlugin.loader,
          { loader: 'css-loader' },
          { loader: 'postcss-loader' },
          {
            loader: 'sass-loader',
            options: {},
          },
        ],
        include: [path.resolve(config.srcDir, 'styles')],
      },
      // 字体
      {
        test: /\.(ttf|eot|woff|woff2)$/,
        loader: 'file-loader',
        options: {
          name: '/fonts/[name].[ext]',
          esModule: false,
        },
      },
      // 文件
      {
        test: /\.(jpg|jpeg|png|gif|svg|ico)$/,
        loader: 'file-loader',
        options: {
          name: '/static/[name].[ext]',
          esModule: false,
        },
      },
    ],
  },
  devServer: {
    hot: false,
    //contentBase: config.distDir,
    compress: true,
    historyApiFallback: {
      index: BASE_PATH,
    },
    host: '0.0.0.0',
    port: 4100,
  },
}
英文:

I need to remove all the .test.js files from my React project.
I am getting errors after building the app.

> Module parse failed: Unexpected token <br />
> You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file.
<br /> If I remove the rules and change it to just exclude: /node_modules/ the error goes away but the BundleAnalyzerPlugin still displays the .test.js files so I assume the webpack didn't removed them.

<h4>Current Webpack Config</h4>

module.exports = {
  devtool: false,
  mode: &#39;production&#39;,
  entry: {
    app: [path.join(config.srcDir, &#39;index.js&#39;)],
  },
  optimization: {
    moduleIds: &#39;named&#39;,
    chunkIds: &#39;named&#39;,
    minimize: true,
    nodeEnv: &#39;production&#39;,
    mangleWasmImports: true,
    removeEmptyChunks: false,
    mergeDuplicateChunks: false,
    flagIncludedChunks: true,
    minimizer: [`...`, 
    new CssMinimizerPlugin({
      minimizerOptions: {
        preset: [
          &quot;default&quot;,
          {
            calc: false,
            discardComments: { removeAll: true },
          },
        ],
      },
    }),
    &#39;...&#39;],
    emitOnErrors: true,
    splitChunks: {
      chunks: &#39;all&#39;,
      minSize: 20000,
      minRemainingSize: 0,
      minChunks: 1,
      maxAsyncRequests: 30,
      maxInitialRequests: 30,
      enforceSizeThreshold: 50000,
      cacheGroups: {
        defaultVendors: {
          test: /[\\/]node_modules[\\/]/,
          priority: -10,
          reuseExistingChunk: true,
        },
        default: {
          minChunks: 2,
          priority: -20,
          reuseExistingChunk: true,
        },
      },
    },
  },
  output: {
    filename: &#39;[name].bundle.js&#39;,
    chunkFilename: &#39;[name].chunk.js&#39;,
    path: config.distDir,
    publicPath: BASE_PATH,
  },
  resolve: {
    fallback: { &quot;querystring&quot;: false },
    modules: [&#39;node_modules&#39;, config.srcDir],
    alias: {
      path: require.resolve(&#39;path-browserify&#39;),
      Components: path.resolve(__dirname, &#39;../app/components&#39;),
      Context: path.resolve(__dirname, &#39;../app/context&#39;),
      Images: path.resolve(__dirname, &#39;../app/images&#39;),
      Plugins: path.resolve(__dirname, &#39;../plugins&#39;),
      Redux: path.resolve(__dirname, &#39;../app/redux&#39;),
      Routes: path.resolve(__dirname, &#39;../app/routes&#39;),
      Styles: path.resolve(__dirname, &#39;../app/styles&#39;),
      Utils: path.resolve(__dirname, &#39;../app/utils&#39;),
    },
  },
  plugins: [
    new CircularDependencyPlugin({
      exclude: /a\.js|node_modules/,
      failOnError: true,
      allowAsyncCycles: false,
      cwd: process.cwd(),
    }),
    new HtmlWebpackPlugin({
      template: config.srcHtmlLayout,
      inject: &#39;body&#39;,
      title: &#39;AdminUI&#39;,
    }),
    new MiniCssExtractPlugin(),
    new webpack.DefinePlugin({
      &#39;process.env&#39;: {
        NODE_ENV: JSON.stringify(&#39;production&#39;),
        BASE_PATH: JSON.stringify(BASE_PATH),
        API_BASE_URL: JSON.stringify(API_BASE_URL),
        CONFIG_API_BASE_URL: JSON.stringify(CONFIG_API_BASE_URL),
        SESSION_TIMEOUT_IN_MINUTES: JSON.stringify(SESSION_TIMEOUT_IN_MINUTES),
      },
    }),
    new PurgeCSSPlugin({ paths: glob.sync(`${PATHS.src}/**/*`,  { nodir: true }) }),
    new webpack.IgnorePlugin({
      resourceRegExp: /\.test\.js$/,
    }),
    new BundleAnalyzerPlugin(),
  ],
  module: {
    rules: [
      {
        test: /\.js$/,
        include: [config.srcDir, config.pluginsDir],
        exclude: /(node_modules|\.test\.js$)/,
        use: &#39;babel-loader&#39;,
        sideEffects: false,
      },
      // Modular Styles
      {
        test: /\.css$/i,
        use: [MiniCssExtractPlugin.loader, &quot;style-loader&quot;, &quot;css-loader&quot;, &quot;postcss-loader&quot;]
      },
      {
        test: /\.scss$/,
        use: [
          MiniCssExtractPlugin.loader,
          {
            loader: &#39;css-loader&#39;,
            options: {
              modules: true,
            },
          },
          { loader: &#39;postcss-loader&#39; },
          &#39;sass-loader&#39;,
        ],
        exclude: [path.resolve(config.srcDir, &#39;styles&#39;)],
        include: [config.srcDir],
      },
      {
        test: /\.scss$/,
        use: [
          MiniCssExtractPlugin.loader,
          { loader: &#39;css-loader&#39; },
          { loader: &#39;postcss-loader&#39; },
          {
            loader: &#39;sass-loader&#39;,
            options: {},
          },
        ],
        include: [path.resolve(config.srcDir, &#39;styles&#39;)],
      },
      // Fonts
      {
        test: /\.(ttf|eot|woff|woff2)$/,
        loader: &#39;file-loader&#39;,
        options: {
          name: &#39;/fonts/[name].[ext]&#39;,
          esModule: false,
        },
      },
      // Files
      {
        test: /\.(jpg|jpeg|png|gif|svg|ico)$/,
        loader: &#39;file-loader&#39;,
        options: {
          name: &#39;/static/[name].[ext]&#39;,
          esModule: false,
        },
      },
    ],
  },
  devServer: {
    hot: false,
    //contentBase: config.distDir,
    compress: true,
    historyApiFallback: {
      index: BASE_PATH,
    },
    host: &#39;0.0.0.0&#39;,
    port: 4100,
  },
}

FYI, I am using webpack 5.x

答案1

得分: 0

`exclude` 属性用于指定任何与模式 `/test\.js$/` 匹配的文件应该被排除在 webpack 构建之外。这应该可以阻止 test.js 文件被包含在输出的捆绑包中。请注意,exclude 属性使用正则表达式模式来匹配文件名,因此您需要使用反斜杠来转义任何特殊字符(比如点号)。

module.exports = {
// ... 其他配置选项
module: {
rules: [
{
test: /.js$/,
exclude: /test.js$/, // 排除所有文件名为 test.js 的文件
use: ['babel-loader']
}
]
}
}

英文:

exclude property to specify that any files matching the pattern /test\.js$/ should be excluded from the webpack build. This should prevent test.js files from being included in the output bundle.

Note that the exclude property uses a regular expression pattern to match file names, so you'll need to escape any special characters (like the dot) using a backslash.

module.exports = {
  // ... other config options
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /test\.js$/, // exclude any files with the name test.js
        use: [&#39;babel-loader&#39;]
      }
    ]
  }
}


答案2

得分: 0

By adding ignore-loader in the rules I was able to solve the error and remove .test.js files from the build.

{
  "test": /\.test\.js$/,
  "include": [config.srcDir, config.pluginsDir],
  "use": "ignore-loader"
}
英文:

By adding ignore-loader in the rules I was able to solve the error and remove .test.js files from the build.

      {
        test: /\.test\.js$/,
        include: [config.srcDir, config.pluginsDir],
        use: &#39;ignore-loader&#39;,
      }
    

</details>



huangapple
  • 本文由 发表于 2023年5月7日 22:15:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76194468.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定