zoukankan      html  css  js  c++  java
  • Webpack 从0开始

    Webpack

    Demos
    https://github.com/ruanyf/webpack-demos

    Docs
    https://webpack.github.io/docs/?utm_source=github&utm_medium=readme&utm_campaign=trdr

    Webpack可以做什么

    • 支持CMD AMD (Gulp还需要browserify才能CMD)
    • 模块加载器 插件机制 (典型的模块加载器babel-loader)
    • 可以通过配置打包成多个文件 (充分利用浏览器缓存功能)
    • 样式 图片等静态资源都可以视作模块 (任何的文件都能被 require)
    • 内置source-map

    第一个例子

    首先npm install -g webpack
    和Gulp一样 有一个入口执行文件 webpack.config.js

    module.exports = {
      entry: './main.js',
      output: {
        filename: 'bundle.js'
      }
    };
    

    如何运行它

    $ webpack // 最基本的启动webpack方法
    $ webpack -w // 提供watch方法,实时进行打包更新(包括被依赖的文件的改动)
    $ webpack -p // 对打包后的文件进行压缩,提供production
    $ webpack -d // 提供source map,方便调试
    

    sourcemap对应的文件将会在 webpack:// 下面的一个 . 目录中

    ES6

    想要把ES6转为ES5 需要babel
    当然Gulp也有babel 为什么网上都是webpack呢
    对于import export这种 babel后会是 require(...)
    浏览器是不认识require的 若用gulp还要再用browserify
    但是wepack可以直接把require编译为浏览器可执行的语句

    webpack.config.js

    module.exports = {
      // entry: './main.jsx',  //不能直接写main.jsx  //当前目录下必须加上 ./  //否则提示找不到文件
      entry: './f2.js',
      output: {
        filename: 'bundle.js'
      },
      module: {
        loaders:[
          { test: /.js[x]?$/, exclude: /node_modules/, loader: 'babel-loader' },
        ]
      }
    };
    

    f2.js

    import f1 from './f1.js';
    console.log(f1.generateRandom());
    

    f1.js

    function generateRandom() {
        return Math.random();
    }
    
    function sum(a, b) {
        return a + b;
    }
    
    export default {
        generateRandom:generateRandom,
        sum:sum
    }
    

    什么是Loader

    Loader就是一个使你的资源经过一定transform变成新资源的东东(好吧 这个翻译很糟糕)
    Loaders are transformations that are applied on a resource file of your app. They are functions (running in node.js) that take the source of a resource file as the parameter and return the new source.

    url-loader

    和file-loader类似 能够返回一个文件的路径
    文件size 小于limit的 将返回文件的data-url

    css-loader style-loader

    style-loader是用于加载css文件的
    css-loader是将css中的 import url 之类翻译为成require

    http://stackoverflow.com/questions/25472908/is-the-webpack-style-loader-meant-to-load-all-css-or-just-application-specific
    css还是建议使用html引入的方式
    现代浏览器会先加载css并解析, 用html来引入css而不是bundle.js引入 页面加载更快
    且对于base.css 浏览器可以缓存

    html-loader

    用于load模板html文件
    比如var domTmp = require('./dom.tpl.html');

  • 相关阅读:
    Tomcat 7 的七大新特性 悟寰轩
    MapReduce提交作业常见问题 悟寰轩
    [MQ]关于ActiveMQ的配置 悟寰轩
    LinkedBlockingQueue应用实例 悟寰轩
    什么是java序列化,如何实现java序列化? 悟寰轩
    远程注入DLL的例子
    回调函数实例
    将网页保存为Stream
    删除文件或文件夹
    选择目录
  • 原文地址:https://www.cnblogs.com/cart55free99/p/4937918.html
Copyright © 2011-2022 走看看