前提条件
在开始之前,请确保安装了 Node.js 的最新版本。
第一步:新建一个项目文件夹
文件目录结构如下:
.+-- src| ??+-- bar.js| ??+-- index.js+-- index.html+-- webpack.config.js
bar.js
export default function bar() {}
index.js
import bar from ‘./bar‘;bar();
index.html
<!DOCTYPE html><html lang="en"><head> ?<meta charset="UTF-8"> ?<meta name="viewport" content="width=device-width, initial-scale=1.0"> ?<meta http-equiv="X-UA-Compatible" content="ie=edge"> ?<title>Document</title></head><body> ?<script src="dist/bundle.js"></script></body></html>
webpack.config.js
const path = require(‘path‘); //node内置的模块,用来设置路径// 因为我们整个js文件被node封装在一份方法中运行。__dirname是node调用方法时传递进来的,表示当前目录。module.exports = { ?entry: ‘./src/index.js‘, //entry 配置当前项目的入口文件 ?output: { ???//output 配置输出 ???path: path.resolve(__dirname, ‘dist‘), //输出的文件名 ???filename: ‘bundle.js‘ ?//输出的路径 resolve拼接一个目录 ?}};
第二步:初始化webpack项目
进入项目根目录,执行命令:
npm init
执行此命令,生成package.json文件,此时的目录结构如下:
.+-- src| ??+-- bar.js| ??+-- index.js+-- index.html+-- webpack.config.js+-- package.json
安装 webpack 依赖
npm install webpack webpack-cli --save-dev
缩写形式安装 webpack
npm i webpack webpack-cli -D# –save:模块名将被添加到dependencies,可以简化为参数-S。# –save-dev: 模块名将被添加到devDependencies,可以简化为参数-D。
第三步:编辑package.json
{ ?"name": "webpacklearning", ?"version": "1.0.0", ?"description": "", ?"main": "webpack.config.js", ?"scripts": { ???"start": "webpack", ???"test": "echo \"Error: no test specified\" && exit 1" ?}, ?"author": "", ?"license": "ISC", ?"devDependencies": { ???"webpack": "^4.26.1", ???"webpack-cli": "^3.1.2" ?}}
第四步:运行webpack
npm start
生成dist文件夹及bundle.js,如下:
.+-- dist| ??+-- bundle.js+-- src| ??+-- bar.js| ??+-- index.js+-- index.html+-- webpack.config.js+-- package.json
webpack入门
原文地址:https://www.cnblogs.com/xmyun/p/10025896.html