preface
Webpack has a wide range of applications, and even if you don’t use it in depth, you still need to know something about it. This article does not describe in detail the installation steps and some concepts of each step, because the webpack official website has been written in great detail, and there are many online learning webpack documents, but in the process of learning, I did not find the document for the combination of Vue and Webpack, and I also encountered many problems in learning configuration. Therefore, The purpose of this article is to document the complete configuration and some bugs encountered
Learning materials
Webpack website: www.webpackjs.com/ vue website: cn.vuejs.org/
Install the WebPack and initialize it
1. Install WebPack as follows (node.js has been installed) :
NPM install --save-dev webpack-cli NPM install --save-dev webpack-cli NPM init // initialize the projectCopy the code
When initializing the project, select the appropriate option according to the question. After initialization, there will be a package.json file in the project
Create webpack.common.js, webpack.dev.js, webpack.prod.js (name can be changed)
The default webpack configuration file name is webpack.config.js, but the environment is usually separated, so delete webpack.config.js and create the following three files: public environment, development environment, and production environment
3. Modify package.json
Json and alias the current environment with set NODE_ENV=. Note that the XXName of set NODE_ENV=XXName cannot be preceded by Spaces, otherwise Spaces will be included in the current environment name
"scripts": {
"build": "set NODE_ENV=production&& webpack --config webpack.prod.js"// Set production environment to NPM build, production environment name to production, production environment configuration file to webpack.prod.js (same below)"start": "set NODE_ENV=development&& webpack-dev-server --open --config webpack.dev.js"
},
Copy the code
4. Other documents
- Index.html, the page the browser needs to run
- SRC folder, where the relevant code is stored
- SRC /main.js entry file for the project
- Store SRC /assets images and other resources
- SRC/common js method
- SRC /page Related code page
- App.vue VUE home page
- Static Project Static resource folder page layout refer to vue-CLI, or you can configure according to your own custom
Project directory
Complete configuration
1. The configuration in webpack.common.js is as follows
const path = require('path'); Const VueLoaderPlugin = require(const VueLoaderPlugin = require('vue-loader/lib/plugin'// add vue-loader const MiniCssExtractPlugin = require('mini-css-extract-plugin'Module.exports = {entry: {app:'./src/main.js'// Import file}, // path alias -- in vue files, you can use @ or static abbreviation path resolve: {extensions: ['.js'.'.vue'.'.json'].alias: {
The '@': path.resolve(__dirname, 'src'),
static: path.resolve(__dirname, 'static'}}, // plugins: [new VueLoaderPlugin(), // plugins: [new VueLoaderPlugin(), // new vue-loader new MiniCssExtractPlugin({filename:'static/style/style.css'Output: {filename: process.env.node_env === output: {filename: process.env.node_env ==='production' ? 'static/js/[name].[chunkhash].js' : 'static/js/[name].[hash].js'// Chunkhash cannot be used with hot updates. The development environment uses hot updates, so we need to distinguish between the development and production environment chunkFilename:'static/js/[name].bundle.js'Resolve (__dirname,'dist'),
publicPath: process.env.NODE_ENV === 'production' ? '/' : '/'}, // module: {rules: [{test: /\.vue$/,
loader: 'vue-loader'}, / / it will be applied to the common ` js ` file / / and ` vue ` file ` < script > {` blocktest: /\.js$/,
use: [
'babel-loader'// exclude: file => (/node_modules/.test(file) &&! /\.vue\.js/.test(file) ) }, {test: /\.(png|svg|jpg|gif)$/,
use: [
{
loader: 'file-loader',
options: {
limit: 10240,
name:"static/imgs/[name].[ext]"// Output file name esModule:false}}],}, {test: /\.(woff|woff2|eot|ttf|otf)$/,
use: [
{
loader: 'file-loader',
options: {
limit: 10240,
name:"static/fonts/[name].[ext]",
esModule: false}}]}, // Extract CSS {test: /\.css$/,
use: [
process.env.NODE_ENV !== 'production'
? 'vue-style-loader'
: MiniCssExtractPlugin.loader,
'css-loader',]}, {test: /\.less$/,
use: [
process.env.NODE_ENV !== 'production'
? 'vue-style-loader'
: MiniCssExtractPlugin.loader,
'css-loader'.'less-loader',]},]},};Copy the code
2. The configuration in webpack.dev.js is as follows
// merge configuration files const merge = require('webpack-merge')
const common = require('./webpack.common.js')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = merge(common, {
devtool: 'inline-source-map'// Hot update devServer: {hot:true,
contentBase: './src/main.js',
host: 'localhost'}, plugins: [// browser preview page new HtmlWebpackPlugin({title:'development',
filename: 'index.html',
template: 'index.html'}), new webpack. NamedModulesPlugin (), / / check to fix (patch) dependence - view the new changes of webpack. HotModuleReplacementPlugin ()],})Copy the code
3. Webpack.prod. js is configured as follows
// Const merge = require('webpack-merge');
const common = require('./webpack.common.js');
const TerserPlugin = require('terser-webpack-plugin'); Const {CleanWebpackPlugin} = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin'); Module. exports = merge(common, {devtool:'source-map'// Production environment error message mode:'production'New CleanWebpackPlugin(), // Provide the generated index.html template new HtmlWebpackPlugin({title:'productionPage',
template: 'index.html'}),], optimization: {// compress js minimize:true,
minimizer: [
new TerserPlugin({
test: /\.js(\? . *)? $/ I,})], // Decompress code - This separates the vUE source code, and the project code separately generates a JS file, splitChunks: {cacheGroups: {vendors: {vendors: {vendors: {test: /[\\/]node_modules[\\/]/,
name: 'vendors'// Public files have defined non-entry bundle locations in chunks:'initial'}}}},});Copy the code
Other Page Configuration
- .babelrc ES6 code parsing file
{
"presets": [["env", {
"modules": false."targets": {
"browsers": ["1%" >."last 2 versions"."not ie <= 8"]}}]],"plugins":[]
}
Copy the code
- Main.js entry file
import Vue from 'vue'
import App from './App.vue'
export const vue = new Vue({
render: (h) => h(App)
}).$mount('#app')
Copy the code
- App.vue After configuration, you can write vUE project according to the normal VUE page writing method
<template>
<div id="app" class="container">
<img src="./assets/img/page.png">
<img :src="imgs" alt="">
<img :src="imgs2" alt="">
<p class="p-test">{{ greeting }} world! ddd!! </p> <home></home> </div> </template> <script> import imgs from'@/assets/img/page.png'
import imgs2 from 'static/img/finger.png'
import home from '@/pages/home'
export default {
name: 'App',
components: { home },
props: {},
data() {
return {
imgs: imgs,
imgs2: imgs2,
greeting: "Hello"}; }, computed: {}, watch: {},created() {},mounted() {},
methods: {},
}
</script>
<style lang="less">
@import 'static/style/common.less';
.container{
.p-test{
color: red
}
}
</style>
Copy the code
The following plug-ins need to be installed:
NPM install --save lodash // Used to package lodash dependencies NPM install --save-dev style-loader CSs-loader // Load CSS NPM install NPM install --save-dev html-webpack-plugin --save-dev html-webpack-plugin --save-dev html-webpack-plugin Install clean-webpack-plugin --save-dev NPM install --save-dev NPM install --save webpack-merge NPM install --save terser-webpack-plugin --save uglifyjs-webpack-plugin --save terser-webpack-plugin Uglifyjs NPM install -- save-dev@babel /plugin-syntax-dynamic-import Mini-css-extract -plugin // CSS extract // install vue NPM install vue NPM install -d vue-loader vue-template-compiler // Install vUE -loader and UE -template-compiler NPM install -d pass-loader node-sass // compile <style> tag NPM install -d less less-loader // Compile the <style> tag (select what is needed) // ES6 preprocessor NPM install ES6-PROMISE // Handle ES6 NPM install -d babel-core NPM install [email protected] // Need to match babel-core version NPM install --save-dev babel-plugin-transform-runtime NPM install --save babel-runtime npm install babel-preset-env --save-devCopy the code
If omitted refer to package.json file: github.com/SaltedFishH…
Problem solving
1. The babel-Loader version does not match
NPM install [email protected]Copy the code
Babelrc file is empty
3, babelrc internal Settings error
NPM install babel-preset-env --save-dev //. Babelrc sets env and installs the appropriate pluginCopy the code
4, csS-loader and style-loader order error
5. Chunkhash cannot be used with hot updates
conclusion
At this point, the project can use NPM run build to package the project and NPM start to run the project. The routing configuration of VUE is still a work in progress, waiting to be updated in the next study 2 document. ‘. Git address of this project: github.com/SaltedFishH…