webpack-从零搭建vue过程

2020-08-10  本文已影响0人  钊神归来
1、使用npm init初始化项目

执行了npm init之后,会让我们填写一些配置信息,如果还不知道怎么填写的话可以一路回车,会生成一个pakeage.json文件,文件内容如下:

{
  "name": "webpackinit",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack"
  },
  "author": "",
  "license": "ISC"
}
2、需要安装vue
npm install vue --save
3、如果你需要在客户端编译模板 (比如传入一个字符串给 template 选项,或挂载到一个元素上并以其 DOM 内部的 HTML 作为模板),就将需要加上编译器,即完整版:
// 需要编译器
new Vue({
  template: '<div>{{ hi }}</div>'
})

// 不需要编译器
new Vue({
  render (h) {
    return h('div', this.hi)
  }
})

当使用 vue-loader 或 vueify 的时候,*.vue 文件内部的模板会在构建时预编译成 JavaScript。你在最终打好的包里实际上是不需要编译器的,所以只用运行时版本即可。

因为运行时版本相比完整版体积要小大约 30%,所以应该尽可能使用这个版本。如果你仍然希望使用完整版,则需要在打包工具里配置一个别名:

module.exports = {
  // ...
  resolve: {
    alias: {
      'vue$': 'vue/dist/vue.esm.js' // 用 webpack 1 时需用 'vue/dist/vue.common.js'
    }
  }
}
4、需要安装合适的loader和模板编译器去加载后缀为.vue的文件
npm install vue-loader vue-template-compiler  --save-dev

在webpack.config.js配置一下vue-loader

module.exports = {
    ...
    module: {
        rules: [
            {
                test: /\.vue$/,
                use: [
                    { loader: "vue-loader" },
                ]
            }
        ]
    }
};

Vue-loader在15.*之后的版本都是 vue-loader的使用都是需要伴生 VueLoaderPlugin的,所以在webpack.config.js中加入

const path = require('path');
const VueLoaderPlugin = require('vue-loader/lib/plugin');
module.exports = {
    entry: './src/main.js',
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'bundle.js'
    },
    plugins: [
        // make sure to include the plugin for the magic
        new VueLoaderPlugin()
    ],
    module:  {
      ...
    }
};
5、通过html-webpack-plugin插件把index.html文件打包到dist文件夹
1597043180(1).jpg

先安装html-webpack-plugin插件 npm install --save-dev html-webpack-plugin,然后配置webpack.config.js

module.exports = {
    entry: './src/main.js',
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'bundle.js'
    },
    plugins: [
        new HtmlWebpackPlugin({template: 'index.html'})
    ],
}
6、搭建本地dev服务器

先安装webpack-dev-server;npm install webpack-dev-server --save-dev
然后在webpack.config.js文件配置:

const path = require('path');
module.exports = {
    entry: './src/main.js',
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'bundle.js'
    },
    devServer: {
        contentBase: path.join(__dirname, "dist"),
        compress: true,
    },
};

最后在package.json文件配置一下运行webpack-dev-server的脚本

  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "webpack-dev-server",
    "build": "webpack"
  },
上一篇 下一篇

猜你喜欢

热点阅读