[webpack] ch5. CSS Code Splitting 실습

CSS Code Splitting 실습

절차

  1. npm init -y로 pacakge.json 생성
  2. npm으로 loader & plugin 설치
    npm i css-loader style-loader --save-dev
    npm i extract-text-webpack-plugin --save-dev
    
  3. index.html, app/index.js, base.css 생성
    • index.html ```html <!DOCTYPE html>
CSS & Libraries Code Splitting

CSS Code Splitting

This text should be colored with blue after injecting CSS bundle

- base.css
```css
p {
  color : blue;
}

module.exports = { mode: “development”, // 책에는 없지만 이것을 붙이지 않으면 기본적으로 production모드임(난독화,압축등) entry: ‘./app/index.js’, output: { filename: ‘bundle.js’, path: path.resolve(__dirname, ‘dist’) }, module: { rules: [{ test: /.css$/, use: [‘style-loader’, ‘css-loader’] }] }, }

5. webpack 실행
6. ExtractTextWebpackPlugin으로 css파일 분리
```javascript
// webpack.config.js
// ...
var ExtractTextPlugin = require('extract-text-webpack-plugin');
// ...
{
  // ...
  module: {
    rules: [{
      test: /\.css$/,
      // Comment this out to load ExtractTextPlugin
      // use: ['style-loader', 'css-loader']
      use: ExtractTextPlugin.extract({
        fallback: "style-loader",
        use: "css-loader"
      })
    }]
  },
  plugins: [
    new ExtractTextPlugin('styles.css')
  ]
}
  1. –save-dev용 webpack설치
    npm i --save-dev webpack
    
    • 위와 같이 설치하면 extract-text-webpack-plugin 3.0설치되어 Webpack4부터는 오류가 발생됨
    • 따라서 아래와 같이 4.0버전을 받아야 사용가능
      npm i -save-dev extract-text-webpack-plugin@next