webpack入门笔记

创建一个webpack项目 可配置 入门学习

webpack是一个静态模块打包器

npm init - y //创建一个package.json

安装需要的包

cnpm i webpack webpack-cli style-loader css-loader file-loader url-loader webpack-dev-server path html-webpack-plugin -D

创建一个index.html,webpack.config.js

创建文件夹 src -> 添加index.js 、style.css gx.png

创建文件夹config -> 添加webpack.development.js 、webpack.production.js

在package.json中添加两个命令

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "webpack-dev-server --env.development --open",
    "build": "webpack --env.production "
},

配置webpack.config.js

const path = require('path');
module.exports = function(env,args){
    console.log(env); //当前环境
    env = env || {development: true};
    return {
        entry: './src/index.js',
        module: {
            rules: [
                {
                    test: /\.css$/,
                    use: ['style-loader','css-loader']
                },
                {
                    test: /\.(png|jpg|gif)$/,
                    use: [
                        {
                            loader: 'url-loader',
                            options: {
                                outputPath: 'img/',
                                limit: 1 * 1024,//url-loader配合file-loader  当大于limit 时使用file-loader编译成图片,当小于则是base64放在样式中
                            }
                        }
                    ]
                }
            ]
        },

        // 动态配置其他配置
        ...env.production ? require('./config/webpack.production') : require('./config/webpack.development'),
    }
}

配置webpack.production.js

const path  = require('path');
const htmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
    mode: 'production',
    output: {
        path: path.resolve(__dirname,'../build'), //此段省略 默认输出到dist文件夹
        filename: '[name].min.js'
    },
    plugins: [
        new htmlWebpackPlugin({
            template: path.resolve(__dirname,'../index.html')
        })
    ]
}

配置webpack.development.js

const path = require('path');
const htmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
    output: {
        filename: '[name].js'
    },
    plugins: [
        new htmlWebpackPlugin({
            template: path.resolve(__dirname,'../index.html')
        })
    ]
}

普通index.html文件




    
    
    
    搭建webpack项目


    

style.css

.box {
    width: 100px;
    height: 100px;
    border: 1px solid #f00;
    background: url(./gx.png) no-repeat;
}

index.js

import './style.css'

console.log('测试项目');

跑项目

//生产 
npm run build


//开发 
npm run dev

效果图


webpack入门笔记_第1张图片
QQ图片20190227105010.png

如果是build 则会有一个build文件夹生成 ,直接将index.html丢在谷歌浏览器中就可以看效果了

你可能感兴趣的:(webpack入门笔记)