How to copy static files to build directory with Webpack?
Requiring assets using the file-loader module is the way webpack is intended to be used (source). However, if you need greater flexibility or want a cleaner interface, you can also copy static files directly using my copy-webpack-plugin
(npm, Github). For your static
to build
example:
const CopyWebpackPlugin = require('copy-webpack-plugin'); module.exports = { context: path.join(__dirname, 'your-app'), plugins: [ new CopyWebpackPlugin({ patterns: [ { from: 'static' } ] }) ]};
Compatibility note: If you're using an old version of webpack like webpack@4.x.x
, use copy-webpack-plugin@6.x.x
. Otherwise use latest.
You don't need to copy things around, webpack works different than gulp. Webpack is a module bundler and everything you reference in your files will be included. You just need to specify a loader for that.
So if you write:
var myImage = require("./static/myImage.jpg");
Webpack will first try to parse the referenced file as JavaScript (because that's the default). Of course, that will fail. That's why you need to specify a loader for that file type. The file- or url-loader for instance take the referenced file, put it into webpack's output folder (which should be build
in your case) and return the hashed url for that file.
var myImage = require("./static/myImage.jpg");console.log(myImage); // '/build/12as7f9asfasgasg.jpg'
Usually loaders are applied via the webpack config:
// webpack.config.jsmodule.exports = { ... module: { loaders: [ { test: /\.(jpe?g|gif|png|svg|woff|ttf|wav|mp3)$/, loader: "file" } ] }};
Of course you need to install the file-loader first to make this work.
If you want to copy your static files you can use the file-loader in this way :
for html files :
in webpack.config.js :
module.exports = { ... module: { loaders: [ { test: /\.(html)$/, loader: "file?name=[path][name].[ext]&context=./app/static" } ] }};
in your js file :
require.context("./static/", true, /^\.\/.*\.html/);
./static/ is relative to where your js file is.
You can do the same with images or whatever.The context is a powerful method to explore !!