玩码玩码

关注互联网
关注技术

Webpack入门

webpack.jpg

  醉心于Web技术,对于页面的交互异常的需要,近来前端技术很热门,发展的异常迅猛,三大框架Angular,react,vue变得炙手可热,但是要想用这些东西,需要一些依赖包的搭配,打包工具应运而生,从grunt到gulp再到webpack,越来越人性化,简单易用,那我就用几篇文章,将我研究的webpack的东西分享出来,让大家从入门到尽快上手。

  webpack说白了就是一个打包工具,将js的很多模块打包成很小的静态文件,然后webpack有一个特性,就是代码分割,意思就是说在项目中只加载当时所需要的那部分文件,整个工具中的最大亮点,莫过于loader,模块就是通过loader处理各种各样的文件,无论是CommonJs写的还是AMD模式或者是ES6的模式,乃至css,less,sass等等都能处理。

开始使用Webpack

安装

  webpack需要用npm安装,但是npm的镜像在国外,有可能会被墙掉,推荐安装cnpm,新建一个目录WebpackDemo,在命令行界面进入到此目录,执行如下如下命令便可以完成安装

//全局安装
cnpm install -g webpack

npm需要有个package.json的文件作为引导,里面包括当前项目的依赖模块,自定义的脚本任务等等。在终端中使用npm init命令可以自动创建这个package.json文件,输入

npm init  //输入这个命令一路回车即可,就会生成默认的信息

1.package.json文件已经就绪,下面我们就需要在本地项目文件中安装webpack依赖包

// 安装Webpack
cnpm install --save-dev webpack

2.在项目目录下新建一个src的目录,里面存放的是我们编写的js的原始代码,然后新建一个html的文件,里面放入基本的html代码

<!DOCTYPE html>
<head>
    <meta charset="utf-8">
    <title>webpack</title>
</head>
  <body>
    <div id='root'>
    </div>
  </body>
   <script type="text/javascript" src="./js/bundle.js"></script>
</html>

3.然后在根目录下建立名为webpack.config.js的文件,这是webpack默认的配置文件,内容如下,

var webpack = require('webpack');
var path = require('path');
var fs = require('fs');

module.exports = {
    entry: {
          bundle: './src/js/main.js' 
      },
    output: {
        path: path.resolve(__dirname, 'dist'), //文件输出目录
        filename: "js/[name].js", //文件名输出
    }
};

  下面来稍微解释一些这些代码的意思module.exports想必不需要太多解释,简单点说就是模块输出,然后在这个对象里面定义entry对象,这个参数的意思是指我们打包的文件入口是从哪里开始,也就是我们编写的js的原始文件,output顾名思义就是打包好文件输出目录,这里启用了node的path模块,指定当前目录下的dist目录,filename便是指输出的文件名,如果启用[name]的写法,那么输出的文件名就是entry中定义的键名bundle一致,如果不需要,可以用固定的文件名.

4.现在我们需要正式启用webpack,首先,我们要写一个js的demo,在src下的js目录下建立Modular.js文件,里面代码如下

module.exports = function() {
  var modules = document.createElement('div');
  modules.textContent = "这是一个引入的模块文件";
  return modules;
};

建立manin.js,内容如下

var greeter = require('./Modular.js');
document.getElementById('root').appendChild(greeter());

ok,一切准备就绪,然后在命令行中输入webpack,就可以执行了了,执行结果如下
webpack

这说明编译成功,就能看到dist的js目录下有bundle.js,在浏览器打开index.html,如果能看到下面的效果,
webpack

那便是运行成功,初步完成了webpack的基础应用。

启用loader

  现在我们来看一下webpack出色loader,我们需要用到babel,Babel其实是一个编译JavaScript的平台,JavaScript标准(ES6,ES7)还没有被大部分浏览器支持,它Babel的强大之处表现在可以通过编译让你的代码被浏览器完全支持,我们先来一次性安装这些依赖包

// npm一次性安装多个依赖模块,模块之间用空格隔开
npm install --save-dev babel-core babel-loader babel-preset-es2015

在webpack中配置Babel的方法如下

var webpack = require('webpack');
var path = require('path');
var fs = require('fs');

module.exports = {
    entry:  {
          bundle: './src/main.js' 
      },
    output: {
        path: path.resolve(__dirname, 'dist'), //文件输出目录
        filename: "js/[name].js", //文件名输出
    },
    module: {
        loaders: [{
            test: /\.js$/,
            loader: 'babel-loader',
            exclude:'/node_modules/',//排除不用loader的文件
        }]
    },
};

简单说明一下loaders的配置项语法,
test:一个匹配loaders所处理的文件的拓展名的正则表达式
loader:loader的名称
include/exclude:手动添加必须处理的文件(文件夹)或屏蔽不需要处理的文件(文件夹),这个不是必须的,屏蔽掉node_modules文件,可以加速编译
然后我们简单的用ES6的语法,写个简单的demo,src下新建person.js文件,代码如下

class Person{
  constructor(name, sex){
    this.name = name;
    this.sex = sex;
  }

  say(){
    return `我是${this.name},我的性别是:${this.sex}。`;
  }
}

export default Person;

main.js

import Person from './Person.js';

let man = new Person('老张', '男');
document.write(man.say());

然后再次执行webpack,执行编译,编译完成后,我们打开index.html就能看到如下效果
webpack,loader

这边是webpack处理模块,针对不同的模块,有不同的loader,详情可点击链接查看webpack-loaders

作为入门,先简单介绍这些,如有问题或者错误,可评论指出,我之后会分享一些热加载,插件等相关的内容,敬请期待……

未经允许不得转载:玩码 » Webpack入门

评论 2

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
  1. Writing a medical thesis or dissertation is a task done by almost all postgraduate and master's medical students. Dissertation is derived from the Latin word disserto which means discuss. It is essential to write successful medical papers such as medicine essays and medical thesis papers. There are several reasons as to why students write medicine essays. One of the reasons is to promote enhancement of critical judgment, research skills as well as analytical skills. Moreover, medicine essay writing produce students with the ability to 4evaluate and analyze data critically.

    The initial step for writing medicine essays is to choose a topic. A writer should have at least three topics to choose from. The topic has to be interesting, feasible and relevant. It is essential to write quality medicine essay. Hence, students need to have analytical skills and perfect writing skills. The writing skills will enable them write outstanding essay papers that can be highly regarded by instructors and professors. Teachers often require a lot and expect a lot from their students in terms of medicine essay writing. for this reason, students find essay writing to be an extremely difficult task and hence resort to buying custom medicine essays.

    A custom medicine essay has to be written by professional writers who are qualified in the field of nursing. Moreover, the custom medicine essay has to be original and plagiarism free. This means that it has to be written from scratch by experts with many years experience. The many years experience should enable a writer to write any form of medical paper including medical thesis, medicine essay and even medicine research paper. Moreover, experience will enable a writer to write a medicine essay that can guarantee academic success.

    Students get custom medicine essays from custom writing company. It is essential to choose the best company so that one can get the best custom medicine essay. The best and the most reliable medicine essay writing company should have some unique characteristics such as affordability and the ability to provide original and superior quality medicine essays. The other quality is that the company has to hire expert writers who can write quality medicine essays and other types of medical papers. The essays should not only be quality but also plagiarism free and free of grammatical and spelling mistakes.

    A custom medicine essay has a similar structure to any other academic essay assignment. It has an introduction that introduces the topic and tells the reader what the essay is all about. The second section is the body that has many paragraphs supporting the main topic. Finally there is the conclusion that briefly summarizes what has been discussed in the body section of the essay. Students should choose reliable writing companies so that they can get quality custom papers on several fields such as technology, sociology and law in addition to medicine field.

    Our custom writing company is the best company that all clients should rely on when in need of any given type of medicine paper. We provide quality papers that not only plagiarism free but also original. Moreover, our custom papers are affordable and able to guarantee academic excellence at all times. All our medical papers are reliable and sure of satisfying clients at all times.

     

    JoshuaIdego (2017-11-13) 回复
  2. A Biological Masterpiece, But Subject to Many Ills
    The human foot is a biological masterpiece. Its strong, flexible, and functional design enables it to do its job well and without complaint—if you take care of it and don't take it for granted.
    healthThe foot can be compared to a finely tuned race car, or a space shuttle, vehicles whose function dictates their design and structure. And like them, the human foot is complex, containing within its relatively small size 26 bones (the two feet contain a quarter of all the bones in the body), 33 joints, and a network of more than 100 tendons, muscles, and ligaments, to say nothing of blood vessels and nerves.
    https://www.cialissansordonnancefr24.com/achat-cialis-securise/

    JessieMab (2017-12-09) 回复