Search code examples
asp.net-coreasp.net-core-2.2

Copy entire folder to wwwroot using MSBuild task


I have the following:

<Target Name="OnBuild" BeforeTargets="Build" Condition="'$(Configuration)' == 'Debug'">
  <Exec WorkingDirectory="app" Command="npm install" />
  <Exec WorkingDirectory="app" Command="npm run build" />
</Target>

The command "npm run build" creates the folder "client/dist".

How to copy the folder and its contentto "wwwroot" with a MSBuild task?

I am using ASP.NET Core 2.2 ...

Webpack.config

const path = require('path');

const environment = process.env.NODE_ENV;

const CopyPlugin = require('copy-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');

module.exports = {

  plugins: [
    new MiniCssExtractPlugin({
      filename: 'main.min.css',
    }),
    new CopyPlugin([
      { from: './assets', to: './assets' }
    ])
  ],

  resolve: {
    extensions: ['.js'],
  },

  entry: path.resolve(__dirname, 'src/app/index.js'),  

  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'main.min.js'
  },

  optimization: {
    minimizer: [
      new MiniCssExtractPlugin({}),
      new OptimizeCSSAssetsPlugin({}),      
      new UglifyJsPlugin({
        cache: true,
        parallel: true,
        sourceMap: false
      })
    ]
  },

  module: {
    rules: [
      {
        test: /\.less$/,
        use: [ MiniCssExtractPlugin.loader, 'css-loader', 'less-loader' ]
      },
      {
        test: /\.(png|svg|jpg|gif)$/,
        use: [ 'file-loader' ]
      },
      {
        test: /\.(otf|eot|ttf|woff|woff2)$/,
        use: [ 'file-loader' ]
      }
    ]
  },

  watch: true

};

Solution

  • You can use this and modify RelativePath for the desired relative path:

    <!-- Include the newly-built files in the publish output -->
    <ItemGroup>
      <DistFiles Include="$(SpaRoot)build\**" />
      <ResolvedFileToPublish Include="@(DistFiles->'%(FullPath)')" Exclude="@(ResolvedFileToPublish)">
        <RelativePath>wwwroot/%(RecursiveDir)%(Filename)%(Extension)</RelativePath>
        <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
        <ExcludeFromSingleFile>true</ExcludeFromSingleFile>
      </ResolvedFileToPublish>
    </ItemGroup>