webpack安装与基本配置

来源:互联网 发布:0.32双丝并绕数据 编辑:程序博客网 时间:2024/06/06 03:13

安装

全局安装
npm install -g webpack
本地安装(安装到项目目录下)
npm install –save-dev webpack

创建package.json

终端中在项目目录下输入命令npm init 自动生成package.json文件,这是一个标准的npm说明文件,包括当前项目的依赖模块,自定义的脚本任务等等

{  "name": "new-project",  "version": "1.0.0",  "description": "",  "main": "index.js",  "scripts": {    "test": "echo \"Error: no test specified\" && exit 1"  },  "author": "",  "license": "ISC",  "devDependencies": {    "webpack": "^3.4.1",  }}

搭建项目结构
这里写图片描述

index.js

var sub = require('./sub');var app = document.createElement('div');app.innerHTML = '<h1>Hello 22222 World</h1>';app.appendChild(sub());document.body.appendChild(app);

sub.js

function generateText() {    var element = document.createElement('h2');    element.innerHTML = "hello h2 world";    return element;}module.exports = generateText;

webpack.config.js配置

var HtmlWebpackPlugin = require('html-webpack-plugin');var webpack = require('webpack'); module.exports = {    // 入口文件名称    entry: __dirname + "/app/index.js",    // 输出文件名称    output: {    //"__dirname" 是node.js中的一个全局变量,它指向当前执行脚本所在的目录        path: __dirname + '/build',//打包后文件的存放地方        filename: "bundle.js"//打包后输出文件的文件名    },    // 插件项    plugins: [        // 压缩生成的js代码,webpack中内置的plugin        new webpack.optimize.UglifyJsPlugin(),        new HtmlWebpackPlugin({            //生成的html文件的title,默认Webpack APP            title: "Test App"        })    ],    devServer: {        //本地服务器所加载的页面所在的目录        contentBase: __dirname + "/build",        historyApiFallback: true,//不跳转        inline: true,//当源文件改变时,自动刷新页面        port: 8080//端口    }}

其中插件项plugins,有webpack中内置的如UglifyJsPlugin,以及需要通过npm引入的第三方包如html-webpack-plugin,另外通过webpack构建本地服务器而来,以上命令如下:

npm install  html-webpack-plugin webpack-dev-server --save-dev

此时package.json配置如下:

{  "name": "new-project",  "version": "1.0.0",  "description": "",  "main": "index.js",  "scripts": {    "start": "webpack-dev-server --hot --inline",    "test": "echo \"Error: no test specified\" && exit 1"  },  "author": "",  "license": "ISC",  "devDependencies": {    "html-webpack-plugin": "^2.29.0",    "webpack": "^3.4.1",    "webpack-dev-server": "^2.6.1"  }}

scripts中start需手动添加,实时监听项目变化

文件打包

这里写图片描述

生成build文件夹,以及内部的bundle.js和index.html

这里写图片描述

项目打包

npm start

这里写图片描述

浏览器地址栏中输入localhost:8080,修改js文件、可获得实时更新

结尾

最基本的webpack安装与配置就暂时告一段落了,待续!

原创粉丝点击