【问题标题】:webpack using with nodejswebpack 与 nodejs 一起使用
【发布时间】:2018-01-22 03:32:24
【问题描述】:

我是 reactjs 的新手。我刚开始学习reactjs。我在 nodejs 中使用 webpack 时遇到问题。我想创建将运行 webpack 文件的节点服务器。我有 webpack 文件:

const {resolve} = require('path');
const webpack = require('webpack');
const validate = require('webpack-validator');
const {getIfUtils, removeEmpty} = require('webpack-config-utils');

module.exports = env => {
  const {ifProd, ifNotProd} = getIfUtils(env)

  return validate({
    entry: './index.js',
    context: __dirname,
    output: {
      path: resolve(__dirname, './build'),
      filename: 'bundle.js',
      publicPath: '/build/',
      pathinfo: ifNotProd(),
    },
    devtool: ifProd('source-map', 'eval'),
    devServer: {
      port: 8080,
      historyApiFallback: true
    },
    module: {
      loaders: [
        {test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader'},
        {test: /\.css$/, loader: 'style-loader!css-loader'},
        {test: /(\.eot|\.woff2|\.woff|\.ttf|\.svg)/, loader: 'file-loader'},
      ],
    },
    plugins: removeEmpty([
      ifProd(new webpack.optimize.DedupePlugin()),
      ifProd(new webpack.LoaderOptionsPlugin({
        minimize: true,
        debug: false,
        quiet: true,
      })),
      ifProd(new webpack.DefinePlugin({
        'process.env': {
          NODE_ENV: '"production"',
        },
      })),
      ifProd(new webpack.optimize.UglifyJsPlugin({
        sourceMap: true,
        compress: {
          screw_ie8: true, // eslint-disable-line
          warnings: false,
        },
      })),
    ])
  });
};

如何在 nodejs 中使用此配置。请帮忙

【问题讨论】:

  • Webpack 是一个代码打包器,它可以在开发环境中工作。使用webpack通常的流程是将所有文件打包到本地,然后当所有文件准备好后,在服务器端不使用webpack部署到服务器。
  • 你在 webpack.config.js 文件中做的太多了。如果在生产中,让你的服务器指向另一个 webpack 文件,否则让它使用 webpack.dev.config.js 文件。 app.js 文件中的 github.com/christian4423/express_blog 显示了解决此问题的可靠方法。

标签: node.js reactjs webpack


【解决方案1】:

我不知道这是否会有所帮助,但我认为你想反其道而行之:

  1. 在 Webpack.config 文件中创建您的配置 (Webpack)。
  2. 您的 webpack 文件启动 Node 服务器 (Express)。
  3. 您的服务器返回您的字体结束文件 (React)。

您可以在post 中了解有关 webpack 的一些信息。

【讨论】:

    【解决方案2】:

    试试这个。将此代码保存在 webpackConfig.js 中

    var webpack = require('webpack')
    
    var config = require('./your_config')
    
    var compiler = webpack(config)
    
    compiler.run(function(err, stats){
       console.log(err, stats)
    })

    使用“node webpackConfig.js”运行

    【讨论】:

      【解决方案3】:

      我的建议:

      package.json 脚本(安装 webpack(-g 和 –save-dev)、nodemon(-g 和 –save-dev)并同时安装(–save-dev))

        "scripts": {
          "webpack-watch-client": "webpack -w",
          "server": "nodemon server",
          "dev": "concurrently --kill-others \"npm run webpack-watch-client\" \"npm run server\""
        }
      

      webpack.config.js 示例

      'use strict'
      
      const path = require('path');
      
      const PATHS = {
        app: path.join(__dirname, 'src'),
        public: path.join(__dirname, 'public')
      };
      
      
      module.exports = {
        entry: {
          app: PATHS.app,
        },
        output: {
          path: PATHS.public,
          filename: 'js/bundle.js'
        },
        devtool: 'source-map',
        module: {
          rules: [
            {
              test: /\.(js|jsx)$/,
              exclude: /node_modules/,
              use: [
                {
                  loader: 'babel-loader',
                  options: {
                    presets: ['react', 'es2015']
                  }
                }
              ]
            },
            {
              test: /\.css$/,
              use: [
                { loader: 'style-loader' },
                { loader: 'css-loader' }
              ]
            },
            {
              test: /\.(woff|woff2|eot|ttf)$/,
              use: [
                {
                  loader: 'file-loader',
                  options: {
                    outputPath: 'assets/fonts/'
                  }
                }
              ]
            },
            {
              test: /\.(png|jpg|gif|svg)$/,
              use: [
                {
                  loader: 'file-loader',
                  options: {
                    outputPath: 'assets/img/'
                  }
                }
              ]
            }
          ]
        },
       plugins: [
      // plugins
        ]
      };
      

      节点服务器起点是./server.js

      React 客户端起点是 ./src/index.js

      输出路径 ./public 包含 index.html 行:

        <div id="root"></div>
        <script type="text/javascript" src="/js/bundle.js" charset="utf-8"></script>
      

      bundle.js 的输出路径是 ./public/js

      fonts 的输出路径是 ./public/assets/fonts

      图片的输出路径是./public/assets/img

      开始:npm run dev(监听端口在server.js中定义)

      等等

      【讨论】:

        【解决方案4】:

        首先你的 webpack 配置不会在 webpack 2+ 上运行,因为 webpack-validator 已被弃用,所以我将其删除。我建议您全局安装 npm install webpack-dev-server -g 并将其用作您的反应开发中的服务器。这是您可以修改配置以使用它的方式 (webpack.config.js):

        const path = require("path");
        const webpack = require('webpack');
        const {getIfUtils, removeEmpty} = require('webpack-config-utils');
        
        module.exports = env => {
          const {ifProd, ifNotProd} = getIfUtils(env)
        
          return {
            entry: [
              "webpack-dev-server/client?http://localhost:3003",
              "webpack/hot/only-dev-server",
              "react-hot-loader/patch"
            ],
            context: __dirname,
            output: {
              path: path.join(__dirname, './build'),
              filename: 'bundle.js',
              publicPath: '/build/',
              pathinfo: ifNotProd(),
            },
            devtool: ifProd('source-map', 'eval'),
            devServer: {
                contentBase: path.join(__dirname, "src"),
                // enable HMR
                hot: true,
                // embed the webpack-dev-server runtime into the bundle
                inline: true,
                // serve index.html in place of 404 responses to allow HTML5 history
                historyApiFallback: true,
                port: 3003
            },
            module: {
              loaders: [
                {test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader'},
                {test: /\.css$/, loader: 'style-loader!css-loader'},
                {test: /(\.eot|\.woff2|\.woff|\.ttf|\.svg)/, loader: 'file-loader'},
              ],
            },
            plugins: removeEmpty([
            //...
            // same as before
            //...
            ])
          };
        };
        

        package.json

        {
          ...
          "dependencies": {},
          "devDependencies": {
            "babel-core": "^6.26.0",
            "babel-loader": "^7.1.2",
            "react-hot-loader": "^3.1.1",
            "webpack": "^3.8.1",
            "webpack-config-utils": "^2.3.0",
            "webpack-dev-server": "^2.9.4",
          }
        }
        

        在 webpack.config.js 所在的同一文件夹中创建一个文件 webpack.development.js,它只会设置环境:

        var config = require('./webpack.config.js')
        
        module.exports = config("development"); // can be "production" or "development"
        

        文件结构:

        root
            build
                bundle.js
            src
                index.html
            index.js
            package.json
            webpack.config.js
            webpack.development.js
        

        最后运行它: webpack-dev-server --config webpack.development.js --progress -p --hot -w

        --hot - 将运行服务器, -w - 观看文件

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-12-05
          • 2017-12-09
          • 2020-10-05
          • 2017-10-02
          • 2016-01-27
          • 1970-01-01
          相关资源
          最近更新 更多