使用Webpack将src文件夹结构保存到dist文件夹中?

时间:2018-06-25 18:57:51

标签: javascript webpack

我正在研究Webpack,并且正面临这个问题。 当我运行构建任务“ npm run build”时,webpack将创建dist文件夹。问题在于dist文件夹不尊重src文件夹,而Webpack将所有文件放入根文件夹(dist文件夹)。所以我在样式文件和所有图像附近都有* .html页面。我想要dist内的html文件,img内的图像(dist内的img)等等...

这是我的webpack.config.js文件:

const path = require('path');
const HtmlWebPackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');

module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
  },
  module: {
    rules: [{
      test: /\.js$/,
      exclude: /node_modules/,
      use: {
        loader: 'babel-loader',
      },
    },
    {
      test: /\.html$/,
      use: [{
        loader: 'html-loader',
        options: {
          minimize: true,
        },
      }],
    },
    {
      test: /\.(css|scss)$/,
      use: [
        MiniCssExtractPlugin.loader,
        {
          loader: 'css-loader',
          options: {
            importLoaders: 1,
            sourceMap: true,
            url: false,
            minimize: true,
          },
        },
        {
          loader: 'postcss-loader',
          options: {
            sourceMap: true,
          },
        },
        {
          loader: 'sass-loader',
        },
      ],
    },
    {
      test: /\.(png|svg|jpg|gif)$/,
      use: [{
        loader: 'file-loader',
        options: {
          name: '[name].[ext]',
        },
      }],
    },
    ],
  },
  plugins: [
    new HtmlWebPackPlugin({
      template: './src/index.html',
      filename: 'index.html',
    }),
    new HtmlWebPackPlugin({
      template: './src/work.html',
      filename: 'work.html',
    }),
    new MiniCssExtractPlugin({
      filename: '[name].[hash].css',
    }),
    new CleanWebpackPlugin(['dist']),
  ],
};

我在Internet上找到了一些东西,但是所有解决方案都没有用。 也许我做错了什么?请帮助我。

1 个答案:

答案 0 :(得分:2)

  ...
  module: {
    rules: [
     ...
    {
      test: /\.(png|svg|jpg|gif)$/,
      use: [{
        loader: 'file-loader',
        options: {
          name: 'img/[name].[ext]',
        },
      }],
    },
    ],
  },
  plugins: [
    ...
    new MiniCssExtractPlugin({
      filename: 'styles/[name].[contenthash].css',
    }),
  ],
};

您只需在名称中添加路径