Webpack help - add hot loading and source mapping

2019-09-16 16:52发布

I'm a webpack newbie. I'm trying to add React to a simple Node project but I've only ever used React with a pre set up webpack dev server and not with another server. Webpack runs it's own node server so this poses one problem for me.

Here's what I need help with:

  1. How do I add hot loading and source mapping if I'm using Express?
  2. How can I add a global Bootstrap css from my public folder with webpack to this project (is there a way to do that kinda of how I did this with the js files and html-webpack-plugin)?

I've tried using webpack's dev server to get get hot loading but I've run into the problem where I have two servers conflicting: webpack and app.js server.

Here's part of my app.js file

var app = module.exports = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public')));

//API Routes

// all other requests
app.get('*', function(req, res) {
  res.sendFile(path.join(__dirname, 'dist', 'index.html'));
});

// Starting server
http.createServer(app).listen(port);

.babelrc

{
  "presets": [
    "react",
    "es2015",
    "stage-0"
  ]
}

webpack.config.babel

import webpack from 'webpack'

var HtmlWebpackPlugin = require('html-webpack-plugin')
var HTMLWebpackPluginConfig = new HtmlWebpackPlugin({
  template: __dirname + '/public/index.html',
  filename: 'index.html',
  inject: 'body'
})

const base = {
  entry: {
    "jquery": __dirname + '/public/js/lib/jquery/jquery-2.0.3.min.js',
    "bootstrap": __dirname + '/public/bootstrap/js/bootstrap.min.js',
    "index": __dirname + '/app',
  },
  output: {
    path: __dirname + '/dist',
    filename: '[name].js',
  },
  module: {
    loaders: [
      {test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader'},
      {test: /\.css$/, loader: 'style!css?sourceMap&modules&localIdentName=[name]__[local]___[hash:base64:5]'}
    ]
  },
}

const developmentConfig = {
  devtool: 'cheap-module-inline-source-map',
  plugins: [HTMLWebpackPluginConfig]
}

export default Object.assign({}, base, developmentConfig)

I tried adding new ExtractTextPlugin("dist/[name].css") to plugins and replacing my css loader with loader: ExtractTextPlugin.extract("style-loader", "css-loader") but I'm still not able to add bootstrap css or any css to my app.

1条回答
疯言疯语
2楼-- · 2019-09-16 17:23

Notice in your webpack.config.babel file you have this output:

  output: {
    path: __dirname + '/dist',
    filename: '[name].js',
  },

You need to put this [name].js file in your dist/index.html.

This blog post might be helpful for you for getting yourself properly set up!

查看更多
登录 后发表回答