Webpack - Include file multiple times

旧巷老猫 提交于 2021-02-10 06:38:50

问题


I want to include a file twice through two different loaders. The reasoning is I want to display code snippets in ES6 while allowing them to be run in browsers not supporting the syntax.

Effectively what I would like to achieve is the below but with both loaders results being included in the output -

{
    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',
        }
      }
    ]
  }

With the above in my webpack config

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

results in

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

Rather than the code run through babel as I would have hoped for.


回答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' },
      ]))
    },
  ]
}

This should do the trick. you have to also use combineLoaders as you have to use options object. inside combine loaders array you can pass loader configuration also.




回答2:


I couldn't manage to handle this with loaders in the end - although with further reading I don't believe this was the correct approach anyway. Instead i'm now using copy-webpack-plugin to copy the files -

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"
    }
  ]
}


来源:https://stackoverflow.com/questions/53252846/webpack-include-file-multiple-times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!