webpack打包非js,json的资源

1.创建webpack.config.js配置文件

image

webpack.config.js配置文件的作用:

当运行webpack指令时,会加载其中的配置

所有的构建工具都是基于Nodejs,模块化默认使用commonjs

2.配置架构

image

const {resolve} = require('path')
//resolve用来拼接路径的方法

module.exports={
    //input
    entry:'./src/index.js',
    //output
    output:{
        //输出文件名
        filename:'built.js',
        //输出路径(需引入Node.js模块)
        //__dirname nodejs的变量,代表当前文件的目录绝对路径
        path:resolve(__dirname,'build')
    },

    //loader的配置
    module:{
        rules:[
            //详细的配置
        ]
    },
    plugins:[
        //详细plugins的配置
    ],
    //模式:development和production
    mode:'development'  //开发模式
}

3.配置loader的rules

以css为例,rules中的具体配置:

	{
                //匹配哪些文件,此处是.css
                test:/\.css$/,
                //使用哪些loader进行处理
                use:[
                    //use数组中的执行顺序是自下到上(自右至左) 依次执行

                    //创建<style>标签,将js中的样式资源插入进行,添加到head中生效
                    'style-loader',
                    // css-loader将css文件变成commonjs模块加载js中,内容是样式的字符串
                    'css-loader'
                ]
            }

webpack 打包成功后

image
引入打包后的js文件
image

F12可见head中多出了一个style标签,其中就是index.css的样式
image

posted @ 2021-10-28 20:11  Wenfancy  阅读(52)  评论(0编辑  收藏  举报