Webpack-多次包含文件

时间:2018-11-11 20:19:19

标签: javascript webpack webpack-4 babel-loader webpack-file-loader

我想通过两个不同的加载器两次包含一个文件。原因是我想在ES6中显示代码片段,同时允许它们在不支持该语法的浏览器中运行。

我实际上想要实现的是以下内容,但是两个加载程序的结果都包含在输出中-

{
    test: /\.(js|jsx)$/,
    exclude: /node_modules/,
    loader: "babel-loader"
},
{
    test: /\.(js|jsx)$/,
    include: /app\/examples/,
    use: [
      {
        loader: "file-loader",
        options: {
          regExp: /app\/examples\/([^\/]+)\/([^\.]+)+\.jsx?$/,
          name: 'examples/[1]/[2].example',
        }
      }
    ]
  }

在我的webpack配置中使用

import example from '../../examples/simple/ex1'

结果

Module {default: "examples/simple/ex1.example", __esModule: true, Symbol(Symbol.toStringTag): "Module"}

而不是我希望的那样通过babel运行代码。

2 个答案:

答案 0 :(得分:1)

const multi = require('multi-loader');
const combineLoaders = require('webpack-combine-loaders');

module: {
  loaders: [
    {
      test: /\.(js|jsx)$/,
      exclude: /node_modules/,
      include: /app\/examples/,
      loader: multi(combineLoaders([
        { loader: 'file-loader' },
        { loader: 'babel-loader' },
      ]))
    },
  ]
}

这应该可以解决问题。您还必须使用CombineLoaders,就像必须使用options对象一样。在合并加载程序数组中,您还可以通过加载程序配置。

答案 1 :(得分:0)

最后我无法用装载机来处理这个问题-尽管进一步阅读后,我仍然不认为这是正确的方法。相反,我现在正在使用copy-webpack-plugin复制文件-

plugins: [
  new CopyWebpackPlugin([ {
    from: path.join(rootDir, 'app', 'examples'),
    to: path.join(outputDir, 'examples')
  }])
],
module: {
  rules: [
    {
      test: /\.(js|jsx)$/,
      exclude: /node_modules/,
      loader: "babel-loader"
    }
  ]
}