Skip to content

support for webpack 5 #126

Description

@Mamba-working

The Issues page for this repository is not a support forum, it is for reporting potential bugs in this module, which
composes webpack-hot-middleware and webpack-dev-middle for use with koa2.
If you have arrived here because you cannot get webpack-hot-middleware
or webpack-dev-middleware working, please review the documentation
for the respective middleware you are experiencing a problem with. If you proceed with this form, please fill out all fields, or your issue may be closed as "invalid." Please remove this header to acknowledge this message.

  • Node Version: 12.14.0
  • NPM Version: 6.13.4
  • koa Version: 2.13.0
  • koa-wepback Version: 6.0.0

If you have a large amount of code to share which demonstrates the problem you're experiencing, please provide a link to your
repository rather than pasting code. Otherwise, please paste relevant short snippets below.

// webpack.config.base.js

const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
const HappyPack = require('happypack');

module.exports = {
context: path.join(__dirname, '..'),
resolve: {
extensions: ['.js', '.jsx', '.ts', '.tsx'],
alias: {
src: path.join(__dirname, '..', 'src'),
'@component': path.join(__dirname, '..', 'src', 'component'),
'@pages': path.join(__dirname, '..', 'src', 'pages'),
'@utils': path.join(__dirname, '..', 'src', 'utils'),
'@assets': path.join(__dirname, '..', 'src', 'assets'),
},
},
entry: {
guide: ['src/Guide.tsx'],
index: ['src/index.tsx'],
},
module: {
rules: [
{
test: /.(js|jsx|ts|tsx)$/,
include: [path.join(__dirname, '..', 'src')],
exclude: [/node_modules/],
use: ['happypack/loader?id=babel'],
},
{
test: /.css$/,
use: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
},
],
},
{
test: /.less$/,
use: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
},
{
loader: 'less-loader',
options: {
lessOptions: {
modifyVars: { 'primary-color': '#1890ff' },
javascriptEnabled: true,
},
},
},
],
},
{
test: /.(jpe?g|png|gif|swf|woff2?|eot|ttf|otf)$/,
use: [
{
loader: 'url-loader',
options: {
limit: 1024 * 5,
name: 'static/img/[name].[hash].[ext]',
},
},
],
},
{
test: /.svg$/,
use: ['@svgr/webpack'],
},
],
},
optimization: {
splitChunks: {
cacheGroups: {
commons: {
test: /node_modules/,
name: 'vendors',
chunks: 'all',
},
},
},
},
plugins: [
new webpack.IgnorePlugin(/^./locale$/, /moment$/),
new webpack.optimize.SplitChunksPlugin(),
new ForkTsCheckerWebpackPlugin(),
new HtmlWebpackPlugin({
filename: 'guide.html',
template: path.join(__dirname, '', 'index.html'),
chunks: ['guide'],
}),
new HtmlWebpackPlugin({
filename: 'index.html',
template: path.join(__dirname, '', 'index.html'),
chunks: ['index'],
}),
new HappyPack({
/*
* 必须配置
*/
// id 标识符,要和 rules 中指定的 id 对应起来
id: 'babel',
loaders: [
{
loader: 'babel-loader',
options: require('./babel.config'),
},
],
}),
],
};
//webpack.dev.js

const webpack = require('webpack');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
const ProgressBarPlugin = require('progress-bar-webpack-plugin');
const WebpackBuildNotifierPlugin = require('webpack-build-notifier');
const ManifestPlugin = require('webpack-manifest-plugin');

const merge = require('webpack-merge');
const base = require('./webpack.base');

const webpackConfig = merge(base, {
  mode: 'development',
  devtool: 'source-map',
  output: {
    path: '/',
    publicPath: '/',
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify('development'),
    }),
    new BundleAnalyzerPlugin({ openAnalyzer: false, analyzerPort: 'auto' }),
    new ProgressBarPlugin(),
    new WebpackBuildNotifierPlugin({
      title: 'DNSPod 平台',
    }),
    new ManifestPlugin(),
  ],
});

module.exports = webpackConfig;
// app.js
const app = new Koa<any, IContext>();
const PORT = process.env.PORT || 8080;
const createServer = (port: number | string) => {
  const server = app.listen(port);
  server.addListener('error', err => {
    if ((err as any).code === 'EADDRINUSE') {
      console.log('\n' + port + '端口被占领, 更换端口为' + (Number(port) + 1) + '\n');
      createServer(Number(port) + 1);
    }
  });
  server.addListener('listening', () => {
    console.log('服务运行在 http://127.0.0.1:' + port + '🤡' + '\n');
  });
};

async function start() {
  const compiler = webpack(webpackConfig);
  try {
    const middleware = await koaWebpack({
      compiler,
      hotClient: {
        hmr: true,
        allEntries: true,
      },
      devMiddleware: {
        publicPath: webpackConfig?.output?.publicPath || '',
        stats: 'minimal',
      },
    });
    app.use(middleware);
    app.use(async (context, next) => {
      context.devMiddleware = middleware.devMiddleware;
      await next();
    });
    app.use(async (context, next) => {
      if (context.url.startsWith('/guide')) {
        context.response.type = 'html';
        context.response.body = context.devMiddleware.fileSystem.readFileSync('/guide.html');
        return;
      }
      await next();
    });
    app.use(async context => {
      context.response.type = 'html';
      context.response.body = context.devMiddleware.fileSystem.readFileSync('/index.html');
    });
    createServer(PORT);
  } catch (e) {
    console.log(e);
  }
}

start();

image

It console error below.

Is there any plan to support webpack 5

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions