1、node版本 首先你要先看下你的node版本,如果小于10,建議升級(jí)到10及以上,因?yàn)榈桶姹镜?node 在自動(dòng)創(chuàng)建 react框架時(shí),有配置文件跟10及以上的有比較大的差異,而且需要增加、修改的配置有點(diǎn)多,有些繁復(fù),所以為了能夠輕松自在的創(chuàng)建基礎(chǔ)框架,最好是升級(jí)下node。我用的nvm,版本隨意切換,所以還算自在。 2、先跑命令 : npm install -g create-react-app 創(chuàng)建下 構(gòu)建環(huán)境。 3、create-react-app <你定義的項(xiàng)目名> ,運(yùn)行后就會(huì)自動(dòng)創(chuàng)建了。 4、完成后 你的 項(xiàng)目目錄結(jié)構(gòu)及package.json配置大概如下: 很整潔,很多配置項(xiàng)集成在了 node_moudles下的 react-scripts 中,如果你想自己加一些自己的配置,或者定制下配置。那就需要 執(zhí)行命令 : npm run eject(這詞是彈出的意思)。 5、執(zhí)行 npm run eject 時(shí),它將把所有配置文件和可傳遞的依賴項(xiàng)(Webpack、Babel、eSlint等)直接復(fù)制到您的項(xiàng)目中,配置文件會(huì)被輸出到config下的webpack.config.js,你可以對(duì)其進(jìn)行修改調(diào)整。 如果你用過vue-cli3去創(chuàng)建并配置vue項(xiàng)目的話,看到react下的 這個(gè) webpack.config.js文件應(yīng)該會(huì)覺得似曾相識(shí),除了有一些優(yōu)化配置項(xiàng)vue沒有,一部分內(nèi)容 和 vue.config.js文件 還是有諸多想通之處的, 玩起來也會(huì)得心應(yīng)手一些。 此時(shí)你的目錄結(jié)構(gòu)如下: 6、這時(shí)候引用antd開發(fā)時(shí),可能會(huì)報(bào)錯(cuò),還需要做一些配置。 const lessRegex = /\.less$/; const lessModuleRegex = /\.module\.less$/; loaders.push( { loader: require.resolve('resolve-url-loader'), options: { sourceMap: isEnvProduction && shouldUseSourceMap, }, }, { loader: require.resolve(preProcessor), options: { sourceMap: true, javascriptEnabled: preProcessor === 'less-loader' //需要加 }, } plugins: [ [ require.resolve('babel-plugin-named-asset-import'), { loaderMap: { svg: { ReactComponent: '@svgr/webpack?-svgo, titleProp, ref![path]', }, }, }, ], //下面需要加 [ "import", { libraryName: "antd", libraryDirectory: "es", style: true // `style: true` 會(huì)加載 less 文件 }, ] ], // less相關(guān)配置 ,下面都需要加 //普通模式 { test: lessRegex, exclude: lessModuleRegex, use: getStyleLoaders( { importLoaders: 2, sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment, }, 'less-loader' ), sideEffects: true, }, //module 模式 { test: lessModuleRegex, // exclude:[/node_modules/],// 針對(duì)第三方的less文件不進(jìn)行module化 use: getStyleLoaders( { importLoaders: 2, sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment, modules: true, getLocalIdent: getCSSModuleLocalIdent, }, 'less-loader' ), }, // "file" loader makes sure those assets get served by WebpackDevServer. 配的時(shí)候,看清配置所在位置哈。這樣就結(jié)束了,可以玩耍了。 |
|