初始化一些文件和依赖
新建一个testwebpack的文件夹。
然后在该文件夹下:
npm init
这时候会出现一个文件。
npm i webpack vue vue-loader
这时候警告如下: npm WARN vue-loader@15.2.4 requires a peer of css-loader@* but none is installed. You must install peer dependencies yourself.
npm WARN vue-loader@15.2.4 requires a peer of vue-template-compiler@^2.0.0 but none is installed. You must install peer dependencies yourself.
需要安装css-loader 和vue-template-compiler。
-loader vue
新建文件夹:
<template><divid="app">
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
import Vue from
新建
const path =
> script下添加代码如下:
因为只有在这里配置了,才能运行内部的webpack
"build":
此时在端口运行npm run build
提示如下:
One CLI for webpack must be installed. These are recommended choices, delivered as separate packages
webpack4需要依赖webpack-cli
cli
安装好之后报错如下:
1、The ‘mode’ option has not been set,
webpack4里面需要声明mode来判断是生产环境还是开发环境
详见官网:
修改build:
"build":
2、You may need an appropriate loader to handle this file type.
这个报错说明需要配置loader
配置必要的loader:
module:
此时继续npm run build
报错如下:
vue-loader was used without the corresponding plugin. Make sure to include VueLoaderPlugin in your webpack config.
提示webpack4配置需要包含VueLoaderPlugin
const VueLoaderPlugin =
然后在输出里面配置plugins:
new VueLoaderPlugin()]
此时发现还有报错,原因很简单,没有安装style-loader.
npm i style-loader
这时候就可以正常的 run build 了。
配置图片资源的打包、css预处理器等
新建文件src>assets>image&&src>assets>styles
然后配置loader:
{ test: /.(jpg|jpeg|svg|png|gif)$/, use: { loader: 'url-loader', options: { limit: 1024, filename: '[name].[ext]'} } },
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
安装loader:
-loader url
此时,就基本完成基本配置了。
devServer的使用
俩面的script配置如下:
"dev":
里面进行一些判断,确定是生产环境还是开发环境:
如何判断呢?安装一个cross-env 的包
cross-
修改内容如下:
"build":
然后在定义一个变量:
const isDev = .NODE_ENV ===
如果这个变量为真,则做如下操作:
if (isDev) { config.devtool = '#cheap-module-eval-source-map', config.devServer = {
这时候还需要一个html来展示,
const HTMLPlugin =
new webpack.DefinePlugin({
到这里,基本配置就已经完成了。
postCss、babel-loader使用
-loader babel
- postcss: 后处理css的作用
aotuprefixer
const autoorefixer =
中使用jsx
-env babel
rules添加如下:
{ test: /.jsx$/, loader: 'babel-loader'},
use: [
这里我遇到一个坑,最后在官方文档找到了。
test:/
使用上面的配置无法解析vue中的stylus,需要向下面这样配置:
test:/
这样就可以了。
正式打包的时候,如何分离css文件
--save
webpack4升级后,使用这个会有很多坑,如下:
开发环境的rules不变:
if (isDev) { config.
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
如果是生产环境:
else { config.output.filename =
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
坑1:
webpack4不支持版本,需要使用版本:
-text
坑2:
new ExtractTextPlugin(
这里不能使用style.[contentHash:8].css
到这里最终编译成功~
单独打包vue代码
join(__dirname,
'initial', minChunks: