wepback基础配置(构建一个vue-cli)--1

197 阅读2分钟

前言: 使用了webpack和vue有一段时间了,但其实对于这两者的配合使用原理一直模糊不清,这带来了一些问题,比如优化,拓展新需求。我想要搞清楚从每一个配置项是为了什么,我到底需不需要这些配置。趁着新的一年,先给自己定个小目标--掌握webpack。

此次学习过程以webpack中文文档为指导,结合vue官网文档进行实践

webpack环境搭建

mkdir webpack-demo && cd webpack-demo

npm init

npm install --save-dev webpack

将用到的所有依赖库通过npm/yarn的形式进行安装,这使得webpack能够构建一个依赖图。

一步步搭建vue-cli

npm install vue
项目目录:
webpack-demo
  |- package.json
  |- webpack.config.js
  |- index.html
  |- /src
    |- app.js
依赖打包:

index.html内容:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>webpack demo</title>
</head>
<body>
  <div id="app"></div>
  <script src="bundle.js"></script>
</body>
</html>

app.js内容:

import Vue from 'vue';
// import App from './App.vue';

Vue.config.devtools = true;
Vue.config.performance = true;
Vue.config.productionTip = false;

const app = {
  template: '<h1>HELLO,PADAKER</h1>'
}

new Vue({
  el: '#app',
  template: '<app />',
  components: {
    app
  }
});

webpack.config.js内容:

const path = require('path');

module.exports = {
  entry: './src/app.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, '')
  }
};

此时执行npx webpack --config webpack.config.jswebpack会开始执行依赖打包,将所有依赖打包输出到bundle.js中。此时我们在浏览其中打开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.

这是为啥呢,翻翻官网文档,发现我们的app.js文件里用到了template选项,就错在这。vue需要将模板编译器将字符串模板编译成render函数,但是runtime-only构建中不包含编译器,因为加上编译器vue的文件体积会增大许多。so,有两种解决方案:

  1. 加上编译器,修改webpack.config.js
module.exports = {
  // ...
+  resolve: {
+   alias: {
+     'vue$': 'vue/dist/vue.esm.js'
+   }
+ }
}

再次打包,打开index.html,OK,但是发现bundle.js大了80KB(未压缩)
2. 直接使用render函数取代template

// ...
const app = {
- // template: '<h1>HELLO,PADAKER</h1>'
+ render(h) {
+   return h('h1', 'HELLO,PADAKER');
+ }
}

new Vue({
  el: '#app',
+ render(h) {
+   return h('app');
+ },
- // template: '<app />',
 components: {
    app
  }
});
  1. 当然了,当使用.vue单文件组件时,配合vue-loader直接就编译成render函数了。(这也算是一个最佳实践了)
脚本命令(scripts)

为了方便,以至于每次要打包时都不需要输入一长串命令字符,使用npm script,可以缩短命令长度。
说白了,它就是一个别名,在package.json里面可有进行定义。
package.json

{
  ...
  "scripts": {
    "build": "webpack --config webpack.config.js"
  },
  ...
}

再要进行打包,只需要在项目根目录命令行中输入npm run build