一、建立简单的项目目录

1、创建 manager 根目录(作为项目根目录)
2、执行 npm init,在根目录manager下自动生成 package.json文件
3、npm install webpack --save-dev,在项目中安装 webpack npm包
4、在根目录下 创建 webpack.config.js,所有的配置代码都写在里面
5、在根目录创建 src 目录,包含 html目录 > index.html,css目录 > index.css,js目录 > index.js,images目录 > index...

如图:

二、配置webpack.config.js文件

1、简单配置及使用

module.exports = {entry: {        'js/index': './src/js/index.js'},output: {path: './build',filename: '[name].js'}
};

执行构建命令:./node_modules/webpack/bin/webpack.js

ok,生成下图的目录结构了

2、安装,使用html-webpack-plugin插件

上一步我们通过构建,在根目录下生成了 ./build/js/index.js 文件,我们希望 生成 ./build/html/index.html 文件
首先安装一下插件 npm install html-webpack-plugin --save-dev,再来看看我们的配置代码

var HtmlWebpackPlugin = require('html-webpack-plugin');var plugins = [];plugins.push(    new HtmlWebpackPlugin({template: './src/html/index.html',filename: 'html/index.html',inject: 'body',hash: true, // index.js?hashcache: true, // if true (default) try to emit the file only if it was changed.showErrors: true, // if true (default) errors details will be written into the html page.chunks: ['js/index'] // filter chunks    })
);module.exports = {entry: {        'js/index': './src/js/index.js'},output: {path: './build',filename: '[name].js'},plugins: plugins
};

执行构建命令:./node_modules/webpack/bin/webpack.js后

打开./build/html/index.html文件,发现html中自动加上了script标签,引用的js路径加上了hash值,是不是感觉很赞
<script type="text/javascript" src="../js/index.js?f5f204be195973d9d81c"></script>

构建后的项目目录如图:

3、配合babel编译器,让我们所写的js代码支持es6语法

babel官网地址:https://babeljs.io/

安装babel编译器 
npm install --save-dev babel-loader babel-core
npm install --save-dev babel-preset-es2015

在根目录下创建 .babelrc 配置文件

{  "presets": ["es2015"]
}

webpack.config.js配置如下:

var HtmlWebpackPlugin = require('html-webpack-plugin');var plugins = [];var loaders = [{ test: /\.js$/, exclude: /node_modules/, loader: "babel-loader" },{ test: /\.css$/, loader: "style-loader!css-loader" }
];plugins.push(    new HtmlWebpackPlugin({template: './src/html/index.html',filename: 'html/index.html',inject: 'body',hash: true, // index.js?hashcache: true, // if true (default) try to emit the file only if it was changed.showErrors: true, // if true (default) errors details will be written into the html page.chunks: ['js/index'] // filter chunks    })
);module.exports = {entry: {        'js/index': './src/js/index.js'},output: {path: './build',filename: '[name].js'},module: {loaders: loaders},plugins: plugins
};

准备好了,我们在 ./src/js/index.js文件中写入:

function testEs6(a, ...args) {console.log(args); // [2,3,4]}testEs6(1,2,3,4);console.log(Set);
console.log(Map);new Promise(function(resolve, reject) {});

执行构建命令:./node_modules/webpack/bin/webpack.js,OK,编译成功了,并没有报错,这意味着你可以在你的项目中使用es6了

4、css文件可以作为模块在js中被引入

npm install css-loader --save-dev
npm install style-loader --save-dev

在webpack.config.js文件中配置

var loaders = [{ test: /\.css$/, loader: "style-loader!css-loader" }
];

在./src/js/index.js中 引入css文件

require('../css/index.css');

执行构建命令:./node_modules/webpack/bin/webpack.js,可以看到 ./src/css/index.css中的css代码 放在了./build/html/index.html文件的style标签内

5、本地服务 webpack-dev-server

npm install --save-dev webpack-dev-server

执行服务启动命令:./node_modules/.bin/webpack-dev-server --progress --host 0.0.0.0 --port 8080 --colors --inline --hot --display-error-details --content-base src/

你可以通过浏览器输入下面地址来访问你的项目:
http://0.0.0.0:8080/html
localhost:8080/html
你的ip:8080/html

ok,也可以通过配置 webpack.config.js

var HtmlWebpackPlugin = require('html-webpack-plugin');var plugins = [];var loaders = [{ test: /\.js$/, exclude: /node_modules/, loader: "babel-loader" },{ test: /\.css$/, loader: "style-loader!css-loader" }
];plugins.push(    new HtmlWebpackPlugin({template: './src/html/index.html',filename: 'html/index.html',inject: 'body',hash: true,cache: true,showErrors: true,chunks: ['js/index']})
);module.exports = {entry: {        'js/index': './src/js/index.js'},output: {path: './build',filename: '[name].js'},devServer: {progress: true,host: '0.0.0.0',port: 8080,colors: true,inline: true,        // hot: true,contentBase: './src',displayErrorDetails: true},module: {loaders: loaders},plugins: plugins
};

配置完了后,我们 在执行命令 ./node_modules/.bin/webpack-dev-server,ok,成功了
我们随便修改一下 ./src/html/index.html代码(也可以修改css,js代码),浏览器页面将会自动刷新,实时预览,神奇吧....

6、多文件自动构建

// webpack.config.jsvar glob = require('glob');var path = require('path');var HtmlWebpackPlugin = require('html-webpack-plugin');var source = getSource();var loaders = [{ test: /\.js$/, exclude: /node_modules/, loader: "babel-loader" },{ test: /\.css$/, loader: "style-loader!css-loader" }
];var plugins = (function() {    var arr = [];source.htmlFiles.forEach(function(htmlFile) {arr.push(            new HtmlWebpackPlugin({template: htmlFile.pageSource,filename: htmlFile.filename,inject: 'body',hash: true,cache: true,showErrors: true,chunks: [htmlFile.jsChunkName]}));});    return arr;
}());module.exports = {entry: source.entry,output: {path: './build',filename: '[name].js'},devServer: {progress: true,host: '0.0.0.0',port: 8080,colors: true,inline: true,hot: true,contentBase: './src',displayErrorDetails: true},module: {loaders: loaders},plugins: plugins
};function getSource() {    var source = {htmlFiles: [],entry: {}};    var pageSource = glob.sync('./src/html/*.html');    var jsSource = glob.sync('./src/js/**/*.js');    var entry = {}; // 存储 alljsSource.forEach(function(item) {entry['js/' + path.basename(item, '.js')] = item;});pageSource.forEach(function(page) {        var jsChunkName = 'js/' + path.basename(page, '.html');source.htmlFiles.push({filename: 'html/' + path.basename(page),pageSource: page,jsChunkName: jsChunkName});source.entry[jsChunkName] = entry[jsChunkName];});    return source;
}

原文地址:http://www.cnblogs.com/yangjunhua/p/5615118.html


.NET社区新闻,深度好文,微信中搜索dotNET跨平台或扫描二维码关注

webpack 前端构建相关推荐

  1. webpack前端构建工具学习总结(一)之webpack安装、创建项目

    npm是随nodeJs安装包一起安装的包管理工具,能解决NodeJS代码部署上的很多问题: 常见的使用场景有以下几种: 允许用户从NPM服务器下载别人编写的第三方包到本地使用. 允许用户从NPM服务器 ...

  2. npm run buil构建后页面白屏_从Npm Script到Webpack,6种常见的前端构建工具对比

    从Npm Script到Webpack,6种常见的前端构建工具对比 小编说:历史上先后出现了一系列构建工具,它们各有优缺点.由于前端工程师很熟悉JavaScript,Node.js又可以胜任所有构建需 ...

  3. 前端构建工具之争——Webpack vs Gulp 谁会被拍死在沙滩上

    阅读目录 理想的前端开发流程 Gulp 为何物 webpack 又是从哪冒出来的 结论 文章有点长,总共 1800 字,阅读需要 18 分钟.哈哈,没耐心的直接戳我到高潮部分. 理想的前端开发流程 在 ...

  4. 时下最流行前端构建工具Webpack 入门总结

    作者:wenjuanrao,腾讯 PCG 前端开发工程师 最近梳理了下以前 webpack 的相关开发经验,整理和总结了一份入门笔记,欢迎大家围观和批评指正. 随着 web 应用越来越复杂和庞大,前端 ...

  5. 从Npm Script到Webpack,6种常见的前端构建工具对比

    从Npm Script到Webpack,6种常见的前端构建工具对比 小编说:历史上先后出现了一系列构建工具,它们各有优缺点.由于前端工程师很熟悉JavaScript,Node.js又可以胜任所有构建需 ...

  6. Vue 2 中,使用Vite作为前端构建开发工具,替代webpack(一)——vite.config.js配置文件

    Vue 2 中,使用Vite作为前端构建开发工具,替代webpack(一)--vite.config.js配置文件 当前版本 vite@2.3.7和vite@2.4.4 "vite" ...

  7. 关于Webpack前端工程化构建,你必须要掌握这些核心知识点

    引言 在很久之前,模块化管理还没有出现,如果我们开发一个页面想要引入一些依赖的话,最常见的做法就是将依赖文件引入到.html文件中.比如,我们要使用JS的一些依赖库,就要在.html文件中使用< ...

  8. webpack快速构建项目

    1.前(fei)言(hua) webpack是什么我在这里就不多说了,实在不知道的可以直接在去搜一下,都一大堆答案.关于用webpack怎么构建项目,方法也是多种多样,五花八门.今天,我就写下我平常构 ...

  9. 前端构建新世代,Esbuild 原来还能这么玩!

    大家好,我是若川.持续组织了5个月源码共读活动,感兴趣的可以点此加我微信 ruochuan12 参与,每周大家一起学习200行左右的源码,共同进步.同时极力推荐订阅我写的<学习源码整体架构系列& ...

最新文章

  1. Oracle 优化器_表连接
  2. numix Docky
  3. 小米 android 刷4.0,小米如何刷MIUI4.0系统教程
  4. 操作系统中的内存分配
  5. springboot2.5.5配置druid数据源1.2.8与jdbc
  6. oracle查询中over(partition by ...order by ...)用法
  7. 【目标检测】SPPNet算法详解
  8. 遥控器油门摇杆电位器封装尺寸图
  9. NANDFlash原理
  10. linux proftpd 用户,linux之proftpd搭建(随时盖楼)
  11. Linux磁盘空闲空间调度管理
  12. 正则表达式匹配行首和行尾
  13. 错误代码0x80004005解决方案
  14. 微型计算机的主要性能指标(),微型计算机的主要性能指标
  15. 【Python】利用百度地图API获取多方式行程时间
  16. FPGA verilog实现全减器
  17. 从抓包砍到接口测试,五分钟看完全过程解析,还说你不会测试?
  18. Lucene,Solr和Elasticsearch中的印度尼西亚语言
  19. ROC 曲线讲解 (Receiver Operarating Curve)
  20. simpy搭建轨道交通客流仿真模型

热门文章

  1. android进程间通信:使用AIDL
  2. 各自用一句话来概括MVC、MVP、MVVM的差异特点
  3. 使用ClickOnce部署VS2005中的WinForm应用程序.(ZT)
  4. Blazor University (9)组件 — 代码生成 HTML 属性
  5. OxyPlot 导出图片及 WPF 元素导出为图片的方法
  6. 如何修改 匿名类型 中的属性值 ?
  7. 让前端与后端异步起来
  8. Dapr + .NET 实战(四)发布和订阅
  9. C#怎么测试静态方法?我给出了2种方案
  10. 社区 正式发布了跨平台的 CoreWCF 0.1.0 GA