乐趣区

webpack4详细教程从无到有搭建react脚手架三

Css

安装 loader

yarn add style-loader css-loader -D

配置

config/webpack.common.js

        ...
        function webpackCommonConfigCreator(options){
            ...
            return {
                ...
                module: {
                    rules: [
                        ...
                        + {
                        +     test: /\.css$/,
                        +     include: path.resolve(__dirname, '../src'),
                        +     use: ["style-loader", "css-loader"]
                        + }
                    ]
                },
                ...
            }
        }

创建 src/app.css

src/app.css

        .text{
            font-size: 20px;
            color: brown;
        }

src/App.js

        + import './app.css';

        function App(){
            return (
                - <div>
                + <div className="text">
                    hello react
                </div>
            )
        }
        ...

yarn start,效果:

Scss

安装 loader

    yarn add sass-loader node-sass -D

配置 loader

config/webpack.common.js

        ...
        function webpackCommonConfigCreator(options){
            ...
            return {
                ...
                module: {
                    rules: [
                        ...
                        {
                        -    test: /\.css/,
                        +    test: /\.(css|scss)$/,
                            include: path.resolve(__dirname, '../src'),
                        -    use: ["style-loader", "css-loader"]
                        +    use: ["style-loader", "css-loader", "sass-loader"]
                        }
                    ]
                },
                ...
            }
        }

创建 src/app.scss

src/app.scss

        .title{
            font-size: 18px;
            font-weight: 800;
            color: #333;
            text-decoration: underline;
        }

src/App.js

        - import './app.css';
        + import './app.scss';

        function App(){
            return (
                - <div className="text">
                + <div className="title">
                    hello react
                </div>
            )
        }
        ...

yarn start, 效果:

配置 css-module 模式

修改配置

config/webpack.common.js

        ...
        function webpackCommonConfigCreator(options){
            ...
            return {
                ...
                module: {
                    rules: [
                        ...
                        {
                            ...
                            - use: ["style-loader", "css-loader", "sass-loader"]
                            + use: [
                            +         "style-loader", 
                            +         {
                            +             loader: "css-loader",
                            +             options: {
                            +                 modules: {
                            +                     mode: "local",
                            +                     localIdentName: '[path][name]_[local]--[hash:base64:5]'
                            +                 },
                            +                 localsConvention: 'camelCase'
                            +             }
                            +         }, 
                            +         "sass-loader"
                            + ]
                        }
                    ]
                },
                ...
            }
        }

src/App.js

        - import './app.scss';
        + import styles from './app.scss';

        function App(){
            return (
                - <div className="title">
                + <div className={styles.title}>
                    hello react
                </div>
            )
        }

        export default hot(App);

yarn start

现在编译后的 css 由 js 动态内联在 html 中,需要分离到单独的文件

安装插件 extract-text-webpack-plugin,注意最新版才支持 webpack4

yarn add extract-text-webpack-plugin@next -D

配置

config/webpack.common.js

        ...
        + const ExtractTextPlugin = require('extract-text-webpack-plugin');

        ...
        module: {
            rules: [
                ...
                {test: /\.(css|scss)$/,
                    include: path.resolve(__dirname, '../src'),
                    - use: [
                    -     "style-loader", 
                    -     {
                    -         loader: "css-loader",
                    -         options: {
                    -             modules: {
                    -                 mode: "local",
                    -                 localIdentName: '[path][name]_[local]--[hash:base64:5]'
                    -             },
                    -             localsConvention: 'camelCase'
                    -         }
                    -     }, 
                    -     "sass-loader"
                    - ]
                    + use: ExtractTextPlugin.extract({
                    +     fallback: "style-loader",
                    +     use: [
                    +         {
                    +             loader: "css-loader",
                    +             options: {
                    +                 modules: {
                    +                     mode: "local",
                    +                     localIdentName: '[path][name]_[local]--[hash:base64:5]'
                    +                 },
                    +                 localsConvention: 'camelCase'
                    +             }
                    +         }, 
                    +         "sass-loader"
                    +     ]
                    + })
                },
                ...
            ]
        },
        plugins: [
            ...
            new ExtractTextPlugin({filename: "[name][hash].css"
            }),
        ]

yarn build, 效果:

使用 postcss 对 css3 属性添加前缀

安装

yarn add postcss-loader postcss-import autoprefixer -D

配置

config/webpack.common.js

        module: {
            rules: [
                ...
                {test: /\.(css|scss)/,
                    use: ExtractTextPlugin.extract({
                        fallback: "style-loader",
                        use: [
                            ...
                            + {
                            +     loader: "postcss-loader",
                            +     options: {
                            +         ident: 'postcss',
                            +         plugins: loader => [+             require('postcss-import')({root: loader.resourcePath}),
                            +             require('autoprefixer')()
                            +         ]
                            +     }
                            + }
                        ]
                    })
                },
                ...
            ]
        }

对生产模式下的 css 进行压缩

安装

yarn add optimize-css-assets-webpack-plugin -D

配置

config/webpack.prod.js

        + const optimizeCss = require('optimize-css-assets-webpack-plugin');

        const config = {
            + plugins: [
            +     new optimizeCss({+         cssProcessor: require('cssnano'),
            +         cssProcessorOptions: {discardComments: { removeAll: true} },
            +         canPrint: true
            +     }),
            + ],
        }
        ...

yarn build,效果:

css 相关配置完了,当然还有一些静态资源的配置

字体

安装 loader

yarn add file-loader -D

配置

config/webpack.common.js

        module: {
            rules: [
                ...
                + {+     test: /\.(woff|woff2|eot|ttf|otf)$/,
                +     use: ['file-loader']
                + },
            ]
        },

图片

安装 loader

yarn add url-loader -D

配置

config/webpack.common.js

        module: {
            rules: [
                ...
                + {+     test: /\.(jpg|png|svg|gif)$/,
                +     use: [
                +         {
                +             loader: 'url-loader',
                +             options: {
                +                 limit: 10240,
                +                 name: '[hash].[ext]',
                +             }
                +         },
                +     ]
                + },
            ]
        }

添加两张图片

  • src/assets/small.jpg — 6kb
  • src/assets/bigger.jpg — 20kb

引入图片

src/App.js

        + import small_pic from './assets/small.jpg';
        + import bigger_pic from './assets/bigger.jpg';

        function App(){
            return (<div className={styles.title}>
                    hello react

                    + <img src={small_pic} alt="" />
                    + <img src={bigger_pic} alt="" />
                </div>
            )
        }

        export default hot(App);

效果

可以看到,小于 10k 的图片编译成了 base64 格式,而大于 10k 的图片以链接形式赋值给 src,由 url-loader 的 limit 选项决定界限


未完待续!

退出移动版