实验环境
Node: V10.8.0, NPM:V6.3.0, Windows10
实验步骤
- 初始化一个项目
npm init
- 安装webpack
由于webpack升级到webpack4,你必须同时安装webpack cli,同时为了多个项目是webpack版本的冲突,最好还是安装到本地
npm install webpack webpack-cli --save-dev
- 安装基本的Vue框架以及plugin
npm install html-webpack-plugin --save-dev
这个插件的主要作用是产生一个通过script
tag包含webpack产生的bundle.js的html5文件
npm install vue
这个不解释:引入Vue框架 - 建立项目目录接口以及编写Webpack配置webpack.config.js
// 目录结构
project
└───folder1
│ │ index.js
│ │ file012.txt
│ index.html
| package.json
| webpack.config.js
// webpack.config.js
// 注意在package.json中要指定
"scripts": {
"start": "webpack --config webpack.config.js"
}
运行npm run start 进行打包,直接运行webpack --config webpack.config.js是无效的
const path = require('path');
const htmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
mode: 'production',
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
},
plugins: [
new htmlWebpackPlugin({
title:'Vue-webpack',
inject:'body',
filename:'index.html',
template:path.resolve(__dirname,"index.html")
})
],
resolve: {
alias: {
'vue': 'vue/dist/vue.js'
}
}
}
进阶配置
到了现在我们已经打包了一个基本的Vue应用了,我们还需要对其进行一些更高级的配置才能用于日常开发,以及生产环境。HMR(Hot Module Replacement),热加载
npm install --save-dev webpack-dev-server
// 在webpack.config.js 中配置 devServer: { contentBase: './dist', hot: true } // package.json "scripts": { "start:dev": "webpack-dev-server --open" } // 直接运行 npm run start:dev 就可以看到自动打开浏览器并启动了热加载
加载css
npm install --save-dev style-loader css-loader
// 在webpack.config.js 中配置 moudle: { rules: [ { test: /\.css$/, use: [ // loader 处理是从下往上构建的 'style-loader', 'css-loader' ] } ] }
加载图片(字体)
npm insatll --save-dev file-loader
// 在webpack.config.js 中配置 { test: /\.(png|svg|jpg|gif)$/, use: [ 'file-loader' ] }
开发环境使用source map 便于调试
当webpack打包代码是,会把所有的源文件打包到一个bundle.js中,对于错误的定位不是很方便,为了更方便调试,webpack提供了source map功能// 在webpack.config.js 中配置 devtool: 'inline-source-map', 'source-map'、'cheap-eval-source-map' 具体见:(https://www.webpackjs.com/configuration/devtool/)
Vue单文件结构
npm install --save-dev vue-loader vue-template-complier
// 在webpack.config.js 中配置 const vueLoaderPlugin = require('vue-loader/lib/plugin'); plugins: [ new vueLoaderPlugin() ]
编译ES6代码,兼容老浏览器
npm install --save-dev babel-loader babel-core
// 在webpack.config.js 中配置 { test: /\.js$/, use: 'babel-loader' }
暂时就这些了,以后还有更骚的操作再更新。