包含/排除不起作用

Ser*_*gey 5 webpack

网络包 2.2.0

我在我的配置中包含/排除文件/文件夹,但 webpack 一直捆绑被排除的:

文件夹结构

src/
  index.js // entry point
server/
  test.js // file for testing
build/
Run Code Online (Sandbox Code Playgroud)

webpack.config.js

const path = require('path')
const SRC = path.resolve(process.cwd(), './src')
const BUILD = path.resolve(process.cwd(), './build')

module.exports = {
  context: SRC,
  entry: {
    main: './'
  },
  output: {
    path: BUILD,
    filename: '[name].bundle.js',
    publicPath: '/assets/'
  },
  module: {
    rules: [{
      test: /\.jsx?/,
      include: SRC,
      exclude: path.resolve(process.cwd(), './server’), // even explicit excluding changes nothing
      loader: 'babel-loader'
    }]
  }
}
Run Code Online (Sandbox Code Playgroud)

./src/index.js

import func from ‘../server/test.js’ // this must not be imported
func() // working
Run Code Online (Sandbox Code Playgroud)

./server/test.js

export default function () { console.log(`I’m in the bundle`) } // this is being executed
Run Code Online (Sandbox Code Playgroud)

我在浏览器控制台中看到了消息。

Ser*_*gey 5

答案是,如果你include/exclude在 webpack 配置中添加了某些内容,它不会被加载器转换,但会被导入到包中。要从捆绑中完全排除某些内容,您需要使用module.noParse选项: https: //webpack.js.org/configuration/module/#module-noparse

  • 这个答案似乎并不完全正确——“module.noParse”并没有“从捆绑中排除[...]”。根据链接的文档,它主要是跳过模块的_parsing_的性能优化。它仍然是捆绑的,只是没有解析。要从包中“排除”模块,您需要使用 [`IgnorePlugin`](https://webpack.js.org/plugins/ignore-plugin/)。根据文档,“IgnorePlugin”将“阻止为给定的正则表达式生成模块”。 (7认同)