Webpack4 を使って webpack-dev-server のベーシック設定

More than 1 year has passed since last update.


経緯

本番用には webpack-cli でビルドして、開発環境では webpack-dev-server というあるあるなビルドの仕組みを作った時に、 webpack-dev-server では dist ができずにちょっと悩んだので、簡単に記載しました。

webpack4 もまだあまり試していなかったので、ついでにと思ってやってみました。


code


package.json

{

"name": "sample",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "rm -rf dist && NODE_ENV=development webpack-dev-server --open --config ./webpack.config.js --hot --inline",
"build": "rm -rf dist && NODE_ENV=production webpack --mode production"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^7.1.4",
"babel-preset-env": "^1.7.0",
"copy-webpack-plugin": "^4.5.1",
"webpack": "^4.8.3",
"webpack-cli": "^2.1.3",
"webpack-dev-server": "^3.1.4",
"write-file-webpack-plugin": "^4.3.1"
}
}



webpack.config.js

const path              = require('path');

const webpack = require('webpack');
const WriteFilePlugin = require('write-file-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');

const NODE_ENV = process.env.NODE_ENV;

module.exports = {
context: path.resolve( __dirname, './src'),

mode : NODE_ENV || 'production',

devServer: {
port: 3000,
contentBase: path.resolve( __dirname , './dist' )
},

entry: {
bundle : [ './js/index.js' ]
},

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

module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: { presets: ['env'] }
}
]
}
]
},

resolve: {
extensions: ['.js', '.jsx'],
},

plugins: [
new WriteFilePlugin(),
new CopyWebpackPlugin( [
{ from: '*.html', to: path.resolve( __dirname , './dist' ) }
]),
new webpack.DefinePlugin({
'NODE_ENV': JSON.stringify( NODE_ENV ),
})
]
}



今後

sass もコンパイルする設定を足したいので、今度余裕がある時にでも。