造轮子--webpack4&vue2

栏目: JavaScript · 发布时间: 5年前

内容简介:我们使用npm init命令初始化一个package.json文件。打包过后,dist文件夹出现打包后的文件,再通过IDEA打开index.html,就可以看到内容。解决方法:

初始化

我们使用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()
  ]
}

改造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].[contenthash].js', //contenthash 若文件内容无变化,则contenthash 名称不变
    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"]
}

HtmlWebpackPlugin 插件

将打包后的文件自动注入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()
]

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

引入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"]
}

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


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Designing with Web Standards (2nd Edition)

Designing with Web Standards (2nd Edition)

Jeffrey Zeldman / Peachpit Press / 2006-07-06 / USD 44.99

Best-selling author, designer, and web standards evangelist Jeffrey Zeldman has updated his classic, industry-shaking guidebook. This new edition--now in full color--covers improvements in best prac......一起来看看 《Designing with Web Standards (2nd Edition)》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

随机密码生成器
随机密码生成器

多种字符组合密码

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码