webpack笔记

webpack笔记

目录

1.webpack是什么(https://www.runoob.com/w3cnote/webpack-tutorial.html)

2.为什么需要webpack(https://segmentfault.com/a/1190000015973544)

3.使用webpack

1.创建一文件path.js来写路径配置

2.写生产环境和开发环境公用配置webpack.common.js

3.生产环境配置:webpack.prod.js

4.开发环境:webpack.dev.js

改进1.:上述配置打包,会把css全部和js文件混在一起,下边在prod中需要分离和压缩css

改进2:提取公共代码:webpack.prod.js

改进3:多入口:

改进4:多进程打包和多进程压缩css

改进5:dev的热更新

改进6:dev的dllPlugin动态链接库插件的使用

使用babel


1.webpack是什么(https://www.runoob.com/w3cnote/webpack-tutorial.html)

Webpack 是一个前端资源加载/打包工具。它将根据模块的依赖关系进行静态分析,然后将这些模块按照指定的规则生成对应的静态资源。

webpack本质上就是一个将我们平时写的模块化代码转成现在浏览器可以直接执行的代码

2.为什么需要webpack(https://segmentfault.com/a/1190000015973544)

1.开发的时候需要一个开发环境,要是我们修改一下代码保存之后浏览器就自动展现最新的代码那就好了(热更新服务)
2.本地写代码的时候,要是调后端的接口不跨域就好了(代理服务)
3.为了跟上时代,要是能用上什么ES678N等等新东西就好了(翻译服务)
4.项目要上线了,要是能一键压缩代码啊图片什么的就好了(压缩打包服务)
5.我们平时的静态资源都是放到CDN上的,要是能自动帮我把这些搞好的静态资源怼到CDN去就好了(自动上传服务)

  • 如果与输入相关的需求,找entry(比如多页面就有多个入口)
  • 如果与输出相关的需求,找output(比如你需要定义输出文件的路径、名字等等)
  • 如果与模块寻址相关的需求,找resolve(比如定义别名alias)
  • 如果与转译相关的需求,找loader(比如处理sass处理es678N)
  • 如果与构建流程相关的需求,找plugin(比如我需要在打包完成后,将打包好的文件复制到某个目录,然后提交到git上)

3.使用webpack

以vue项目为例,会将webpack配置分成三块:common,dev,prod

1.创建一文件path.js来写路径配置

/**
 * @description 常用文件夹路径

 */

const path = require('path')

const srcPath = path.join(__dirname, '..', 'src')
const distPath = path.join(__dirname, '..', 'dist')

module.exports = {
    srcPath,
    distPath
}

2.写生产环境和开发环境公用配置webpack.common.js

const path = require('path')//Node.js path 模块提供了一些用于处理文件路径的小工具
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { srcPath, distPath } = require('./paths')

module.exports = {
    entry: path.join(srcPath, 'index'),
    module: {
        rules: [
            {
                test: /\.js$/,
                loader: ['babel-loader'],
                include: srcPath,
                exclude: /node_modules/
            },
            {
                test: /\.vue$/,
                loader: ['vue-loader'],
                include: srcPath
            },
            // {
            //     test: /\.css$/,
            //     // loader 的执行顺序是:从后往前(知识点)
            //     loader: ['style-loader', 'css-loader']
            // },
            {
                test: /\.css$/,
                // loader 的执行顺序是:从后往前
                loader: ['style-loader', 'css-loader', 'postcss-loader'] // 加了 postcss
            },
            {
                test: /\.less$/,
                // 增加 'less-loader' ,注意顺序
                loader: ['style-loader', 'css-loader', 'less-loader']
            }
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: path.join(srcPath, 'index.html'),
            filename: 'index.html'
        })
    ]
}

3.生产环境配置:webpack.prod.js

const path = require('path')
const webpack = require('webpack')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const webpackCommonConf = require('./webpack.common.js')
const { smart } = require('webpack-merge')
const { srcPath, distPath } = require('./paths')

module.exports = smart(webpackCommonConf, {
    mode: 'production',
    output: {
        filename: 'bundle.[contentHash:8].js',  // 打包代码时,加上 hash 戳
        path: distPath,
        // publicPath: 'http://cdn.abc.com'  // 修改所有静态文件 url 的前缀(如 cdn 域名),这里暂时用不到
    },
    module: {
        rules: [
            // 图片 - 考虑 base64 编码的情况
            {
                test: /\.(png|jpg|jpeg|gif)$/,
                use: {
                    loader: 'url-loader',
                    options: {
                        // 小于 5kb 的图片用 base64 格式产出
                        // 否则,依然延用 file-loader 的形式,产出 url 格式
                        limit: 5 * 1024,

                        // 打包到 img 目录下
                        outputPath: '/img1/',

                        // 设置图片的 cdn 地址(也可以统一在外面的 output 中设置,那将作用于所有静态资源)
                        // publicPath: 'http://cdn.abc.com'
                    }
                }
            },
        ]
    },
    plugins: [
        new CleanWebpackPlugin(), // 会默认清空 output.path 文件夹
        new webpack.DefinePlugin({
            // window.ENV = 'production'
            ENV: JSON.stringify('production')
        })
    ]
})

4.开发环境:webpack.dev.js

const path = require('path')
const webpack = require('webpack')
const webpackCommonConf = require('./webpack.common.js')
const { smart } = require('webpack-merge')
const { srcPath, distPath } = require('./paths')

module.exports = smart(webpackCommonConf, {
    mode: 'development',
    module: {
        rules: [
            // 直接引入图片 url
            {
                test: /\.(png|jpg|jpeg|gif)$/,
                use: 'file-loader'
            }
        ]
    },
    plugins: [
        new webpack.DefinePlugin({
            // window.ENV = 'development'
            ENV: JSON.stringify('development')
        })
    ],
    devServer: {
        port: 8080,
        progress: true,  // 显示打包的进度条
        contentBase: distPath,  // 根目录
        open: true,  // 自动打开浏览器
        compress: true,  // 启动 gzip 压缩

        // 设置代理
        proxy: {
            // 将本地 /api/xxx 代理到 localhost:3000/api/xxx
            '/api': 'http://localhost:3000',

            // 将本地 /api2/xxx 代理到 localhost:3000/xxx
            '/api2': {
                target: 'http://localhost:3000',
                pathRewrite: {
                    '/api2': ''
                }
            }
        }
    }
})

改进1.:上述配置打包,会把css全部和js文件混在一起,下边在prod中需要分离和压缩css

对webpack.prod.js:

const path = require('path')
const webpack = require('webpack')
const { smart } = require('webpack-merge')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const TerserJSPlugin = require('terser-webpack-plugin')
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin')
const webpackCommonConf = require('./webpack.common.js')
const { srcPath, distPath } = require('./paths')

module.exports = smart(webpackCommonConf, {
    mode: 'production',
    output: {
        // filename: 'bundle.[contentHash:8].js',  // 打包代码时,加上 hash 戳
        filename: '[name].[contentHash:8].js', // name 即多入口时 entry 的 key
        path: distPath,
        // publicPath: 'http://cdn.abc.com'  // 修改所有静态文件 url 的前缀(如 cdn 域名),这里暂时用不到
    },
    module: {
        rules: [
            // 图片 - 考虑 base64 编码的情况
            {
                test: /\.(png|jpg|jpeg|gif)$/,
                use: {
                    loader: 'url-loader',
                    options: {
                        // 小于 5kb 的图片用 base64 格式产出
                        // 否则,依然延用 file-loader 的形式,产出 url 格式
                        limit: 5 * 1024,

                        // 打包到 img 目录下
                        outputPath: '/img1/',

                        // 设置图片的 cdn 地址(也可以统一在外面的 output 中设置,那将作用于所有静态资源)
                        // publicPath: 'http://cdn.abc.com'
                    }
                }
            },
            // 抽离 css
            {
                test: /\.css$/,
                loader: [
                    MiniCssExtractPlugin.loader,  // 注意,这里不再用 style-loader
                    'css-loader',
                    'postcss-loader'
                ]
            },
            // 抽离 less --> css
            {
                test: /\.less$/,
                loader: [
                    MiniCssExtractPlugin.loader,  // 注意,这里不再用 style-loader
                    'css-loader',
                    'less-loader',
                    'postcss-loader'
                ]
            }
        ]
    },
    plugins: [
        new CleanWebpackPlugin(), // 会默认清空 output.path 文件夹
        new webpack.DefinePlugin({
            // window.ENV = 'production'
            ENV: JSON.stringify('production')
        }),

        // 抽离 css 文件
        new MiniCssExtractPlugin({
            filename: 'css/main.[contentHash:8].css'
        })
    ],

    optimization: {
        // 压缩 css
        minimizer: [new TerserJSPlugin({}), new OptimizeCSSAssetsPlugin({})],
    }
})

改进2:提取公共代码:webpack.prod.js

在plugis中的optimization:

  optimization: {
        // 压缩 css
        minimizer: [new TerserJSPlugin({}), new OptimizeCSSAssetsPlugin({})],

        // 分割代码块
        splitChunks: {
            chunks: 'all',
            /**
             * initial 入口chunk,对于异步导入的文件不处理
                async 异步chunk,只对异步导入的文件处理
                all 全部chunk
             */

            // 缓存分组
            cacheGroups: {
                // 第三方模块
                vendor: {
                    name: 'vendor', // chunk 名称
                    priority: 1, // 权限更高,优先抽离,重要!!!
                    test: /node_modules/,
                    minSize: 0,  // 大小限制
                    minChunks: 1  // 最少复用过几次
                },

                // 公共的模块
                common: {
                    name: 'common', // chunk 名称
                    priority: 0, // 优先级
                    minSize: 0,  // 公共模块的大小限制
                    minChunks: 2  // 公共模块最少复用过几次
                }
            }
        }
    }

改进3:多入口:

1.在commmon中对entry和plugins进行修改:

  entry: {
        index: path.join(srcPath, 'index.js'),
        other: path.join(srcPath, 'other.js')
    },





  plugins: [
        // new HtmlWebpackPlugin({
        //     template: path.join(srcPath, 'index.html'),
        //     filename: 'index.html'
        // })

        // 多入口 - 生成 index.html
        new HtmlWebpackPlugin({
            template: path.join(srcPath, 'index.html'),
            filename: 'index.html',
            // chunks 表示该页面要引用哪些 chunk (即上面的 index 和 other),默认全部引用
            chunks: ['index']  // 只引用 index.js
        }),
        // 多入口 - 生成 other.html
        new HtmlWebpackPlugin({
            template: path.join(srcPath, 'other.html'),
            filename: 'other.html',
            chunks: ['other']  // 只引用 other.js
        })
    ]

改进4:多进程打包和多进程压缩css

在prod中引入:

const HappyPack = require('happypack')

const ParallelUglifyPlugin = require('webpack-parallel-uglify-plugin')

全部如下: 

const path = require('path')
const webpack = require('webpack')
const { smart } = require('webpack-merge')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const TerserJSPlugin = require('terser-webpack-plugin')
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin')
const HappyPack = require('happypack')
const ParallelUglifyPlugin = require('webpack-parallel-uglify-plugin')
const webpackCommonConf = require('./webpack.common.js')
const { srcPath, distPath } = require('./paths')

module.exports = smart(webpackCommonConf, {
    mode: 'production',
    output: {
        // filename: 'bundle.[contentHash:8].js',  // 打包代码时,加上 hash 戳
        filename: '[name].[contentHash:8].js', // name 即多入口时 entry 的 key
        path: distPath,
        // publicPath: 'http://cdn.abc.com'  // 修改所有静态文件 url 的前缀(如 cdn 域名),这里暂时用不到
    },
    module: {
        rules: [
            // js
            {
                test: /\.js$/,
                // 把对 .js 文件的处理转交给 id 为 babel 的 HappyPack 实例
                use: ['happypack/loader?id=babel'],
                include: srcPath,
                // exclude: /node_modules/
            },
            // 图片 - 考虑 base64 编码的情况
            {
                test: /\.(png|jpg|jpeg|gif)$/,
                use: {
                    loader: 'url-loader',
                    options: {
                        // 小于 5kb 的图片用 base64 格式产出
                        // 否则,依然延用 file-loader 的形式,产出 url 格式
                        limit: 5 * 1024,

                        // 打包到 img 目录下
                        outputPath: '/img1/',

                        // 设置图片的 cdn 地址(也可以统一在外面的 output 中设置,那将作用于所有静态资源)
                        // publicPath: 'http://cdn.abc.com'
                    }
                }
            },
            // 抽离 css
            {
                test: /\.css$/,
                loader: [
                    MiniCssExtractPlugin.loader,  // 注意,这里不再用 style-loader
                    'css-loader',
                    'postcss-loader'
                ]
            },
            // 抽离 less
            {
                test: /\.less$/,
                loader: [
                    MiniCssExtractPlugin.loader,  // 注意,这里不再用 style-loader
                    'css-loader',
                    'less-loader',
                    'postcss-loader'
                ]
            }
        ]
    },
    plugins: [
        new CleanWebpackPlugin(), // 会默认清空 output.path 文件夹
        new webpack.DefinePlugin({
            // window.ENV = 'production'
            ENV: JSON.stringify('production')
        }),

        // 抽离 css 文件
        new MiniCssExtractPlugin({
            filename: 'css/main.[contentHash:8].css'
        }),

        // 忽略 moment 下的 /locale 目录
        new webpack.IgnorePlugin(/\.\/locale/, /moment/),

        // happyPack 开启多进程打包
        new HappyPack({
            // 用唯一的标识符 id 来代表当前的 HappyPack 是用来处理一类特定的文件
            id: 'babel',
            // 如何处理 .js 文件,用法和 Loader 配置中一样
            loaders: ['babel-loader?cacheDirectory']
        }),

        // 使用 ParallelUglifyPlugin 并行压缩输出的 JS 代码
        new ParallelUglifyPlugin({
            // 传递给 UglifyJS 的参数
            // (还是使用 UglifyJS 压缩,只不过帮助开启了多进程)
            uglifyJS: {
                output: {
                    beautify: false, // 最紧凑的输出
                    comments: false, // 删除所有的注释
                },
                compress: {
                    // 删除所有的 `console` 语句,可以兼容ie浏览器
                    drop_console: true,
                    // 内嵌定义了但是只用到一次的变量
                    collapse_vars: true,
                    // 提取出出现多次但是没有定义成变量去引用的静态值
                    reduce_vars: true,
                }
            }
        })
    ],

    optimization: {
        // 压缩 css
        minimizer: [new TerserJSPlugin({}), new OptimizeCSSAssetsPlugin({})],

        // 分割代码块
        splitChunks: {
            chunks: 'all',
            /**
             * initial 入口chunk,对于异步导入的文件不处理
                async 异步chunk,只对异步导入的文件处理
                all 全部chunk
             */

            // 缓存分组
            cacheGroups: {
                // 第三方模块
                vendor: {
                    name: 'vendor', // chunk 名称
                    priority: 1, // 权限更高,优先抽离,重要!!!
                    test: /node_modules/,
                    minSize: 0,  // 大小限制
                    minChunks: 1  // 最少复用过几次
                },

                // 公共的模块
                common: {
                    name: 'common', // chunk 名称
                    priority: 0, // 优先级
                    minSize: 0,  // 公共模块的大小限制
                    minChunks: 2  // 公共模块最少复用过几次
                }
            }
        }
    }
})

改进5:dev的热更新

1.针对dev引入:

const HotModuleReplacementPlugin = require('webpack/lib/HotModuleReplacementPlugin');

 2.修改入口:

 // index: path.join(srcPath, 'index.js'),
        index: [
            'webpack-dev-server/client?http://localhost:8080/',
            'webpack/hot/dev-server',
            path.join(srcPath, 'index.js')
        ],

3.new插件

 plugins: [
        new webpack.DefinePlugin({
            // window.ENV = 'production'
            ENV: JSON.stringify('development')
        }),
        new HotModuleReplacementPlugin()
    ],

在devServer中添加hot:true

  devServer: {
        port: 8080,
        progress: true,  // 显示打包的进度条
        contentBase: distPath,  // 根目录
        open: true,  // 自动打开浏览器
        compress: true,  // 启动 gzip 压缩

        hot: true,

        // 设置代理
        proxy: {
            // 将本地 /api/xxx 代理到 localhost:3000/api/xxx
            '/api': 'http://localhost:3000',

            // 将本地 /api2/xxx 代理到 localhost:3000/xxx
            '/api2': {
                target: 'http://localhost:3000',
                pathRewrite: {
                    '/api2': ''
                }
            }
        }
    },

在入口文件index.js中增加代码逻辑:设置热更新范围

// 增加,开启热更新之后的代码逻辑
if (module.hot) {
    module.hot.accept(['./math'], () => {
        const sumRes = sum(10, 30)
        console.log('sumRes in hot', sumRes)
    })
}

改进6:dev的dllPlugin动态链接库插件的使用

第三方库比较大,不怎么改变,可以构建一次就是,不用每次都重新构建

比如针对react的两个依赖:

 "dependencies": {
    "react": "^16.12.0",
    "react-dom": "^16.12.0"
  },

新增webpack.dll.js

const path = require('path')
const DllPlugin = require('webpack/lib/DllPlugin')
const { srcPath, distPath } = require('./paths')

module.exports = {
  mode: 'development',
  // JS 执行入口文件
  entry: {
    // 把 React 相关模块的放到一个单独的动态链接库
    react: ['react', 'react-dom']
  },
  output: {
    // 输出的动态链接库的文件名称,[name] 代表当前动态链接库的名称,
    // 也就是 entry 中配置的 react 和 polyfill
    filename: '[name].dll.js',
    // 输出的文件都放到 dist 目录下
    path: distPath,
    // 存放动态链接库的全局变量名称,例如对应 react 来说就是 _dll_react
    // 之所以在前面加上 _dll_ 是为了防止全局变量冲突
    library: '_dll_[name]',
  },
  plugins: [
    // 接入 DllPlugin
    new DllPlugin({
      // 动态链接库的全局变量名称,需要和 output.library 中保持一致
      // 该字段的值也就是输出的 manifest.json 文件 中 name 字段的值
      // 例如 react.manifest.json 中就有 "name": "_dll_react"
      name: '_dll_[name]',
      // 描述动态链接库的 manifest.json 文件输出时的文件名称
      path: path.join(distPath, '[name].manifest.json'),
    }),
  ],
}

在package.json中新增一个dll打包命令:

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "webpack-dev-server --config build/webpack.dev.js",
    "dll": "webpack --config build/webpack.dll.js"
  },

会输出一个索引文件和一个js文件

在webpack.dev.js中:

// 第一,引入 DllReferencePlugin
const DllReferencePlugin = require('webpack/lib/DllReferencePlugin');






   module: {
        rules: [
            {
                test: /\.js$/,
                loader: ['babel-loader'],
                include: srcPath,
                exclude: /node_modules/ // 第二,不要再转换 node_modules 的代码
            },
        ]
    },
    plugins: [
        new webpack.DefinePlugin({
            // window.ENV = 'production'
            ENV: JSON.stringify('development')
        }),
        // 第三,告诉 Webpack 使用了哪些动态链接库
        new DllReferencePlugin({
            // 描述 react 动态链接库的文件内容
            manifest: require(path.join(distPath, 'react.manifest.json')),
        }),
    ],

 

使用babel

新建.babelrc文件:

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

最后转载一篇webpack4—搭建vue项目过程(https://www.imooc.com/article/279078

前言

首先祝大家元宵节快乐,最近已经好久没有写过文章了,刚好趁着这几天刚刚上班,领导还没有来,偷偷的写一篇关于webpack搭建vue的博客。因为公司使用vue比较多,构建vue项目使用vue-cli显得有点臃肿,感觉还是自己配置比较好些,所以就有了这篇教程。由于水平有限,欢迎大家指正,一起进步。

新建项目

1.新建名为webpackconfig文件夹

2.使用命令

npm init -y

在webpackconfig文件夹中生成package.josn

3.下载依赖包

1

npm i webpack webpack-dev-server webpack-cli -D

4.新建src文件夹并在src中创建main.js文件

alert(1)

5.新建webpack.config.js文件

webpack.config.js文件

var path = require('path'); 
var config = {                   
  entry: './src/main.js',                     
  output: {                            
    path: path.resolve(__dirname + '/dist'),//打包生成文件地址
    filename: '[name].build.js',//生成文件ming                     
    publicPath: '/dist/'//文件输出的公共路径     
  } 
} 
module.exports = config;

entry: 引入文件,对象写法可以引入多文件

entry: {     
  app: './src/app.js',     
  vendors: './src/vendors.js'   
}

output:文件输出地址

path: 输出文件地址

filename:输出文件名

publicPath:文件输出路径

6.新建一个index.html文件并引入main.js

<!DOCTYPE html>
<html> 
  <head>         
    <meta charset="UTF-8">         
    <meta name="viewport" content="width=device-width, initial-scale=1.0">        
    <meta http-equiv="X-UA-Compatible" content="ie=edge">         
    <title>Document</title> 
  </head> 
  <body>         
    <script src="/dist/main.build.js"></script> 
  </body> 
</html>

7.配置package.json

"dev": "webpack-dev-server --open --hot",     
"build": "webpack --mode=development --progress --hide-modules",

配置之后运行

npm run dev

会打开一个服务并弹出1

但是webpack会有一个警告,这个警告就是因为没有配置mode,就是没有配置相应模式

mode有两个参数,一个是开发模式development一个是生产模式production。

可以在package.json里直接配置

"dev": "webpack-dev-server --mode=development --open --hot"

这样就没有警告了

接下来运行

npm run build

会打包生成一个新的dist文件夹

5c6b63ac0001c80707980467.jpg

8.引入loader兼容代码

npm i babel-loader babel-core babel-preset-env -D

babel-preset-env 帮助我们配置 babel。我们只需要告诉它我们要兼容的情况(目标运行环境),它就会自动把代码转换为兼容对应环境的代码。

更改webpack.config.js文件

module: {     
  rules: [         
    {                 
      test: '/\.js$/',             
      include: path.resolve(__dirname + '/src'),             
      exclude: /node_modules/,             
    use: [                 
           {                     
              loader: 'babel-loader',                     
              options: ['env', 'stage-0']                 
            }             
          ]         
    }     
  ] 
}

9.下载vue并在main.js引入

import Vue from 'vue'; 
new Vue({       
  el: '#app',       
  data: 
  {              
    msg: 'hello'       
  } 
})

运行项目发现报错

vue.runtime.esm.js:620 [Vue warn]: You are using the runtime-only build of Vue
where the template compiler is not available. Either pre-compile the templates 
into render functions, or use the compiler-included build. 
(found in <Root>)

 

报这个错误原因就是因为使用的是运行版本的vue,编译版本不能用,这时候在我们需要随后我们还要配置别名,将 resolve.alias 配置为如下对象

resolve: {           
  alias: {                 
    'vue$': 'vue/dist/vue.esm.js'                           
  }     
}

然后在运行项目,发现已经在页面上打印出了hello。

一个简单的基于webpack的vue项目已经搭建好了。

接下来就是一些配置

10.配置css

输入命令下载style-loader css-loader

npm i style-loader css-loader -D

配置module中的rules

{     
  test: /\.css$/,     
  use:['style-loader','css-loader'],     
  include: path.resolve(__dirname + '/src/'),     
  exclude: /node_modules/ 
}

测试引入css,新建index.css并在在main.js中引入

index.css

div{       
  color:skyblue; 
}
import './index.css';

可以看到文字颜色已经改变了

5c6b63ad0001b9e118410690.jpg

11.支持图片

输入命令下载file-loader url-loader

npm i file-loader url-loader -D

配置module中的rules

{      
  test: /\.(jpg|png|gif|svg)$/,      
  use: 'url-loader',      
  include: path.resolve(__dirname + '/src/'),      
  exclude: /node_modules/ 
}

测试引入图片,新建asset文件夹放一张图片并在在main.js中引入

import img from'./assets/a.png'

在html中显示

<img :src="img" alt="">

 

5c6b63ad000176f402920282.jpg

12.引入html-webpack-plugin

输入命令下载html-webpack-plugin

npm i html-webpack-plugin -D

设置plugins

var HtmlWebpackPlugin = require('html-webpack-plugin'); 
plugins: [    
  new HtmlWebpackPlugin({         
    template: './index.html',         
    chunks: ['main']                
  }) 
]

13.vue开发需要.vue文件只要引入vue-laoader和vue-template-compiler就行了

输入命令下载vue-loader vue-style-loader vue-template-compiler

npm i vue-loader vue-style-loader vue-template-compiler -D

配置vue-loader

{     
  test: '/\.vue$/',     
  loader: 'vue-loader' 
}

还需要引入vue-loader/lib/plugin

var VueLoaderPlugin = require('vue-loader/lib/plugin');

并在plugin实例化

new VueLoaderPlugin()

新建App.vue

<template>  
  <h1>Hello World!</h1>
</template> 
<script>  
  export default {    
    name: 'App'  
  }
</script> 
<style>
</style>

更改main.js

import Vue from 'vue';
import App from './App.vue'; 
new Vue({  
  el: '#app',  
  render: h => h(App)
});

运行项目

5c6b63ae00019b7c03370190.jpg

14.开启js热更新

因为 vue-style-loader 封装了 style-loader,热更新开箱即用,但是 js 热更新还不能用,每次修改代码我们都会刷新浏览器,所以我们需要继续配置。

const webpack = require('webpack');

并在plugin中配置

new webpack.HotModuleReplacementPlugin()

热更新已静开启

到现在为止webpack构建的vue项目已经跑起来了。

接下来就是一些优化,

15.在resolve配置别名

resolve: {       
  extensions: ['.js', '.jsx','.ts','.tsx', '.scss','.json','.css'],       
  alias: {             
    'vue$': 'vue/dist/vue.esm.js',             
    "@": path.resolve(__dirname, 'src'),             
    "components": path.resolve(__dirname, '/src/components'),             
    "utils": path.resolve(__dirname + '/src/utils'),         
  },         
  modules: ['node_modules']    
}

 

16.支持sass

输入命令下载sass-loader node-sass

npm i sass-loader node-sass -D

修改webpack.config.js的css

{      
  test: /\.sass$/,      
  use:['vue-style-loader', 'css-loader', 'sass-loader'],      
  include: path.resolve(__dirname + '/src/'),       
  exclude: /node_modules/ 
},

基本也配置个差不多了,还需要补充一些东西,以后会加上。

这一篇算是webpack构建vue项目基础吧,下一篇会再次补充并深入,谢谢大家,希望大家能多提意见,一起在码农的道路上越走越远

感恩骗点star项目地址https://github.com/mr-mengbo/webpackconfig


作者:旧巷老友
链接:https://www.imooc.com/article/279078
来源:慕课网
本文原创发布于慕课网 ,转载请注明出处,谢谢合作

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值