所有的代碼及筆記均可以在個人github上查看, 歡迎star:https://github.com/Jasonwang911/webpackStudyInit/tree/master/csscss
引入--loaderhtml
npm install style-loader css-loader --save-dev
var path = require('path') module.exports = { entry: { app: './src/app.js' }, output: { path: path.resolve(__dirname, 'dist'), filename: '[name].bundle.js' }, module: { rules: [ { test: /\.css$/, use: [ { loader: 'style-loader' }, { loader: 'css-loader' } ] } ] } }
2. style-loader配合file-loader 使用在html中插入link標籤並引入js中import的樣式,注意:publicPath爲指定打包後文件的路徑webpack
var path = require('path') module.exports = { mode: 'production', entry: { app: './src/app.js' }, output: { path: path.resolve(__dirname, 'dist'), publicPath: './dist/', filename: '[name].bundle.js' }, module: { rules: [ { test: /\.css$/, use: [ { loader: 'style-loader/url' }, { loader: 'file-loader' } ] } ] } }
var path = require('path') module.exports = { mode: 'production', entry: { app: './src/app.js' }, output: { path: path.resolve(__dirname, 'dist'), publicPath: './dist/', filename: '[name].bundle.js' }, module: { rules: [ { test: /\.css$/, use: [ { loader: 'style-loader/useable' }, { loader: 'css-loader' // loader: 'file-loader' } ] } ] } }
## style-loader 的一些經常使用配置 options git
1. insertAt: 插入位置 github
2. singleton: 是否只使用一個style標籤,會將多個引入混合爲一個style標籤插入頁面 web
{ loader: 'style-loader', options: { singleton: true } }
3. insertInto: 插入到domnpm
module.exports = function(css) { if(window.innerWidth > 400) { // css += 'html{background: aqua;}' css = css.replace('red', 'aqua') }else { css = css.replace('aqua', 'red') } console.log(css); return css; }
var path = require('path') module.exports = { mode: 'production', entry: { app: './src/app.js' }, output: { path: path.resolve(__dirname, 'dist'), // publicPath: './dist/', filename: '[name].bundle.js' }, module: { rules: [ { test: /\.css$/, use: [ { loader: 'style-loader', options: { singleton: true, transform: './src/css/transform.js', } }, { loader: 'css-loader' // loader: 'file-loader' } ] } ] } }