weback基础配置

139 阅读1分钟

webpack 虽然之前配置过,但是没有记录,后面又不记得了,这次一步一步的记录下来,加深印象。

  1. cnpm i -y

image.png

  1. cnpm i webpack webpack-cli -D

image.png

// src/index.js

let fn = (a, b) => a + b
fn(1, 2)
  1. npx webpack --mode=development 生成的dist/main.js
(() => {
  var __webpack_modules__ = ({
    "./src/index.js": (() => {
      eval("let fn = (a, b) => a + b\r\nfn(1, 2)\n\n//# sourceURL=webpack://webpack2/./src/index.js?");
    })
  });
  var __webpack_exports__ = {};
  __webpack_modules__["./src/index.js"]();
})();
  1. 配置babel ,降级js
cnpm i 
@babel/core 
@babel/preset-env 
@babel/plugin-transform-runtime 
@babel/runtime 
@babel/runtime-corejs3 
-D
//webpack.config.js
module.exports = {
    module: {
        rules: [{
            test: /\.jsx?$/,
            use: ['babel-loader'],
            exclude: /node_modules/
        }]
    }
}

//.babelrc
{
    "presets": ["@babel/preset-env"],
    "plugins": [
        [
            "@babel/plugin-transform-runtime",
            {
                "corejs": 3
            }
        ]
    ]
}


或者将Babel的配置写在webpack.config.js中,

module.exports = {
    module: {
        rules: [
            // {
            //     test: /\.jsx?$/,
            //     use: ['babel-loader'],
            //     exclude: /node_modules/
            // },
            {
                test: /.\jsx?$/,
                use: {
                    loader: "babel-loader",
                    options: {
                        "presets": ["@babel/preset-env"],
                        "plugins": [
                            [
                                "@babel/plugin-transform-runtime",
                                {
                                    "corejs": 3
                                }
                            ]
                        ]
                    }
                },
                exclude: /node_modules/
            },
        ]
    }
}
npx webpack --mode=development ,已经转换为
```js
(() => { // webpackBootstrap
  var __webpack_modules__ = ({
    "./src/index.js": (() => {
      eval("var fn = function fn(a, b) {\n  return a + b;\n};\n\nfn(1, 2);\n\n//# sourceURL=webpack://webpack2/./src/index.js?");
    })
  });
  var __webpack_exports__ = {};
  __webpack_modules__["./src/index.js"]();
})();
  1. 增加mode
//webpack.config.js
mode: "development",
  1. cnpm i html-webpack-plugins -D