问题背景
我有 webpack 用于将我的打字稿编译成 javascript。当我更改我的打字稿代码时,自动重新加载工作。但是,webpack 并没有看我的静态 html 文件。
.
├── dist
│ ├── index.html
│ └── style.css
├── src
│ └── index.ts
└── webpack.config.js
问题是我需要在我的index.html
和 webpack 中进行一些更改并不会自动检测这些更改。而且,如果我刷新 html 页面,它似乎会破坏 webpack 的 webpack-dev-server。
预期产出
我希望所有内容都在src
文件夹中,并且当我运行时,我的文件夹webpack
中有一个完全正常工作的静态站点dist
。那是:
. .
├── dist ├── dist
├── src │ ├── index.html
│ ├── index.html │ ├── bundle.js
│ ├── index.ts npx webpack -> │ └── style.css
│ └── style.css ├── src
└── webpack.config.js │ ├── index.html
│ ├── index.ts
│ └── style.css
└── webpack.config.js
文件dist
夹中的文件可能具有散列文件名。不过,我现在不担心这一步。我希望 webpack 会检查我的文件并确保它们链接到正确的资源。因此,如果 webpack 要给出style.css
一个散列名称,href inindex.html
将被更新。
电流输出
我当前的解决方案同时输出index.html
和bundle.js
,但我无法将其复制style.css
到dist
文件夹中。我的当前webpack.config.js
看起来像这样:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
module.exports = {
entry: './src/index.ts',
devtool: 'inline-source-map',
mode: 'development',
devServer: {
contentBase: './dist'
},
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
},
{
test: /\.css$/,
use: [
'style-loader',
'css-loader'
]
},
{
test: /\.html$/,
use: [
{ loader: 'file-loader?name=[name].[ext]' },
{ loader: 'extract-loader' },
{ loader: 'html-loader' }
]
}
]
},
plugins: [
new CleanWebpackPlugin()
],
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
我的index.html
样子是这样的:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>stuff</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<script src="./bundle.js" charset="utf-8"></script>
</body>
</html>
我的index.ts
包含:
import './index.html';
我试过的
起初,我尝试将我的 css 的导入添加到我的index.ts
:
import './style.css';
但这没有用。接下来我查看了 html-loader 文档,它似乎暗示了我正在寻找的内容:
但是,我已经读过这样的内联加载程序已被弃用,并且查看源代码似乎没有任何插值的配置选项。无论如何,我尝试按照文档中的描述进行操作,但它要么根本不起作用,要么给我一些关于
require
未找到的错误消息(尽管我似乎无法重现该错误)。我的index.html
包含:
<link rel="stylesheet" href="${require(`style.css`)">
并index.ts
包含:
require("html-loader?interpolate=require!./index.html");
如何让 webpack 将我的移动style.css
到 dist 文件夹?
我有预感我误解了 webpack 应该如何使用。当我有工作时,我可以在代码审查堆栈交换上发布我的 webpack 配置,以获得创建更惯用的 webpack 配置的帮助吗?