webpack小白入门之基础概念【1-1】

环境搭建:安装Node.js 和 NPM

安装nvm github.com/nvm-sh/nvmjavascript

ps: nvm(Node.js Version Manager)也就是 Node.js 的包管理器,能够经过它方便安装和切换不一样的Node.js版本。
复制代码
  • Mac经过 curl 安装:curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bashhtml

  • Windows的安装方法 参考这里java

检查node和NPM版本安装成功以下:node

环境搭建:安装webpack和webpack-cli

建立空目录和package.json

  • mkdir webpack.1-1
  • cd webpack.1-1
  • npm init -y

安装 webpack 和 webpack-cli

  • npm install webpack webpack-cli --save-devwebpack

  • 检查是否安装成功 cd node_modules.bin> webpack -vgit

在项目根目录下建立一个webpack.config.js 文件github

'use strict';

const path = require('path');

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.join(__dirname, 'dist'),// 打包的文件夹名
    filename: 'bundle.js'    // 打包的文件名
  },
  mode: 'production'

}
复制代码

同时,在项目根目录下,建立src文件夹及其子文件helloworld.jsindex.jsweb

helloworld.jsnpm

export function helloworld() {
  return 'hello webpack';
}
复制代码

index.jsjson

import { helloworld } from './helloworld';

document.write(helloworld());
复制代码

这样一个简单的demo就完成了,在工程命令行中执行命令 webpack开始打包工程。

打包好的结果是这样的:

因为咱们打包出来的dist文件夹下面是没有html文件的,因此咱们在dist文件夹下新建一个index.html文件,而后将bundle.js引进来。而后在浏览器中打开,一个简单的demo效果就出来了。

总结一下:

'use strict';                                      

const path = require('path');                    
                                                   
module.exports = {                                     
  entry: './src/index.js', // 用来指定webpack的打包入口  // 若是是Windows电脑应该这样配置 entry: '../../src/index.js',                 
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js'    // 打包的文件名
  },
  mode: 'production'

}
复制代码

index.html

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Hello Webpack</title>
</head>

<body>
  <script src="./bundle.js" type="text/javascript"></script>
</body>

</html>
复制代码

下一篇 webpack小白入门【1-2】webpack的基本用法之相关核心概念

相关文章
相关标签/搜索