解决问题方案:
- 使用amfe-flexible
- 引入postcss,使用px-to-rem、autoprefix插件
什么是amfe-flexible
淘宝提供的解决移动端适配方案, 具体参考https://github.com/amfe/article/issues/17
注意:目前官方已经明确表明,该方案存在一些问题,建议使用vw+rem的方案,后续调研
如何使用?
直接在html中直接引用amfe-flexible.js。
在我们的项目中的配置,将amfe-flexible.js存放在根/static目录下面,在Head标签通过script标签引用
<Head> <title>Demo</title> <meta name="viewport" content="initial-scale=1.0, width=device-width" /> <script src="/static/flexible/amfe-flexible.js"></script> </Head>
什么是PostCss
概念:是一个css处理器,通过插件处理css
常用的插件: autocomplete、pxtorem、cssnext
postcss和less、sass有什么区别? 感兴趣的话,后续再延伸讨论
postcss sugarss 语法:
/* index.sss */
html,
body
border: 0;
font-family: 'Conv_ProximaNova-Regular', Sans-Serif !important;
line-height: 1.5;
margin: 0;
padding: 0;
width: 100%;
/*正常的语法 index.css*/
html,
body {
border: 0;
font-family: 'Conv_ProximaNova-Regular', Sans-Serif !important;
line-height: 1.5;
margin: 0;
padding: 0;
width: 100%;
}
如何使用postcss?
- npm install postcss-loader, postcss-pxtorem, styled-jsx-postcss, autoprefixer, sugarss
- 根目录创建postcss.config.js,主要使用的autoprefixer、postcss-pxtorem插件, sugarss parser看需要使用不使用,不使用的话可以直接parser: false
- 配置autoprefixer, 在postcss.config.js plugins中增加autoprefixer: {}, 在package.json中增加browserslist: {}
// postcss.config.js
module.exports = ({ file, options }) => {
return {
parser: file.extname === '.sss' ? 'sugarss' : false,
plugins: {
autoprefixer: {},
'postcss-pxtorem': {
replace: false,
// unitPrecision: 5,
rootValue: 16,
// mediaQuery: false,
}
}
};
};
// package.json中的browserslist配置
"browserslist": [
"last 5 versions",
"> 1%",
"not ie <= 8"
],
遇到的问题
- ts文件中import less文件报错Cannot find module './index.less'.
解决方案, 在next-env.d.ts增加以下代码
declare module '*.less' {
const content: any;
export default content;
}
- post-css配置的时候, postcss.config.js或者next.config.js的postcssLoaderOptions 二选一(没仔细看文档浪费了挺久时间)
- autoprefixer配置,不要直接在postcss.config.js中配置, 配置在package.json中