Webpack中babel,vue-loader的使用

887 阅读3分钟

2.6.4:设置babel

  • Babel是一个工具链,主要用于旧浏览器或者环境中将ECMAScript 2015+代码转换为向后兼容版本的JavaScript;
  • 包括:语法转换、源代码转换等;
  • 如果我们希望在命令行尝试使用babel,需要安装如下库: @babel/core:babel的核心代码,必须安装;
  • @babel/cli:可以让我们在命令行使用babel;
  • npm install @babel/core @babel/cli -D
    
  1. 创建demo.js

    const message = "Hello World";
    const names = ["abc", "cba", "nba"];
    ​
    names.forEach(item => console.log(item));
    
  2. src:是源文件的目录; --out-dir:指定要输出的文件夹dist;

    npx babel demo.js --out-dir dist #生成dist文件夹
    npx babel demo.js --out-file test.js #生成test.js文件
    
  3. 插件的使用

    1. npm install @babel/plugin-transform-arrow-functions -D
    
    • 可以把arrow函数转为普通函数
    2. npx babel demo.js --out-file test.js --pliguns=@babel/plugin-transform-arrow-functions
    
    • 查看转换后的结果:我们会发现 const 并没有转成 var
    • 我们需要使用 plugin-transform-block-scoping 来完成这样的功能
     npm install @babel/plugin-transform-block-scoping -D
    
    2. npx babel demo.js --out-file test.js --pliguns=@babel/plugin-transform-arrow-functions,@babel/plugin-transform-block-scoping 
    
    • 但是如果要转换的内容过多,一个个设置是比较麻烦的,我们可以使用预设(preset):

    • 安装@babel/preset-env预设:

      npm install @babel/preset-env -D
      
      npx babel demo.js --out-file test.js --presets=@babel/preset-env
      
  4. Babel底层原理

  • 就是编译器,事实上我们可以将babel看成就是一个编译器。 p Babel编译器的作用就是将我们的源代码,转换成浏览器可以直接识别的另外一段源代码;
  • Babel也拥有编译器的工作流程:
  • 解析阶段(Parsing)
  • 转换阶段(Transformation)
  • 生成阶段(Code Generation)

  • 构建工具中通过配置babel来对其进行使用的,比如在webpack中。

  • 那么我们就需要去安装相关的依赖:

    • 如果之前已经安装了@babel/core,那么这里不需要再次安装;

      npm install babel-loader @babel/core
      
    • 配置规则使用babel

      const path = require("path");
      const { CleanWebpackPlugin } = require("clean-webpack-plugin");
      const HtmlWebpackPlugin = require("html-webpack-plugin");
      const { DefinePlugin } = require("webpack");
      const CopyWebpackPlugin = require('copy-webpack-plugin');
      ​
      module.exports = {
        // 设置模式
        // development 开发阶段, 会设置development
        // production 准备打包上线的时候, 设置production
        mode: "development",
        // 设置source-map, 建立js映射文件, 方便调试代码和错误
        devtool: "source-map",
        
        entry: "./src/main.js",
        output: {
          path: path.resolve(__dirname, "./build"),
          filename: "js/bundle.js",
          // assetModuleFilename: "img/[name]_[hash:6][ext]"
        },
        module: {
          rules: [
            {
              test: /.css$/,
              use: ["style-loader", "css-loader", "postcss-loader"],
            },
            {
              test: /.less$/,
              use: ["style-loader", "css-loader", "less-loader"],
            },
            // },
            {
              test: /.(jpe?g|png|gif|svg)$/,
              type: "asset",
              generator: {
                filename: "img/[name]_[hash:6][ext]",
              },
              parser: {
                dataUrlCondition: {
                  maxSize: 10 * 1024,
                },
              },
            },
            {
              test: /.(eot|ttf|woff2?)$/,
              type: "asset/resource",
              generator: {
                filename: "font/[name]_[hash:6][ext]",
              },
            },
            // {
            //   test: /.js$/,
            //   use: {
            //     loader: "babel-loader",
            //     options: {
            //       // plugins: [
            //       //   "@babel/plugin-transform-arrow-functions",
            //       //   "@babel/plugin-transform-block-scoping",
            //       // ]
            //       presets: [
            //         "@babel/preset-env"
            //       ]
            //     }
            //   }
            // }
            {
              test: /.js$/,
              use: {
                loader:"babel-loader",
                options: {
                  //plugins: [
                    //"@babel/plugin-transform-arrow-functions",
                    //"@babel/plugin-transform-block-scoping"
                 // ]
                  presets: [
                    "@babel/preset-env"
                  ]
                  //如果preset需要配置其他额外参数需要这么写
                  //presets: [
                    //["@babel-preset-env",{
                      
                    //}]
                  //]
                }
              } //配置babel-loader
            }
          ],
        },
        plugins: [
          new CleanWebpackPlugin(),
          new HtmlWebpackPlugin({
            template: "./public/index.html",
            title: "哈哈哈哈"
          }),
          new DefinePlugin({
            BASE_URL: "'./'"
          }),
          new CopyWebpackPlugin({
            patterns: [
              {
                from: "public",
                to: "./",
                globOptions: {
                  ignore: [
                    "**/index.html"
                  ]
                }
              }
            ]
          })
        ],
      };
      ​
      
  • 5.抽离babel,创建于postcss一样的config文件

    • 5.1创建babel.config.js

      module.exports = {
         presets: [
          "@babel/preset-env"
        ]
      }
      
    • 5.2webpack.config.js中只需要写成以下这种格式就可以

       {
              test: /.js$/,
              loader:"babel-loader"
       }
      

2.7:Vue源码的打包

2.7.1:安装vue@next

npm install vue@next

2.7.2: 在main.js中以模块方式使用vue

import { createApp } from 'vue';
import { sum } from "./js/math";
const { priceFormat } = require("./js/format");
​
import App from './vue/App.vue';
​
import "./js/element";
​
console.log(sum(20, 30));
console.log(priceFormat());
​
 const app = createApp({
  template: `<h2>我是vue渲染出来的</h2>`,
   data() {
     return {
       title:"hello wolrd"
     }
   }
 });
const app = createApp(App);
app.mount("#app");

2.7.3:Vue打包后会有不同版本的解析

如图所示:

[注意​]  以上这张图是三种方式来编写DOM

2.7.4:创建vue文件夹并且创建App.vue

<template>
  <h2>我是Vue渲染出来的</h2>
  <h2>{{title}}</h2>
  <hello-world></hello-world>
</template><script>
  export default {
    components: {
      HelloWorld
    },
    data() {
      return {
        title: "Hello World",
        message: "哈哈哈"
      }
    },
    methods: {
​
    }
  }
</script><style scoped>
  h2 {
    color: red;
  }
</style>

2.7.4.2:修改main.js的vue引入

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

2.7.4.3:引入新的文件vue就意味着需要用一个loader来进行识别

npm install vue-loader@next -D 
{
  test:/.vue$/,
  loader:"vue-loader" -> compiler-sfc
}

2.7.4.4:如果以上代码进行打包报错使用 @vue/compiler-sfc -D

npm i @vue/compiler-sfc -D

接下来还必须在webpack.config.js中配置VueLoaderPlugin

const {VueLoaderPlugin} = require("vue-loader/dist/index")

然后配置plugin,就可以正常打包

plugins: [
   new VueLoaderPlugin()
]

如果有tree shaking报错使用这段代码