webpack4从0开始构建前端单页项目(5)用babel-loader处理js㈡.babelrc文件

如果在 webpack.config.js 配置文件中写 babel-loader 的配置可能比较麻烦。则可以把 babel-loader 配置抽离出来单独配置。

项目结构(在根目录创建 .babelrc 文件作为 babel-loader 的配置文件)

    project
    |   .babelrc            # babel-loader配置文件
    |   .editorconfig       # 配置格式化插件
    |   package.json        # 项目需要的依赖
    |   webpack.config.js   # webpack配置文件
    |
    +---public
    |       index.html      # 用于打包生成 .html 文件的模板
    |
    \---src
            main.js         # webpack的入口文件

webpack 配置文件

// webpack.config.js
    const webpack = require("webpack");
    const path = require("path");
    const htmlWebpackPlugin = require("html-webpack-plugin");

    module.exports = {
        entry: "./src/main.js",
        mode: "development",
        output: {
            path: path.join(__dirname, "dist"),
            filename: "app.[hash:16].js",
        },
        plugins: [
            new htmlWebpackPlugin({
                filename: "index.html",
                template: "./public/index.html",
                minify: {
                    collapseWhitespace: false,
                },
                inject: true,
            }),
        ],
        devServer: {
            contentBase: path.join(__dirname, "dist"),
            compress: true,
            port: 9000, // 配置端口
            hot: true,
        },

        module: {
            rules: [
                {
                    test: /\.js$/,
                    exclude: /(node_modules|bower_components)/, // 忽略node_modules和bower_components目录下的js的文件
                    use: "babel-loader",
                },
            ],
        },
    };

.babelrc配置文件

    {
        "presets": [
            [
                "@babel/preset-env", {
                    "targets": {
                        "browsers": [">1%", "last 3 version"]
                    }
                }
            ]
        ]
    }
posted @ 2020-09-10 19:03  氵灬  阅读(345)  评论(0编辑  收藏  举报