Webpack + Babel正在转译Webpack加载器,我该如何防止这种情况发生?

3

我以为Webpack+Babel只会转换应用程序代码,不会转换用于Webpack构建的代码。然而,它似乎正在转换来自css-loadermini-css-extract-plugin等的代码,这导致了以下错误:

ERROR in ./styles/main.scss
Module build failed (from ../node_modules/mini-css-extract-plugin/dist/loader.js):
TypeError: __webpack_require__(...) is not a function

如果我将以下内容添加到exclude中,这个错误就会被修复:

  module: {
    rules: [
      {
        test: /\.(j|t)sx?$/,
        include: [APP_ROOT, path.resolve('./node_modules')],
        exclude: [
          path.resolve('./node_modules/mini-css-extract-plugin'),
          path.resolve('./node_modules/css-loader'),
        ],
        use: [
          'babel-loader',
        ],
      },
      ...

我认为不需要这个,因为 Babel 不应该对 Webpack 构建过程中使用的包进行转译。我将node_modules添加到include中,因为一些包使用的代码在旧版浏览器中无法正常工作。


你能提供一个重现这个问题的代码仓库吗? - Legends
3个回答

3
可能的原因与您规则中的包含选项有关,为什么不尝试将node_modules的引用放在解析选项中,这样webpack会查看已声明的入口并解析它需要解决的内容,但不包括声明的排除项进行转译。
entry: SRC_DIR + '/main.js',
resolve: {
    extensions: ['.js'],
    modules: [SRC_DIR, 'node_modules']
},
module: {
    rules: [
        {
            test: /\.js$/,
            exclude: /node_modules/,
            use: ['eslint-loader']
        }
    ]
}

我想要转译node_modules中的应用程序代码,这可以防止它被转译。一些包使用了更新的语法。 - Leo Jiang

0
尝试排除所有node_modules,只包含您实际需要转译的node_module资源。我打赌这将解决您的问题。

是的,这个方法可以行得通,但我必须弄清楚哪些包使用了新语法,据我所知,目前没有工具可以做到这一点。 - Leo Jiang

0

为了将项目文件夹中的特殊文件(如css、png、jpg或svg等)转换,需要使用特定的加载器。在转换过程中,它还会选择加载器文件,以便匹配和分析文件格式(如css)以检测错误。然后将其转换为最终的构建文件。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接