Reputation: 2000
I am trying to serve static assets from webpack, but am right now using the copywebpack plugin to copy any desired static assets into my static_dist/ directory, which is also where my build files go. While this hack works, I now also need to serve stats file that is generated after the build process, stats.json. I cannot hack this and use copywebpackplugin, because this file does not yet exist when the copywebpackplugin runs. I am a bit overwhelmed by all of webpacks configuration options, and nothing seems to work for serving these static files.
// my webpack.config.js
const PATHS = {
app: path.join(__dirname, '../src/static'),
build: path.join(__dirname, '../src/static_dist')
};
const basePath = path.resolve(__dirname, '../src/static/');
module.exports = {
mode: 'development',
devtool: 'cheap-module-eval-source-map',
output: {
filename: '[name].js',
path: PATHS.build,
publicPath: '/static/'
},
devServer: {
watchOptions: {
aggregateTimeout: 300,
ignored: /node_modules/,
poll: 1000,
},
port: 3000,
contentBase: '/static/',
host: '0.0.0.0',
disableHostCheck: true,
historyApiFallback: { index: '/static/index.html' },
public: 'localhost:8000',
writeToDisk: true,
// hot: true
},
plugins: [
new CopyPlugin([
{ from: '../static/assets/img/favicons', to: '../static_dist/favicons' },
{ from: '../static/assets/img/logos', to: '../static_dist/logos' },
{ from: '../static/assets/img/icons', to: '../static_dist/icons'},
]),
new BundleTracker({ path: PATHS.build, filename: './stats/webpack-stats.json'})
],
}
Right now, my bundles are accessed at domain.com/static/app.[some-hash].js
and logos, for example, are accessed at domain.com/static/logos/somelogo.png
. It appears most people do not have these served from the same directory, but I don't particularly care where they are served from. Just that I can serve the stats file which is generated after the build.
Upvotes: 2
Views: 1191
Reputation: 10539
So you have to wait until webpack compile is done. You can write your own plugin using a webpack compiler-hook. This is an example script. Untestet!
// fs-extra to copy files (npm install fs-extra)
const fs = require('fs-extra');
const path = require('path');
// own plugin: do what ever
class MyPlugin {
apply(compiler) {
compiler.hooks.afterCompile.tap('MyPlugin', (compilation) => {
// copy all files and folder (recursive)
fs.copySync(path.resolve(process.cwd(), 'static/assets/img/favicons'), path.resolve(process.cwd(), 'static_dist/favicons'), { recursive: true })
// return true to emit the output, otherwise false
return true;
});
}
};
//...
// append your plugin to webpacks plugin section
plugins: [
//...
new MyPlugin(),
//...
]
Upvotes: 1