先说结论
看看项目是否添加了浏览器支持的信息?
package.json添加如下信息
"browserslist": [
"defaults",
"not ie <= 8",
"last 2 versions",
"> 1%",
"iOS >= 7",
"Android >= 4.0"
]
需求
使用webpack打包index.ts的代码,涉及DOM操作,引入.scss
postcss-loader
-> scss-loader
-> css-loader
-> style-loader
基本配置如下
package.json
{
"name": "session1",
"version": "1.0.0",
"description": "",
"private": true,
"scripts": {
"bundle": "webpack"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@types/node": "^13.7.0",
"autoprefixer": "^9.7.4",
"css-loader": "^3.4.2",
"file-loader": "^5.0.2",
"node-sass": "^4.13.1",
"postcss-loader": "^3.0.0",
"sass-loader": "^8.0.2",
"style-loader": "^1.1.3",
"ts-loader": "^6.2.1",
"typescript": "^3.7.5",
"url-loader": "^3.0.0",
"webpack": "^4.41.5",
"webpack-cli": "^3.3.10"
}
}
webpack.config.js
const path = require('path');
module.exports = {
mode: 'development',
// entry: './src/index.ts', // 简写
entry: {
main: './src/index.ts',
},
module: {
rules: [{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/,
}, {
test: /\.(png|jp?g|gif)$/,
use: [{
loader: 'url-loader',
options: {
name: '[name].[ext]', // placeholder 占位符
outputPath: 'images/',
limit: 2048
}
}],
}, {
test: /\.scss$/,
use: [
'style-loader',
'css-loader',
'sass-loader',
'postcss-loader'
]
}
],
},
resolve: {
extensions: ['.tsx', '.ts', '.js'],
},
output: {
filename: 'bundle.js', // 打包后文件名
path: path.resolve(__dirname, 'dist') // 输出路径(必须为绝对路径)
}
}
postcss.config.js
module.exports = {
plugins: [
require('autoprefixer')
],
}
index.ts
import avatar from './static/avatar.jpg';
import './index.scss';
const img = new Image();
img.src = avatar;
img.classList.add('avatar')
const root = document.getElementById('root');
root!.append(img);
bug复现
执行npm run bundle # 即webpack打包 ,
postcss-loader内使用的autoprefixer失效。
解决办法
package.json添加浏览器支持配置
{
"name": "session1",
"version": "1.0.0",
"description": "",
"private": true,
"scripts": {
"bundle": "webpack"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@types/node": "^13.7.0",
"autoprefixer": "^9.7.4",
"css-loader": "^3.4.2",
"file-loader": "^5.0.2",
"node-sass": "^4.13.1",
"postcss-loader": "^3.0.0",
"sass-loader": "^8.0.2",
"style-loader": "^1.1.3",
"ts-loader": "^6.2.1",
"typescript": "^3.7.5",
"url-loader": "^3.0.0",
"webpack": "^4.41.5",
"webpack-cli": "^3.3.10"
},
"browserslist": [
"defaults",
"not ie <= 8",
"last 2 versions",
"> 1%",
"iOS >= 7",
"Android >= 4.0"
]
}