webpack打包的资源放到body里
时间: 2023-08-12 12:08:52 浏览: 42
可以通过在 webpack 配置中使用 html-webpack-plugin 插件来实现将打包生成的资源文件自动插入到 HTML 文件的 body 中。
首先需要安装 html-webpack-plugin:
```bash
npm install html-webpack-plugin --save-dev
```
然后在 webpack 配置文件中添加以下代码:
```javascript
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
//...其他配置
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html',
inject: 'body'
})
]
};
```
其中,template 指定了 HTML 文件模板路径,inject 设置为 'body' 表示将打包生成的资源文件插入到 body 标签中。这样,在运行 webpack 打包后,生成的 HTML 文件中就会自动引入打包生成的 js 和 css 文件,并放在 body 标签中。
相关问题
webpack 打包图片放到images文件夹
要把 webpack 打包的图片放到 images 文件夹,你可以通过配置 webpack 的 `output` 属性来实现。具体步骤如下:
1. 在 webpack 配置文件中添加 `output` 属性,指定打包后的图片输出路径为 `images/`:
```js
module.exports = {
// 其他配置项
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
publicPath: '/',
// 图片输出路径
assetModuleFilename: 'images/[hash][ext][query]'
}
}
```
其中,`assetModuleFilename` 属性的设置可以让 webpack 将图片文件输出到指定的路径。
2. 在你的代码中使用图片时,需要使用 `import` 或 `require` 导入图片文件,如下所示:
```js
import myImage from './path/to/image.png';
const img = document.createElement('img');
img.src = myImage;
document.body.appendChild(img);
```
这样,webpack 就会将图片文件打包到 `images/` 目录下,并在代码中使用打包后的文件路径。
react webpack 打包public里所有的静态资源
要使用Webpack打包public里所有的静态资源,你需要在Webpack的配置文件中添加相应的规则。具体步骤如下:
1. 在Webpack配置文件中添加一个名为`copy-webpack-plugin`的插件,用于复制public目录中的文件到打包后的目录中:
```javascript
const CopyWebpackPlugin = require('copy-webpack-plugin');
module.exports = {
// ...
plugins: [
new CopyWebpackPlugin({
patterns: [
{ from: 'public', to: '.' },
],
}),
],
// ...
};
```
2. 添加一个规则,用于处理其他非JavaScript类型的文件。这里我们使用`file-loader`,将这些文件复制到打包后的目录中:
```javascript
module.exports = {
// ...
module: {
rules: [
// ...
{
test: /\.(png|jpe?g|gif|ico|svg|woff|woff2|eot|ttf|otf)$/i,
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'assets',
},
},
],
},
// ...
};
```
这个规则会匹配所有以`.png`、`.jpg`、`.jpeg`、`.gif`、`.ico`、`.svg`、`.woff`、`.woff2`、`.eot`、`.ttf`、`.otf`结尾的文件,并将它们复制到打包后的`assets`目录中。
通过以上步骤,你就可以使用Webpack打包public目录中的所有静态资源了。