WebPack準備の手順20230326版

現時点でよく使うWebPackの設定等をメモしておく。

npm i -D webpack webpack-cli webpack-dev-server html-webpack-plugin copy-webpack-plugin css-loader style-loader url-loader raw-loader

webpack.config.js

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

const outputPath	= path.resolve( __dirname, 'dist' );

module.exports = {
  context: __dirname,
  entry: {
    index	: path.join( __dirname, 'src', 'index.js' )
  },
  output: {
    filename: 'bundle.js',
    path: outputPath,
    sourcePrefix: '',
  },
  module: {
    rules: [{
      test: /\.css$/,
      use: [ 'style-loader', 'css-loader' ]
    }, {
      test: /\.(png|gif|jpg|jpeg|svg|xml)$/,
      use: [ 'url-loader' ]
    }, {
      test: /\.(vs|fs|glsl)$/,
      use: [ 'raw-loader' ]
    }]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: path.join( __dirname, 'src', 'index.html' )
    }),
    // new CopywebpackPlugin({ patterns:[{ from: path.join(__dirname, 'src', 'img'), to: 'img' }] }),
  ],
  resolve:	{
  },
  mode: 'development',
  devServer	: {
    static	: {
      directory	: outputPath
    },
    open	: {
      app	: {
        name	: 'firefox'
      }
    },
    port	: 3001
  }
};

package.json

  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack --mode=production --config webpack.config.js",
    "start": "webpack --watch --config webpack.config.js & webpack-dev-server"
  },

package.json変更

上記の記述だとstart内で&でコマンドをつなぐ形式がWindowsで動作しない。

  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack --mode=production --config webpack.config.js",
    "start": "webpack serve --config webpack.config.js"
  },