webpack与express同时使用,开发环境怎样配置express能够让路由都走前端

发布于 2022-09-04 11:52:18 字数 5784 浏览 12 评论 0

// webpack.config.js
**/* build/webpack.config.js */
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const path = require('path');
const debug = require('debug')('webpack:config');

console.log(path.join(__dirname + '/app/main.js'));
const publicPath = 'http://127.0.0.1:8000/';
const appEntry = {
    App: [
        'webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000',
        path.join(__dirname + '/app/main.js')
    ],
    vendor: [
        'react',
        'react-router',
        'react-redux',
        'redux',
        'reqwest'
    ]
};
debug('start bundle...')
const config = {
    entry: appEntry,
    output: {
        filename: '[name].js',
        path: path.join(__dirname, '/dist/'),
        publicPath: publicPath
    },
    resolve: {
        extensions: ['.web.js', '.ts', '.tsx', '.js']
    },
    module: {
        loaders: [
            {
                test: /\.(js|jsx)$/,
                exclude: /node_modules/,
                loader: 'babel-loader'
                // query: {
                //     cacheDirectory: true,
                //     plugins: [[
                //         'import',
                //         {
                //             'libraryName': 'antd',
                //             'style': true
                //         }
                //     ], 'transform-runtime'],
                //     presets: ['es2015', 'react', 'stage-0'],
                // }
            }, {
                test: /\.json$/,
                loader: 'json-loader',
            },
            {
                test: /\.tsx?$/,
                loader: 'babel-loader!ts-loader',
                exclude: /node_modules/,
            },
            {
                test: /\.css/,
                loader: ['style-loader', 'css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]']
            },
            {
                test: /\.less$/,
                loader: 'style-loader!css-loader!less-loader'
            },
            {
                test: /\.woff(\?.*)?$/,
                loader: 'url?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=application/font-woff'
            },
            {
                test: /\.woff2(\?.*)?$/,
                loader: 'url?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=application/font-woff2'
            },
            { test: /\.otf(\?.*)?$/, loader: 'file?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=font/opentype' },
            {
                test: /\.ttf(\?.*)?$/,
                loader: 'url?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=application/octet-stream'
            },
            { test: /\.eot(\?.*)?$/, loader: 'file?prefix=fonts/&name=[path][name].[ext]' },
            { test: /\.svg(\?.*)?$/, loader: 'url?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=image/svg+xml' },
            { test: /\.(png|jpg)$/, loader: 'url?limit=8192' }
        ]
    },
    plugins: [
        new webpack.HotModuleReplacementPlugin(),
        new webpack.NoErrorsPlugin(),
        new HtmlWebpackPlugin({
            template: path.join(__dirname, '/server/view/index.html'),
            hash: false,
            filename: 'index.html',
            inject: 'body',
            minify: {
                collapseWhitespace: true,
            }
        }),
        new webpack.optimize.CommonsChunkPlugin({
            names: ['vendor'],
        })
    ],
    devServer: {
        historyApiFallback: {
            disableDotRule: true
        }
    },
    devtool: 'source-map'
}

module.exports = config;
// server.js
// 依赖项
const express = require('express');
const path = require('path');
const webpack = require('webpack');
const history = require('connect-history-api-fallback');
const webpackMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');
const proxy = require('express-http-proxy');
const debug = require('debug')('app:server');

const config = require('./webpack.config.js');
const isDeveloping = process.env.NODE_ENV !== 'production';
const port = isDeveloping ? 8000 : process.env.PORT;

const app = express();

if (isDeveloping) {
    debug('测试环境 --> express use webpackHotMiddleware & webpackMiddleware ')
    const compiler = webpack(config);
    const middleware = webpackMiddleware(compiler, {
        publicPath: config.output.publicPath,
        contentBase: path.join(__dirname, '/app'),
        stats: {
            colors: true,
            hash: false,
            timings: true,
            chunks: false,
            chunkModules: false,
            modules: false
        }
    });
    app.use(middleware);
    app.use(webpackHotMiddleware(compiler));
    app.use(express.static('statics'));
    app.use(history());
    // app.get('*', function response(req, res) {
    //     res.sendFile(path.join(__dirname + '/server/view/index.html'));
    // });
} else {
    app.use(express.static(__dirname + '/dist'));
    // app.get('*', function response(req, res) {
    //     res.sendFile(path.join(__dirname, 'dist/index.html'));
    // });
}
app.all('/api/*', proxy('http://api.ilovelook.cn'));

app.listen(port, function onStart(err) {
    if (err) {
        console.log(err);
    }
    console.info(`Listening on port ${port}. Open up http://localhost:${port}/ in your browser.`);
});

我本来想给express设置所有路由都走webpack HtmlWebpackPlugin生成的html,但是发现HtmlWebpackPlugin并没有生成出来html...所以现在来求一下解决方案

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

仲春光 2022-09-11 11:52:18

看vue模板的配置有类似的情况

// handle fallback for HTML5 history API
app.use(require('connect-history-api-fallback')())
掩于岁月 2022-09-11 11:52:18

我也遇到同样的问题了,请问你是怎么解决的呢?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文