簡體   English   中英

使用Express和Babel在React應用程序中配置Webpack

[英]Webpack configuration in React application with express and babel

我正在使用React版本^ 15.6.1開發一個React應用程序,該版本使用Webpack,Express和Babel和Yarn作為包管理器。

我的應用程序運行良好,現在可以使用Webpack和CSS將應用程序投入生產並將js編譯為bundle.js,並使用快速版本^ 4.15.3配置服務器以創建開發和生產版本。

到目前為止,我已經創建了一個webpack.config.js文件,如下所示:

const path = require('path');

const HtmlWebpackPlugin = require('html-webpack-plugin');

const webpack = require('webpack');


const config = {
    entry: ['babel-polyfill', './src/index.js'],
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'bundle.js'
    },
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                exclude: /node_modules/,
                use: 'babel-loader'
            }
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: 'index.html',
            filename: 'index.html',
            inject: 'body'
        })
  ]
};

module.exports = config;

一個具有以下代碼的server.js文件:

const express = require('express');
const app = express();

app.use(express.static(__dirname + '/src'));

app.listen(3000, function () {
  console.log('server on port 3000');
});

這是我的package.json文件的腳本部分:

"scripts": {
    "start": "node server.js",
    "dev": "node server.js webpack -w",
    "build": "webpack -p --progress --config ./webpack.prod.config.js"
  },

我遇到的問題是,當我在訪問網頁時以當前的server.js文件設置運行yarn start ,出現“ Cannot GET /但是當我不使用server.js文件而運行yarn start以我的package.json中的以下腳本:

"start": "webpack-dev-server"

項目文件夾結構:

/dist
    bundle.js
    index.html
/node_modules
/src
    /assets
        /styles
            carousel.css
            slider.css
/components
    App.js
    App.js.map
    App.jsx
      index.js
      index.js.map
.babelrc
.eslintrc.js
.gitignore
index.html
package.json
server.js
web pack.config.js
yarn.lock
yarn-error.log

我的網頁加載完全正常,但dist文件夾未使用預期的bundle.js文件創建。 放入該文件的bundle.js文件和index.html文件僅在我運行yarn build時出現

我想了解為什么會這樣? 如果我在當前設置中有任何錯誤需要調整,以便可以使用webpack和babel運行Express服務器進行開發和生產。

您的server.js文件存在一些問題,它看起來應該更像這樣

app.use(express.static(__dirname + 'dist'));

app.get('/', function (req, res) {
   res.sendFile(__dirname + 'dist/index.html', {root: __dirname})
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM