玩转webpack(01):初识webpack

一、webpack配置组成

webpack默认配置文件:bebpack.config.js

可以通过webpack --config指定配置文件


moudle.exports = {

        entry: './src/index.js',        ————打包的入口文件

        output: './dist/main.js',        ————打包的输出

        mode: 'prouction',        ————环境

        moudle:{

                rules:[        ————loader配置

                        {test:/\.txt$/,use:'raw-loader'}

                ]

        },

        plugins:[

                new HtmlwebpackPlugin({

                        template: './src/index.html'

                })

        ]

}

零配置的webpack包含哪些配置

  • 指定默认的entry为:./src/index.js
  • 指定默认的output为:./dist/main.js

二、安装Node.js和NPM

1、安装nvm(nodejs的包管理器)

  • 通过 curl 安装:curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bash
  • 通过 wget 安装:wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bash
  • 安装完成需要配置环境变量:source ~/.bash_profile 

2、安装Node.js 和 npm

nvm install v10.15.3

nvm list   (查看计算机上安装的所有的nodejs的版本)

三、环境搭建——安装webpack和webpack-cli

1、新建空目录

在新建的目录中打开终端

执行:npm init -y

2、安装webpack和webpack-cli

npm i webpack webpack-cli --save-dev

四、一个简单的例子 

webpack.config.js

 'use strict'

 const path = require('path');
 module.exports = {
    entry: './src/index.js',
    output: {
        path: path.join(__dirname, 'dist'),
        filename: 'bundle.js'
    },
    mode: 'production'
 }

src/index.js

 import { helloWorld } from "./helloWorld";
 document.write(helloWorld());

src/helloWorld.js

export function helloWorld(){
    return 'hello webpack!'
}

代码编写完成后,在当前目录下运行:

./node_modules/.bin/webpack

在dist目录下新建index.html ,并在浏览器打开此文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script src="./bundle.js"></script>
</body>

</html>

配置快捷打包方式:修改package.json

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack"
  },

猜你喜欢

转载自blog.csdn.net/m0_47135993/article/details/128075800