See output.filename
configuration, you are allowed to use something like 'js/[name]/bundle.js'
to create a folder structure.
The filename
of MiniCssExtractPlugin
works like output.filename
.
In order to simplify the configuration, the following example does not use ts-loader
and sass-loader
as they do not affect the build output.
Project structure(after building):
$ tree -L 4 -I node_modules
.
├── package-lock.json
├── package.json
├── public
│ ├── index.html
│ └── success
│ ├── script
│ │ └── index.js
│ └── style
│ └── style.css
├── src
│ ├── index.html
│ ├── index.js
│ └── style.css
└── webpack.config.js
src/index.js
:
import './style.css';
console.log('webpack mini template');
src/index.html
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
</body>
</html>
src/style.css
:
body {
background: green;
}
webpack.config.js
:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
entry: path.resolve(__dirname, './src/index.js'),
mode: 'development',
output: {
path: path.resolve(__dirname, './public/'),
filename: 'success/script/index.js',
clean: true,
},
module: {
rules: [
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, 'css-loader'],
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: path.resolve(__dirname, './src/index.html'),
inject: 'body',
}),
new MiniCssExtractPlugin({ filename: 'success/style/style.css' }),
],
};
Build logs:
> webpack
asset success/script/index.js 3.23 KiB [emitted] (name: main)
asset index.html 357 bytes [emitted]
asset success/style/style.css 242 bytes [emitted] (name: main)
Entrypoint main 3.46 KiB = success/style/style.css 242 bytes success/script/index.js 3.23 KiB
orphan modules 2.76 KiB (javascript) 937 bytes (runtime) [orphan] 7 modules
runtime modules 274 bytes 1 module
cacheable modules 111 bytes (javascript) 29 bytes (css/mini-extract)
./src/index.js 61 bytes [built] [code generated]
./src/style.css 50 bytes [built] [code generated]
css ./node_modules/css-loader/dist/cjs.js!./src/style.css 29 bytes [built] [code generated]
webpack 5.88.2 compiled successfully in 203 ms
Output:
public/index.html
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link href="success/style/style.css" rel="stylesheet"></head>
<body>
<script defer src="success/script/index.js"></script></body>
</html>
package.json
:
{
"version": "1.0.0",
"scripts": {
"build": "webpack"
},
"devDependencies": {
"css-loader": "^6.8.1",
"html-webpack-plugin": "^5.5.3",
"mini-css-extract-plugin": "^2.7.6",
"webpack": "^5.80.0",
"webpack-cli": "^5.0.2"
}
}