webpack静态资源管理加载及输出管理

webpack指南梳理学习 - 静态资源管理加载及输出管理

导读

在webpack中,静态资源管理加载和输出管理是非常重要的一个功能,在模块化开发中起到了很重要的作用,我们通过加载打包css、图片、字体、数据文件等来
了解webpack对资源的管理

安装依赖

cnpm install --save-dev style-loader css-loader # 加载css
cnpm install --save-dev file-loader # 加载图片、字体
cnpm install --save-dev csv-loader xml-loader # 加载CSV、TSV 和 XML等数据文件

加载样式css 、加载加载图片/字体、加载CSV、TSV 和 XML等数据文件

修改webpack.config.js配置文件如下:

const path = require('path');

module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  },
  module:{
    rules: [
        {
            test: /\.css$/,
            use: [ 'style-loader', 'css-loader' ]
        },
        {
            test: /\.(png|svg|jpg|gif)$/,
            use: [ 'file-loader' ]
        },
        {
            test: /\.(woff|woff2|eot|ttf|otf)$/,
            use:[ 'file-loader' ]
        },
        {
            test: /\.(csv|tsv)$/,
            use: [ ' csv-loader ' ]
        },
        {
            test: /\.xml$/,
            use: [ 'xml-loader' ]
        }
    ]
  }
};

src目录下新建style.css文件,编辑如下:

@font-face {
    font-family: Myfont;
    src: url('./font/font.ttf');
    font-weight: 600;
    font-style: normal;
}

.box{
    font-family:Myfont;background-color: red; color: #000;border: 1px solid #333;background: url('./img_1.jpg');
}

src目录下新建data.xml文件,编辑如下:

<?xml version="1.0" encoding="UTF-8"?>
<note>
  <to>Mary</to>
  <from>John</from>
  <heading>Reminder</heading>
  <body>Call Cindy on Tuesday</body>
</note>

src目录下新建拷贝进入两张图片文件,如下:

在这里插入图片描述
在这里插入图片描述

src目录下编辑index.js如下:

import _ from 'lodash';
import './style.css'
import ImgPng from './img.png'
import Data from './data.xml'

function component(){
    let element = document.createElement("div")
    element.innerHTML = _.join(['Hello','webpack','爱心小兔字体'], ' ')
    
    element.classList.add('box')

    // 添加图片到box中
    let img = new Image()
    img.src = ImgPng
    element.appendChild(img)

    // 打印出xml信息
    let newSpan = document.createElement('span')
    console.log(Data)
    newSpan.innerHTML = JSON.stringify(Data)
    document.body.appendChild(newSpan)

    return element
}

document.body.appendChild(component())

执行打包编译

D:\me\npm\test\webpack-test>npm run build

> [email protected] build D:\me\npm\test\webpack-test
> npx webpack --config webpack.config.js

Hash: 10274a0f4dd93f8703cf
Version: webpack 4.33.0
Time: 4429ms
Built at: 2019-06-12 11:10:12
                               Asset      Size  Chunks                    Chunk Names
836340c677d81305c33ed659d67328da.jpg  28.1 KiB          [emitted]
a407e9d6d9baa89ee0916a24f93d7a9b.png   290 KiB          [emitted]  [big]
                           bundle.js  77.3 KiB       0  [emitted]         main
ec581258a2a8c1a8bd018aef265b4152.ttf  16.2 MiB          [emitted]  [big]
Entrypoint main = bundle.js
 [0] ./src/data.xml 113 bytes {0} [built]
 [2] ./src/img.png 82 bytes {0} [built]
 [3] ./src/index.js 593 bytes {0} [built]
 [4] (webpack)/buildin/global.js 472 bytes {0} [built]
 [5] (webpack)/buildin/module.js 497 bytes {0} [built]
 [6] ./src/style.css 1.13 KiB {0} [built]
 [7] ./node_modules/[email protected]@css-loader/dist/cjs.js!./src/style.css 681 bytes {0} [built]
[10] ./src/font/font.ttf 82 bytes {0} [built]
[11] ./src/img_1.jpg 82 bytes {0} [built]
    + 5 hidden modules

WARNING in configuration
The 'mode' option has not been set, webpack will fallback to 'production' for this value. Set 'mode' option to 'development' or 'production' to enable defaults for each environment.
You can also set it to 'none' to disable any default behavior. Learn more: https://webpack.js.org/configuration/mode/

WARNING in asset size limit: The following asset(s) exceed the recommended size limit (244 KiB).
This can impact web performance.
Assets:
  a407e9d6d9baa89ee0916a24f93d7a9b.png (290 KiB)
  ec581258a2a8c1a8bd018aef265b4152.ttf (16.2 MiB)

WARNING in webpack performance recommendations:
You can limit the size of your bundles by using import() or require.ensure to lazy load some parts of your application.
For more info visit https://webpack.js.org/guides/code-splitting/

执行结果

在这里插入图片描述

output文件输出管理

到目前为止,我们在 index.html 文件中手动引入所有资源,然而随着应用程序增长,并且一旦开始对文件名使用哈希(hash)]并输出多个 bundle,手动地对 index.html 文件进行管理,一切就会变得困难起来。然而,可以通过一些插件,会使这个过程更加容易被操控。

src目录下新增文件project.js,编辑如下:

export default function printMe() {
  console.log('打印这条信息~~~~');
}

src/index.js编辑如下:

import _ from 'lodash';
import printMe from './project.js'

function component(){
    let element = document.createElement("div")
    element.innerHTML = _.join(['Hello','webpack','爱心小兔字体'], ' ')
    
    element.classList.add('box')

    // 新增点击按钮
    let btn = document.createElement('button');
    btn.innerHTML = '点击我会打印信息';
    btn.onclick = printMe;

    element.appendChild(btn);

    return element 
}

document.body.appendChild(component())

dist/index.html编辑如下:

<!doctype html>
<html>
<head>
    <title>output输出管理</title>
</head>
<body>
    <script src="./project.bundle.js"></script>
    <script src="./app.bundle.js"></script>
</body>
</html>

webpack.config.js 配置文件编辑如下:

const path = require('path');

module.exports = {
  entry: {
    app: './src/index.js',
    project: './src/project.js'
  },
  output: {
    filename: '[name].bundle.js',
    path: path.resolve(__dirname, 'dist')
  }
};

打包编译如下:

D:\me\npm\test\webpack-test>npm run build

> [email protected] build D:\me\npm\test\webpack-test
> npx webpack --config webpack.config.js

Hash: 4eb77ce34995a49aeb4f
Version: webpack 4.33.0
Time: 3856ms
Built at: 2019-06-12 11:58:56
            Asset      Size  Chunks             Chunk Names
    app.bundle.js  70.6 KiB    0, 1  [emitted]  app
project.bundle.js     1 KiB       1  [emitted]  project
Entrypoint app = app.bundle.js
Entrypoint project = project.bundle.js
[0] ./src/project.js 68 bytes {0} {1} [built]
[2] ./src/index.js 440 bytes {0} [built]
[3] (webpack)/buildin/global.js 472 bytes {0} [built]
[4] (webpack)/buildin/module.js 497 bytes {0} [built]
    + 1 hidden module

WARNING in configuration
The 'mode' option has not been set, webpack will fallback to 'production' for this value. Set 'mode' option to 'development' or 'production' to enable defaults for each environment.
You can also set it to 'none' to disable any default behavior. Learn more: https://webpack.js.org/configuration/mode/

显示效果:

在这里插入图片描述

清理dist目录,且使用HtmlWebpackPlugin自动生成index.html

cnpm install --save-dev html-webpack-plugin
cnpm install --save-dev clean-webpack-plugin

webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');

module.exports = {
  entry: {
    app: './src/index.js',
    project: './src/project.js'
  },
  output: {
    filename: '[name].bundle.js',
    path: path.resolve(__dirname, 'dist')
  },
  plugins:[
    new CleanWebpackPlugin(),  // 清除dist文件夹内容
    new HtmlWebpackPlugin({
        title: 'output出口管理'   // 自动生成index.html ,引入js文件
    })
  ]
};

生成的index.html内容如下:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>output出口管理</title>
  </head>
  <body>
  <script type="text/javascript" src="app.bundle.js"></script><script type="text/javascript" src="project.bundle.js"></script></body>
</html>

猜你喜欢

转载自blog.csdn.net/WU5229485/article/details/91523525