webpack4学习笔记(三)

webpack打包资源文件

  1,打包css文件,先安装css-loader和style-loader

npm install --save-dev css-loader style-loader

webpack.config.js配置如下:

module: {
        rules: [
            ...
            {
                test: /\.css$/,
                use: [
                    'style-loader',
                    'css-loader'
                ]
            }
}

2,webpack打包sass文件,先安装node-sass,sass-loader(还需安装css所需的依赖)

npm install --save-dev sass-node sass-style
}

3,webpack打包less文件,先安装less,less-loader(还需安装css所需的依赖)

npm install --save-dev less less-style

 

...
{
    test: /\.scss$/,
    use:[ 'style-loader','css-loader','sass-loader'],
},
{
    test: /\.less$/,
    use:[ 'style-loader','css-loader','less-loader'],
}

4,提取css代码,需要一个插件:extract-text-webpack-plugin,首先安装此插件

npm install --save-dev extract-text-webpack-plugin

 

 

const path = require('path')
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
    entry: {
        main: path.resolve(__dirname, 'src/main.js'),       //入口
    },
    output: {
        filename: 'bundle.js',               //输出的文件名
        path: path.resolve(__dirname, 'build') //输出文件所在的目录
    },
    devServer: { // 检测代码变化并自动重新编译并自动刷新浏览器
        contentBase: path.resolve(__dirname, 'build') // 设置静态资源的根目录
    },
    module: { // 如何处理项目中不同类型的模块
        rules: [ // 用于规定在不同模块被创建时如何处理模块的规则数组
            {
                test: /(\.jsx|\.js)$/,
                use: {
                    loader: "babel-loader",
                    options: {
                        presets: [
                            "env", "react"
                        ]
                    }
                },
                exclude: path.resolve(__dirname, 'node_modules'),
                include: path.resolve(__dirname, 'src'),
            },
            {
                test: /\.css$/,
                use:ExtractTextPlugin.extract({
                    fallback:"style-loader",
                    use:"css-loader"
                })
            },
            {
                test: /\.scss$/,
                use:ExtractTextPlugin.extract({
                    fallback:"style-loader",
                    use:[{
                        loader:"css-loader"
                    },{
                        loader:"sass-loader"
                    }]
                })
            },
            {
                test: /\.less$/,
                use:ExtractTextPlugin.extract({
                    fallback:"style-loader",
                    use:[{
                        loader:"css-loader"
                    },{
                        loader:"less-loader"
                    }]
                })
            }
        ]
    },
    plugins: [
        new ExtractTextPlugin('css/index.css')
    ]
}

 

posted @ 2019-02-13 17:35  Mine&&Mine  阅读(338)  评论(0编辑  收藏  举报