webpack与nodejs一起使用

时间:2017-08-14 10:04:12

标签: node.js reactjs webpack

我是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中使用此配置。请帮忙

4 个答案:

答案 0 :(得分:5)

首先,您的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 - 观看文件

答案 1 :(得分:2)

我的建议:

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

字体的输出路径为 ./ public / assets / fonts

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

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

答案 2 :(得分:1)

我不知道这是否会有所帮助,但我认为你想做反过来的事情:

  1. 在Webpack.config文件(Webpack)中创建配置。
  2. 你的webpack文件就是Node服务器(Express)。
  3. 您的服务器返回您的字体结尾文件(React)。
  4. 您可以在此post中了解有关webpack的一些信息。

答案 3 :(得分:0)

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

&#13;
&#13;
var webpack = require('webpack')

var config = require('./your_config')

var compiler = webpack(config)

compiler.run(function(err, stats){
   console.log(err, stats)
})
&#13;
&#13;
&#13;

使用&#34;节点webpackConfig.js&#34;

运行