webpack 构建前端项目(1)

webpack是一个现代 JavaScript 应用程序的静态模块打包器(module bundler)。当 webpack 处理应用程序时,它会递归地构建一个依赖关系图(dependency graph),其中包含应用程序须要的每一个模块,而后将全部这些模块打包成一个或多个bundle。
css

后续章节

webpack构建前端项目2html

webpack构建前端项目3前端

搭建webpack

新建项目 npm init -y 生成package.json 文件;vue

npm init -y复制代码

安装 webpack 和 webpack-clinode

npm i webpack webpack-cli -D复制代码

在文件根目录新建一个 webpack.config.js 文件,新建src目录,在 src目录下新建main.js做为入口文件。webpack.config.js代码以下webpack

const path=require('path')
module.exports={    
entry:path.resolve(__dirname,'src/main.js'),  //入口文件    
output:{  //输出文件        
    filename:'index.js',        
    path:path.resolve(__dirname,'dist')
}}复制代码

入口文件若是不写,默认是src目录下的index.js文件,在 package.json 文件中 加入脚本启动
ios

"scripts": {
    "build":"webpack"
 }复制代码

在命令行输入 npm run build ,可看到 dist目录下生成了 index.js。git

资源处理

webpack在处理各类类型的资源时,需用到各资源的loader es6

处理图片资源

处理图片资源使用 file-loader url-loader,在命令行输入github

npm i file-loader url-loader -D复制代码

webpack.config.js中添加 

module.exports = {
  entry: path.resolve(__dirname, 'src/main.js'),
  output: {
    filename: 'index.js',
    path: path.resolve(__dirname, 'dist')
  },
  module: {
    rules: [{
      test: /\.(jpe?g|png|gif|svg)(\?.*)?$/,
      use: [{
        loader: "url-loader",
        options: {
          limit: 10000,
          filename: '[name].[hahs:5].[ext]',
          outputPath: 'imgs/'
        }
      }]
    }]
  }}
复制代码


limit选项将小于此大小的图片转换为base64,以base64字符串形式内联进项目中;outputPath是打包后的图片所在的目录。

处理js文件

应用babel-loader把es6 7语法转换成浏览器支持度高的es5语法,参考小诺哥的作法:

npm i babel-loader @babel/core @babel/preset-env @babel/runtime @babel/plugin-transform-runtime -D复制代码

webpack.config.js 中添加

module.exports = {
    module: {
        rules: [
            ...
            {
            test: /\.js$/,
            exclude: /node_modules/,
            use: ['babel-loader?cacheDirectory']
            }
        ]
    }}
复制代码

在文件更目录下新建 .babelrc 文件

{
    "presets": [
        ["@babel/preset-env"]
    ],
    "plugins": [
        [
         "@babel/plugin-transform-runtime",
          {
            "corejs": false,
            "helpers": true,
            "regenerator": true,
            "useESModules": false,
            "absoluteRuntime": "@babel/runtime"
          }
        ]
    ]}   

复制代码

处理css、less文件

命令行安装

npm i style-loader css-loader less less-loader复制代码

webpack.config.js 中添加

module.exports = {
    entry: path.resolve(__dirname, 'src/main.js'),
    output: {
        filename: 'index.js',
        path: path.resolve(__dirname, 'dist')
    },
    module: {
        rules: [
            ...
            {
            test: /\.(le|c)ss$/,
            use: ['style-loader', 'css-loader', 'less-loader']
            }
        ]
    }}
     

复制代码

use 的处理顺序是右往左处理 对css、less 文件依次进行处理,

处理vue文件 

命令行输入

npm i vue vue-loader vue-style-loader vue-template-compiler -D复制代码

在webpack.config.js中的插件中引入vuePlugin; vue-style-loader替换掉style-loader:

参考vue-loader官网

const vuePlugin = require('vue-loader/lib/plugin')
module.exports = {
    ...    
    module: {
        rules: [
            ....
             {
                test: /\.(le|c)ss$/,
                use: ['vue-style-loader', 'css-loader', 'less-loader']
            },
             {
                test: /\.vue$/,
                use: ['vue-loader']
            }
        ]
    },
    plugins: [new vuePlugin()]
}复制代码

在src 下 新建一个app.vue文件,

<template>
    <h1>hello world</h1></template>
<script>
    export default {}
</script>
<style></style>
复制代码

在src/main.js中引入 app.vue 建立 vue对象

import App from './app'import Vue from 'vue'
let ele = document.createElement('div')
ele.id = 'root'document.body.appendChild(ele) 
new Vue({
    el: '#root',
    render: h => h(App)
})
复制代码

运行 npm run build生成 打包后的 index.js ,新建一个html文件,script引入 index.js便可在浏览器中查看效果

plugins插件

插件是 webpack 的支柱功能,插件目的在于解决 loader 没法实现的其余事

clean-webpack-plugin

用 clean-webpack-plugin 能够自动清除output打包的目录,不用本身手动清理

npm i clean-webpack-plugin -D复制代码

在webpack.config.js中

const { CleanWebpackPlugin} = require('clean-webpack-plugin') 
module.exports = {    
   ...    
   plugins: [        
     ...        
    new CleanWebpackPlugin()    
]}复制代码

html-webpack-plugin

用html-webpack-plugin能够在打包的目录生成一个html文件,并在html中自动引入打包好的js、css等文件

npm i html-webpack-plugin -D复制代码

新建目录template,在tempalte目录中新建template.html文件做为模板文件。

在webpack.config.js中

const htmlPlugin=require('html-webpack-plugin')

module.exports={
   ...  
   plugins:[ 
    ...    
    new htmlPlugin({
       template:'template/template.html'
    })  
  ]
}复制代码

resolve和externals

配置了webpack.resolve.extensions,在引入文件时,自动补全文件的后缀名。webpack.resolve.alias配置路径别名。

const res = (p) => path.join(process.cwd(), p);
module.exports = {
    resolve: {
        extensions: ['.js', '.vue', '.json'],
        alias: {
            '@': res('src'),
            '@style': res('src/common/style'), 
           '@js': res('src/common/js'),
            '@mock': res('mock'),
            '@component': res('src/component')
        }
    },
    externals: {
        'axios': 'axios'
    }}
复制代码

配置在externals中的项目,webpack在打包时会进行过滤,通常用于cdn加速

相关文章
相关标签/搜索