天天看点

Webpack 入门;构建项目,脚手架

1. 选择一个文件夹: D:/usr/webpack/demo01,并且在该目录下创建一个package.json 空白文件

demo
|- package.json
           

2. 打开vscode:

3. 进入终端执行: 

npm init
           

4. 在当前文件夹下创建文件目录:

demo
|- package.json
|- /dist
  |- index.html
|- /src
  |- index.js
           

5. 安装webpack

npm install webpack -g //如果已经全局安装过,忽略此条命令

npm install webpack --save-dev

npm install webpack-cli --save-dev
           

6. 创建一个webpack.config.json 文件

//提供目录
const path = require('path');

//
module.exports = {
    entry: './src/index.js',
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist')
    }
};
           

7. 配置 package.json 文件,设置webpack的npm 启动方式; 配置 :"build":"webpack"

{
  "name": "demo01",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack",
    
  },
  "author": "Jon",
  "license": "ISC",
  "devDependencies": {
    "lodash": "^4.17.11",
    "webpack": "^4.20.2",
    "webpack-cli": "^3.1.1"
  },
  
}
           

8. 配置服务启动方式: 

npm install --save-dev webpack-dev-server
           

9. 在 package.json中加入:

"start": "webpack-dev-server --open"
           

10. 在webpack.json中加入

//提供目录
const path = require('path');

//
module.exports = {
    entry: './src/index.js',
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist')
    },
    devServer: {
        contentBase: './dist'
    }
};
           

11. 打包运行

npm start //运行

npm run build //打包
           

12. 最终配置:

/* package.json */

{
  "name": "demo01",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack",
    "start": "webpack-dev-server --open"
    
  },
  "author": "Jon",
  "license": "ISC",
  "devDependencies": {
    "lodash": "^4.17.11",
    "webpack": "^4.20.2",
    "webpack-cli": "^3.1.1",
    "webpack-dev-server": "^3.1.9"
  },
  "dependencies": {
    "lodash": "^4.17.11"
  }
}

// webpack.config.json

const path = require('path');
module.exports = {
    entry: './src/index.js',
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist')
    },
    devServer: {
        contentBase: './dist'
    }
};