我按照 webpack 的官方入门说明设置了一个小测试项目和配置文件。正如他们推荐的那样,我使用带有 webpack 中间件的快速服务器。
设置
server.js
:
const express = require('express');
const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');
const app = express();
const config = require('./webpack.config.js');
const compiler = webpack(config);
// Tell express to use the webpack-dev-middleware and use the webpack.config.js
// configuration file as a base.
app.use(
webpackDevMiddleware(compiler, {
publicPath: config.output.publicPath,
})
);
// Serve the files on port 3000.
app.listen(3000, function () {
console.log('Example app listening on port 3000!\n');
});
我的目录文件夹如下所示:
- dist/
- assets/
- css/
- bundle.index.html
- bundle.about.html
- index.html
- about.html
- src/
- fonts/
- images/
- sass/
- templates/
- about.html
- index.html
- ts/
- abstracts/
- utils/
- pages/
- about.ts
- index.ts
这是我的webpack.config
(为此删除了不必要的项目)。
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
module.exports = {
mode: mode,
entry: {
index: './src/ts/pages/index.ts',
about: './src/ts/pages/about.ts',
},
output: {
filename: 'bundle.[name].js',
path: path.resolve(__dirname, './dist'),
clean: true,
publicPath: '.',
assetModuleFilename: 'assets/[name][ext][query]',
},
devServer: {
port: 3000,
sockPort: 3000,
contentBase: path.resolve(__dirname, 'dist'),
},
plugins: [
new HtmlWebpackPlugin({
title: 'Index',
filename: 'index.html',
template: 'dist/index.html',
chunks: ['index'],
}),
new HtmlWebpackPlugin({
title: 'about',
filename: 'about.html',
template: 'dist/about.html',
chunks: ['about'],
}),
],
module: {
rules: [
{
test: /\.html$/i,
loader: "html-loader",
},
// Support von versch. Grafiktypen
{
test: /\.(png|svg|jpg|jpeg|gif)$/i,
type: 'asset/resource',
generator: {
filename: './assets/images/[name][ext][query]'
}
},
// Support von Fonts
{
test: /\.(woff|woff2|eot|ttf|otf)$/i,
type: 'asset/resource',
generator: {
filename: './assets/fonts/[name][ext][query]'
}
},
],
},
resolve: {
extensions: ['.ts'],
alias: {
Style: path.resolve(__dirname, './src/sass'),
Fonts: path.resolve(__dirname, './src/fonts'),
Images: path.resolve(__dirname, './src/images'),
}
}
};
问题
在我的浏览器中运行localhost:3000
,快递返回Cannot get /
。
在我的浏览器中运行localhost:3000
,快递返回Cannot get / index.html
。
在我的浏览器中运行localhost:3000/dist/index.html
,快递返回Cannot get dist/index.html
。
简单地说,我不能接受任何东西。为什么?我的配置说该
dist
目录应该用作根目录。
devServer: {
port: 3000,
sockPort: 3000,
contentBase: path.resolve(__dirname, 'dist'),
},