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

本文介绍了如何从零开始搭建Webpack和Vue的开发环境,并详细解释了配置过程中的关键步骤。包括Webpack配置、Vue模板编译选项的选择及npm脚本的使用。

前言: 使用了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

转载于:https://juejin.im/post/5a7527e8f265da4e6f17b788

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值