如何使用webpack来打包ES6的代码(一)

接着上一篇,使用babel打包时对单个文件打包的问题,可能有其他解决方案,此处就不研究了,想使用webpack来解决的,请看此篇

1.文件构成

Paste_Image.png

demo.js ,可以看到,使用ES6的语法应用了helloWorld,并执行了方法

import helloWorld from './helloWorld.js'
helloWorld()

helloWorld.js,导出一个Test方法,在上一句中被重命名了

export default function Test(){
    console.log(123)
}

index.html,引用生成后的js

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <title>Document</title>
</head>
<body>
    <script type="text/javascript" src='./dist/index.js'></script>
</body>
</html>

package.json,定义了依赖的包,只有babel-loader,webpack

{
  "name": "webpack",
  "version": "1.0.0",
  "description": "This is a webpack demo",
  "main": "demo.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "webpack"
  ],
  "author": "chenbin",
  "license": "MIT",
  "dependencies": {
    "babel-loader": "^6.4.0",
    "webpack": "^2.2.1"
  }
}

webpack.config.js,定义入口,出口,loader

module.exports={
    entry:'./demo.js',
    output:{
        filename:'index.js',
        path:'./dist'
    },
  module: {
     loaders: [
        {
          test: /\.js$/,
          exclude: /(node_modules|bower_components)/,
          loader: 'babel-loader'
        }
      ]
  }
}

重点看package.json和webpack.config.js,可以看见只引用了两个依赖,并且只使用了一个loader即可完成

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 无意中看到zhangwnag大佬分享的webpack教程感觉受益匪浅,特此分享以备自己日后查看,也希望更多的人看到...
    小小字符阅读 8,227评论 7 35
  • 写在开头 先说说为什么要写这篇文章, 最初的原因是组里的小朋友们看了webpack文档后, 表情都是这样的: (摘...
    Lefter阅读 5,322评论 4 31
  • 最近在学习 Webpack,网上大多数入门教程都是基于 Webpack 1.x 版本的,我学习 Webpack 的...
    My_Oh_My阅读 8,204评论 40 247
  • GitChat技术杂谈 前言 本文较长,为了节省你的阅读时间,在文前列写作思路如下: 什么是 webpack,它要...
    萧玄辞阅读 12,710评论 7 110
  • 人生面临三个重要的关系,分别是与子女、与父母、与配偶,这三个关系很难逃脱,无法更换或者更换的成本很高。在这三个重要...
    石泉BABU阅读 124评论 0 2