第一步
执行npm init 命令 初始化出package.json文件
{ "name": "demo1", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC" } name 表示项目的名称version 表示项目的版本号description 对项目的描述main 项目的入口文件script 脚本命令配置author 作者(可以使用项目作者的名字)license 证书第二部
执行 yarn add webpack webpack-cli --save-dev 或者执行 cnpm/npm install webpack webpack-cli --save-dev 其中第一个表示安装webpack打包工具 第二个表示安装webpack脚手架 安装了脚手架才能使用wepback命令 第三部
配置构建脚本 如下面的build脚本
"scripts": { "build": "webpack", "test": "echo \"Error: no test specified\" && exit 1" }配置完成后可以运行npm run build 命令执行项目构建 这时会报错 can not resolve ./src 这是因为找不到项目的入口文件
解决完成后再次执行npm run build 命令发现项目中多出一个dist文件夹 dist文件夹中有一个压缩过后的js文件 main.js 在该文件中可以找到在src文件夹下的index.js的代码 此时表示能够成功打包项目但是终端会提示未设置mode的警告
第四步
配置出入口文件
在项目根目录中创建src文件夹 然后在src文件下创建main.js这时打包会报错 因为没有修改入口文件配置 项目根目录中创建webpack.config.js文件在文件中写入 const path = require('path') module.exports = { // 配置入口文件 入口的值可以是一个字符串 也可以是一个对象 // entry: './src/main.js' entry: { // 入口文件是对象的时候 对象的key(在不配置output的时候)会作为默认生成的js文件的文件名称 index: './src/main.js' }, // 打包输出文件的相关配置 // publicPath : __dirname + '/static/' 表示publicpath(资源引入路径)为绝对路径 // publicPath: '/' 资源引入从根目录开始 // publicPath: './' 代表相对路径 output: { publicPath: '/', // 公共资源引入的路径 path: path.resolve(__dirname, 'dist'), // 将打包生成的文件夹解析到当前项目的跟目录中 filename: 'index.js' // 打包生成的js文件的名称引入bable
使用 npm i @babel/core babel-loader @babel/preset-env @babel/plugin-transform-runtime @babel/polyfill @babel/runtime --save-dev 安装babel相关依赖在项目的根目录中创建名为 .babelrc 的新文件来配置 Babel: { "presets": ["@babel/preset-env"], "plugins": ["@babel/plugin-transform-runtime"] }如果遇到如下警告
WARNING: We noticed you're using the `useBuiltIns` option without declaring a core-js version. Currently, we assume version 2.x when no version is passed. Since this default version will likely change in future versions of Babel, we recommend explicitly setting the core-js version you are using via the `corejs` option. 不仅仅要安装 npm install --save core-js@3 还需要设置 .babelrc 设置 “corejs”: 3{ "presets": [ [ "@babel/preset-env", { "useBuiltIns": "usage", "corejs": 3 } ] ], "plugins": ["@babel/plugin-transform-runtime"] }安装结束后配置babel-loader
// 在webpack.config.js中添加配置 module: { rules: [ test: /\.js$/ exclude: '/node_modules/', use: { loader: 'babel-loader' } ] }