K
K
Kirill Tekord2018-04-28 21:52:22
npm
Kirill Tekord, 2018-04-28 21:52:22

How to copy assets from node_modules to public directory using gulp or webpack?

I am developing an application in PHP, I am a dinosaur in front-end development. I have several libraries connected via npm. I need to copy some folders from node_modules to the project's public/assets folder while maintaining the subfolder structure. An example of folders that I want to copy:
- node_modules\vue\dist\
- node_modules\bootstrap\dist\
I want to get the following structure at the output:
- public/assets/vue/dist
- public/assets/bootstrap/dist
Tell me how to do this using gulp or webpack, preferably by purely available means, without additional plugins.
And what are the general practices for publishing assets? Basically, I meet assembly in just 1 file, examples are full of plugins, tutorials were written in different years and due to the rapid development of tools, the code presented there often does not work, so I have difficulty learning.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Igor Zabrodin, 2018-04-28
@Rapt0p7

An example of part of the configuration for webpack version 4 (but also works on the previous ones):

output: {
    path: resolve(__dirname, './dist'),
    publicPath: mode === 'development' ? '/' : 'static/',
    filename: '[name].js'
  },
  module: {
    rules: [
      {
        test: /\.(png|jpg|jpeg|gif|svg|woff|ico|woff2|ttf|eot)(\?.*$|$)/,
        loader: 'file-loader',
        exclude: /node_modules/,
        options: {
          name: '[path][name].[ext]?[hash]',
          publicPath: mode === 'development' ? '' : './static'
        }
      },
      {
        test: /\.(png|jpg|jpeg|gif|svg)(\?.*$|$)/,
        loader: 'file-loader',
        options: {
          regExp: /node_modules/,
          name: '[name].[ext]?[hash]',
          publicPath: mode === 'development' ? '' : './static/img',
          outputPath: 'static/img'
        }
      }
    ]
  }

The first loader is for own assets, the second one is for node_modules.
In my case, it was necessary to move the static and get the correct paths for it in css from this (without the second loader):
{
  background: transparent url(./static/_/node_modules/fancybox/dist/img/blank.gif);
}

Into this:
{
  background: transparent url(./static/img/blank.gif);
}

This configuration is simple, there are not many statics, and I didn’t have a task to somehow optimize it (use url-loader, for example, separate fonts and graphics, etc.).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question