造轮子--webpack4&vue2

初始化

我们使用npm init命令初始化一个package.json文件。

npm init

安装webpack

npm i webpack webpack-cli webpack-dev-server --save-dev

安装vue

npm i vue --save

创建相应文件

createVue
  |--dist
  |--webpack.config.js
  |--src
      |--main.js
  |--index.html
===index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>webpack4-vue-demo</title>
</head>
<body>
    <div id="app"></div>
    <script src="./dist/bundle.js"></script>
</body>
</html>
====main.js
import Vue from 'vue';

new Vue({
    el: '#app',
    data: {
        message: "hello"
    }
});
===webpack.config.js
const webpack = require('webpack');

module.exports = {
  entry: './src/main.js', //入口
  output:{
      path: path.resolve(__dirname, 'dist'),
      filename: "bundle.js"
  },
  resolve: {
    extensions: ['.js', '.vue', '.json'],
    alias: {
      '@': resolve('src')
    }
  }
};

打包

webpack

打包过后,dist文件夹出现打包后的文件,再通过IDEA打开index.html,就可以看到内容。

打开index.html后,控制台报错

[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.

解决方法:

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

改造成vue文件

createVue
  |--dist
  |--webpack.config.js
  |--src
      |--main.js
      |--App.vue
  |--index.html
====main.js
import Vue from 'vue';
import App from './APP';

new Vue({
    el: '#app',
    render:h=>h(App)
});
====App.vue
<template>
  <div id="app">
    hello world
  </div>
</template>

<script>
export default {
  name: 'app'
}
</script>

如果直接运行,发现报错。
解决方案:

npm install -D vue-loader vue-template-compiler

请在webpack.config.js添加如下:

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

module.exports = {
  module: {
    rules: [
      // ... 其它规则
      {
        test: /\.vue$/,
        loader: 'vue-loader'
      }
    ]
  },
  plugins: [
    // 请确保引入这个插件!
    new VueLoaderPlugin()
  ]
}

自动注入

将打包后的文件自动注入index.html。

npm install --save-dev html-webpack-plugin

将index.html页面中的"<script src="./dist/bundle.js"></script>" 删除。
在webpack.config.js 中增加如下配置:

const HtmlWebpackPlugin = require('html-webpack-plugin')
...

plugins:[
     new HtmlWebpackPlugin({
            filename: 'index.html',
            template: 'index.html',
            inject: 'body',
            favicon: 'favicon.ico',
            minify: {
                removeAttributeQuotes: true // 移除属性的引号
            }
        })
]

运行"npm build", 生成的index.html中自动注入打包好的js文件。

改造webpack.config.js

npm i webpack-merge --save-dev

新建两个文件,webpack.prod.js和webpack.dev.js。

createVue
  |--dist
  |--webpack.config.js
  |--webpack.dev.js
  |--webpack.prod.js
  |--src
      |--main.js
      |--App.vue
  |--index.html
======= webpack.dev.js
const merge = require('webpack-merge');
const common = require('./webpack.config.js');
const path = require('path');

module.exports = merge(common, {
  devtool: 'inline-source-map',
  devServer: { // 开发服务器
    contentBase: './dist'    //告诉开发服务器(dev server),在哪里查找文件
  },
  output: { // 输出
    filename: 'js/[name].[hash].js',  // 每次保存 hash 都变化
    path: path.resolve(__dirname, './dist')
  },
  module: {},
  mode: 'development',
});
======= webpack.prod.js
const path = require('path');
// 合并配置文件
const merge = require('webpack-merge');
const common = require('./webpack.config.js');

module.exports = merge(common, {
  module: {},
  plugins: [],
  mode: 'production',
  output: {
    filename: 'js/[name].[chunkhash].js', 
    path: path.resolve(__dirname, './dist')
  },
});

接下来,在package.json的scripts 配置中添加运行脚本:

"scripts": {
  "start": "webpack-dev-server --open --config webpack.dev.js",
  "build": "webpack --config webpack.prod.js"
},

当我们打包的时候webpack4会报错

The 'mode' option has not been set, webpack will fallback to 'production' for this value. Set 'mode' option to 'development' or 'production' to enable defaults for each environment.
You can also set it to 'none' to disable any default behavior. Learn more: https://webpack.js.org/concepts/mode/

解决方法:

"scripts": {
  "start": "webpack-dev-server --mode=development --open --config webpack.dev.js",
  "build": "webpack --mode=production --config webpack.prod.js"
},

热替换

在webpack.dev.js 中增加如下配置:

devServer: {
  hot: true
},
plugins: [
  new webpack.NamedModulesPlugin(),
  new webpack.HotModuleReplacementPlugin()
],

压缩js

npm i -D uglifyjs-webpack-plugin

请在webpack.prod.js添加如下配置:

const UglifyJsPlugin = require('uglifyjs-webpack-plugin')

module.exports = {
  plugins: [
    new UglifyJsPlugin()
  ]
}

清理 /dist 文件夹

npm install clean-webpack-plugin --save-dev

请在webpack.prod.js添加如下配置:

const UglifyJsPlugin = require('uglifyjs-webpack-plugin')

module.exports = {
  plugins: [
    new CleanWebpackPlugin(['dist'])
  ]
}

引入babel

复制代码由于在使用vue时会用到很多es6的语法,但是现在很多浏览器对es6的支持不是很好,所以在编译时需要将这些语法转换es5的语法,此时我们使用babel来进行编译。

npm install --save-dev babel-core babel-loader babel-preset-env babel-plugin-transform-runtime
  • babel-loader 用于让 webpack 知道如何运行 babel
  • babel-core 可以看做编译器,这个库知道如何解析代码
  • babel-preset-env 这个库可以根据环境的不同转换代码

请在webpack.config.js添加如下配置:

module:{
    rules:[
        {
            test: /\.js$/,
            loader:"babel-loader",
            exclude: /node_modules/
        }
    ]
}

目录下创建.babelrc文件用于配置 babel :

{
  "presets": ["env"],
  "plugins": ["@babel/plugin-transform-runtime"]
}

IE下报Promise未定义错误解决方法:

npm install babel-polyfill --save

在main.ts中 import "babel-polyfill";

Babel 默认只转换新的 JavaScript 句法(syntax),而不转换新的 API,如果想让这个方法运行,必须使用babel-polyfill,为当前环境提供一个垫片。

引入vue-router

npm install --save vue-router

添加 src/router/routes.js 文件,用于配置项目路由:

import Vue from 'vue';
import Router from 'vue-router';

Vue.use(Router);

export default new Router({
  routes: [
    { path: '', component: () => import ('@/views/Home')}
  ]
});

新创建文件如下:

createVue
  |--dist
  |--webpack.config.js
  |--webpack.dev.js
  |--webpack.prod.js
  |--src
      |--views
        |--Home.vue
      |--router
        |--routes.js
      |--main.js
      |--App.vue
  |--index.html

运行npm start,发现报错了!!!

注意
如果您使用的是 Babel,你将需要添加 syntax-dynamic-import 插件,才能使 Babel 可以正确地解析语法。
找了好久,才发现,原来还需要装这个插件~~~哭.jpg
npm install --save-dev @babel/plugin-syntax-dynamic-import

// .babelrc
{
  "plugins": ["@babel/plugin-syntax-dynamic-import"]
}

到这儿,完成了基本的框架,剩下的可以看自己的项目需要进行选择了。

相关推荐