# fed-e-task-02-02 **Repository Path**: zhangxiaofeng66/fed-e-task-02-02 ## Basic Information - **Project Name**: fed-e-task-02-02 - **Description**: No description available - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2020-07-26 - **Last Updated**: 2020-12-19 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README #### 一、Webpack的构建流程主要有那些环节,如果可以请尽可能的描述详尽的描述Webpack打包的整个过程。 解答:Webpack的构建流程主要包含: 1.初始化package.json文件 ``` yarn init ``` 2.安装webpack ``` yarn add webpack --dev ``` 3.新建webpack配置文件,webpack.config.js 4.配置入口目录和输出目录 ``` const path = require('path); module.exports = { enter: './src', output: { filename: 'bundle.js', path: path.join(__dirname, 'dist') }, } ``` 5.配置资源文件加载器 ``` yarn add css-loader style-loader --dev yarn add url-loader --dev const path = require('path); module.exports = { enter: './src', output: { filename: 'bundle.js', path: path.join(__dirname, 'dist') }, modules: { rules: [ { test: /.css$/, use: [ 'style.loader', 'css-loader' ] },{ test: /\.(png|jpg|gif)$/, options: { limit: 10 * 1024 // 字节也就是10kb } } ] } } ``` 6.自动生成html文件 ``` yarn add html-webpack-plugin --dev ... const htmlWebpackPlugin = require('html-webapck-plugin'); module.exports = { ... plugins: [ new htmlWebpackPlugin({ title: 'my title', template: './src/index.html' }) ] ... } ``` #### 2、Loader 和 Plugin 有哪些不同?请描述一下开发 Loader 和 Plugin 的思路。 1、Loader用于对模块的源代码进行转换。\ 2、Plugin主要是扩展Webpack的功能,比如打包优化和压缩。 **loader开发步骤** ###### loader开发结构 ``` module.exports = function (source) { // source是输入文件的内容 // 输出内容, return result } ``` >由于输出内容是js,所以对于一些非js内容需要处理成js, 常见的的方式处理是: - return `module.exports = ${result}`; - return `export default ${JSON.stringify(result)}`; - 或者通过其他loader去处理 **Plugin开发步骤** ###### plugin插件结构 ``` class MyPlugin{ apply(compiler) { compiler.hooks.emit.tap('MyPlugin', compilation => { ... }) } } module.exports = MyPlugin ``` Webpack主要主要使用到两个对象,compiler和compilation: - compiler: 包含了webpack的环境配置,当webpack调用插件的时候,会返回一个compiler对象,提供给插件。 - compilation:是编译过程的生命周期,这个对象可以访问到所有的模块和它们的依赖。