一、建立简单的项目目录

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?hash
cache: 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?hash
cache: 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.js

var 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 = {}; // 存储 all jsSource.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;
}

ps:转载请注明出处:杨君华

webpack 前端构建的更多相关文章

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

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

  2. webpack前端构建工具学习总结(二)之loader的使用

    Webpack 本身只能处理 JavaScript 模块,如果要处理其他类型的文件,就需要使用 loader 进行转换. Loader 可以理解为是模块和资源的转换器,它本身是一个函数,接受源文件作为 ...

  3. webpack前端构建工具学习总结(四)之自动化生成项目中的html页面

    接续上文:webpack前端构建工具学习总结(三)之webpack.config.js配置文件 插件的介绍文档:https://www.npmjs.com/package/html-webpack-p ...

  4. webpack前端构建angular1.0!!!

    webpack前端构建angular1.0 Webpack最近很热,用webapcak构建react,vue,angular2.0的文章很多,但是webpack构建angualr1.0的文章找来找去也 ...

  5. webpack前端构建工具学习总结(三)之webpack.config.js配置文件

    Webpack 在执行的时候,除了在命令行传入参数,还可以通过指定的配置文件来执行.默认情况下,会搜索当前目录的 webpack.config.js 文件,这个文件是一个 node.js 模块,返回一 ...

  6. 如何用webpack实现自动化的前端构建工作流

    什么是自动化的前端构建流? 1. 自动补全css私有前缀,自动转化less\sass为css,自动转化es6\vue\jsx语法为js,自动打包小图片为base64以减少http请求,自动给js,cs ...

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

    .table tr>td:nth-child(1){width: 2em !important;padding-left: .6rem !important;padding-right: .6r ...

  8. webpack前端自动化构建工具

    博主不易,不求赞赏,希望把自己遇到的难点写出来,以及希望自己能有能力写出一篇不错的博文. 前端构建工具本人 bootstrap+jquery用gulp vue+element 用webpack 本人最 ...

  9. webpack进阶构建项目(一)

    webpack进阶构建项目(一) 阅读目录 1.理解webpack加载器 2.html-webpack-plugin学习 3.压缩js与css 4.理解less-loader加载器的使用 5.理解ba ...

随机推荐

  1. 【poj3264】 Balanced Lineup

    http://poj.org/problem?id=3264 (题目链接) 题意 给出序列,求区间最大值-最小值 Solution 无修改,询问较多,ST表水一发. ST算法(Sparse Table ...

  2. pyenv的使用

    开始想使用virtual实现不同的版本的py隔离,然后发现不太方便,然后发现了这货. pyenv安装(ubuntu环境 ➜ ~ git clone git://github.com/yyuu/pyen ...

  3. 关于The serializable class XXX does not declare a static final serialVersionUID field of type long的警告

    编写实体类并且继承序列化接口时候,实体类会有警告,要生成一个静态的serialVersionUID. 上网搜了一下资料,现通俗解释一下: 点击前2个选项,会生成: private static fin ...

  4. Win10 Theano Install Guide

    basic install guide 1. download miniconda 2. conda install libpython mingw 3. conda install theano n ...

  5. STM8L --- External interrupt

    note 1:  Several interrupts can be pending at the same time. When an interrupt request is not servic ...

  6. 修改MySQL的默认数据存储引擎

    因为MySQL默认的是MyISAM数据引擎,不支持事务也不支持外键,所以需要用到Innodb引擎,于是决定将mysql的默认引擎设置为innodb.1 . 查看MySQL存储引擎是用的哪个?登录MyS ...

  7. ios动态添加属性的几种方法

    http://blog.csdn.net/shengyumojian/article/details/44919695 在ios运行过程中,有几种方式能够动态的添加属性. 1-通过runtime动态关 ...

  8. ASP------如何使界面布局具有一致外观

    使用布局页或布局块的方法 转载: http://www.runoob.com/aspnet/webpages-layout.html

  9. Linq------各种查询语句大全

    查询Title列的第一个值 string str = db.Webs.Select(p => p.Title).FirstOrDefault(); 根据ID,查询Title列的第一个值 b.We ...

  10. Eclipse 安装svn插件及使用

    1 安装 参考:http://welcome66.iteye.com/blog/1845176 通过svn插件安装,地址: Links for 1.8.x Release: Eclipse updat ...