webpack核心概念使用的综合小案例

注:

由于版本更新很快,同样的配置不同版本很可能会出错(这个就很绝望了)

解决思路

  1. 看文档
  2. 查看源码接口
  3. 网上搜索相应错误

环境

webpack4.x + yarn

文件结构

.
├── dist //打包输出目录
├── package.json
├── postcss.config.js
├── rules_config //module 中各种文件到导入处理
│   ├── babel-polyfill.js
│   ├── babel-runtime.js
│   ├── css.js
│   ├── font.js
│   ├── images.js
│   └── less.js
├── src
│   ├── fonts
│   │   ├── iconfont.css
│   │   ├── iconfont.eot
│   │   ├── iconfont.svg
│   │   ├── iconfont.ttf
│   │   ├── iconfont.woff
│   │   └── iconfont.woff2
│   ├── images
│   │   ├── 1.png
│   │   └── 2.png
│   ├── js
│   │   ├── app.js
│   │   └── math.js
│   └── sheet
│       ├── css.css
│       └── less.less
├── view
│   └── index.html
├── webpack.config.build.js
├── webpack.config.bundle.js
├── webpack.config.serve.js
└── yarn.lock

package.json

{
  "name": "sample",
  "version": "1.0.0",
  "private": true,
  "license": "MIT",
  "scripts": {
    "bundle": "webpack --config webpack.config.bundle.js",
    "serve": "webpack-dev-server --config webpack.config.serve.js",
    "build": "webpack --config webpack.config.build.js"
  },
  "devDependencies": {
    "@babel/core": "^7.4.5",
    "@babel/plugin-transform-runtime": "^7.4.4",
    "@babel/polyfill": "^7.4.4",
    "@babel/preset-env": "^7.4.5",
    "@babel/runtime": "^7.4.5",
    "@babel/runtime-corejs2": "^7.4.5",
    "autoprefixer": "^9.6.0",
    "babel-loader": "^8.0.6",
    "clean-webpack-plugin": "^3.0.0",
    "css-loader": "^2.1.1",
    "file-loader": "^4.0.0",
    "html-webpack-plugin": "^3.2.0",
    "less": "^3.9.0",
    "less-loader": "^5.0.0",
    "postcss-loader": "^3.0.0",
    "style-loader": "^0.23.1",
    "url-loader": "^2.0.0",
    "webpack": "^4.33.0",
    "webpack-cli": "^3.3.3",
    "webpack-dev-server": "^3.7.1"
  },
  "browserslist": [
    "last 2 versions"
  ]
}

可用的命令

  • yarn build //打包生产环境的代码
  • yarn serve //运行本地服务器
  • yarn bundle //打包开发环境的代码(未压缩)
  • yarn add -D [pagckage-name] //添加开发依赖包
  • yarn install  [pagckage-name] //安装包

打包配置文件

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

module.exports = {
    entry: {
        app: './src/js/app.js' //入口js文件
    },
    output: {
        filename: "[hash:8]--[name].js", //输出的js文件名
        path: path.resolve(__dirname, 'dist'), //输出目录(必须是绝对路径)
        // publicPath: "https://192.168.1.106:6655" //用于CDN
    },
    mode: "development", //开发环境
    devtool: "cheap-module-eval-source-map",
    module: {
        rules: [
            require('./rules_config/css.js'),
            require('./rules_config/less.js'),
            require('./rules_config/images.js'),
            require('./rules_config/font.js'),
            {
                test: /\.js$/,
                exclude: /node_modules/,
                loader: "babel-loader",
                options: require('./rules_config/babel-polyfill.js'),
                // options: require('./rules_config/babel-runtime.js'),
            }
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({ //生成模版html,自动注入打包的js文件
            template: './view/index.html'
        }),
        new CleanWebpackPlugin(), //清除dist目录的内容
    ],
    stats: {children: false} //避免 Entrypoint undefined = index.html
};
 
webpack.config.serve.js
const md = require('./webpack.config.bundle.js');
const path = require('path');
const serve = {
    devServer: {
        contentBase: path.resolve(__dirname, 'dist'),
        port: 12986,
        hot: true,
        hotOnly: true,
        open: true
    }
};
Object.assign(md, serve);
const webpack = require('webpack');
md.plugins.push(new webpack.HotModuleReplacementPlugin());
module.exports = md;
 
webpack.config.build.js
const md = require('./webpack.config.bundle.js');
const build = {
    mode: "production", //用于线上(生成环境)
    devtool: "cheap-module-source-map",
};
Object.assign(md, build);
module.exports = md;
处理各种文件(loader)的配置
css 文件
module.exports = {
    test: /.css$/,
    use: [
        'style-loader',
        {
            loader: "css-loader",
            options: {
                importLoaders: 1
            }
        },
        'postcss-loader'
    ]
};
 
    
   

less 文件
module.exports = {
    test: /\.less$/,
    use: [
        'style-loader',
        {
            loader: "css-loader",
            options: {
                modules: true,
                importLoaders: 2
            }
        },
        'less-loader',
        "postcss-loader"
    ]
};
 
    
   

js 文件,主要出es6转es5
全局替换,用于应用
module.exports = {
    "presets": [
        [
            "@babel/preset-env",
            {
                "targets": {
                    "edge": "17",
                    "firefox": "60",
                    "chrome": "67",
                    "safari": "11.1",
                    "ie": "9"
                },
                "useBuiltIns": "usage", //按需引入
                "corejs": "2",
            }
        ]
    ],
};
 
     
    

局部替换,用于框架/库
module.exports = {
    "plugins": [
        [
            "@babel/plugin-transform-runtime",
            {
                "absoluteRuntime": false,
                "corejs": 2,
                "helpers": true,
                "regenerator": true,
                "useESModules": false
            }
        ]
    ]
};
 
    
   

font 文件
module.exports = {
    test: /\.(eot|svg|ttf|woff|woff2)$/,
    loader: "file-loader",
    options: {
        name: '[hash:8]--[name].[ext]',
    }
};
 
    
   

图片文件
module.exports = {
    test: /\.(png|jpg|gif)$/,
    loader: "url-loader",
    options: {
        name: '[hash:8]--[name].[ext]',
        outputPath: 'images', //输出目录中的images的目录下
        limit: 8 * 1024, //小于8K 转成 base64字符串
    }
};
 
  

样式相关的文件

/src/sheet/css.css
*{
    padding: 0;
    margin: 0;
}
.at{
    transform: translate(30px, 30px);
    color: red;
}
/src/sheet/less.less
.lt{
  transform: translate(unit(100, px), unit(100, px));
  color: chocolate;
}
postcss.config.js //用于使用 postcss-loader
module.exports = {
    plugins: [
        require('autoprefixer')
    ],
};

/view/index.html 模版文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1 class="hmr">
    1111111
</h1>
<div style="font-size: 100px; background: coral">
    <i class="iconfont icon-icon-test"></i>
    <i class="iconfont icon-icon-test1"></i>
    <i class="iconfont icon-icon-test2"></i>
</div>
<div id="img1" style="width: 100px; height: 150px; overflow: hidden"></div>
<div id="img2"></div>

<h1 class="at">全局的</h1>
<h1 class="lt">模块化样式测试1(局部样式,代码中添加)</h1>
<div style="height: 200px"></div>
<h1 class="lt">模块化样式测试2(没有在代码中添加类)</h1>
</body>
</html>

测试使用的代码 /src/js/app.js

// 全局样式
import '../sheet/css.css';
import '../fonts/iconfont.css';


// 样式模块化测试
import less from '../sheet/less.less';

window.document.querySelector('.lt').classList.add(less.lt);


// 图片测试 > 8 K
let img = new Image();
img.src = require('../images/1.png');
window.document.querySelector('#img1').appendChild(img);

// 图片测试 < 8 K
img = new Image();
img.src = require('../images/2.png');
window.document.querySelector('#img2').appendChild(img);


// es6 语法,按需加载
const es6m = (a, b)=>{
    return new Promise(resolve => {
        resolve(a + b);
    });
};
(async function () {
    const ret = await es6m('afn111', 'b11');
    console.log(ret);
})();


// 普通的js导入测试11
import './math.js';
// HMR
if(module.hot){
    module.hot.accept(['./math.js'], function () {
        console.log('213')
    });
}

font文件夹中的内容

阿里巴巴矢量图标库  https://www.iconfont.cn/ 中下载的压缩包中的字体文件

猜你喜欢

转载自www.cnblogs.com/heidekeyi/p/11009586.html