有没有童鞋遇到过同样的问题:antd的babel-plugin-import插件,服务端渲染时,如果babel中配置了import会报错,删掉正常启动 大佬们有什么好的建议?

使用express服务端渲染,如果babel中配置了import会报错,删掉就可以正常启动。但是这个配置,用webpack,不管是devServer,还是编译文件,都正常。只有在尝试用express启动的时候会包错
就是在.babelrc文件中的plugins的这段代码:
[
"import",
{
"libraryName":"antd",
"libraryDirectory":"es",
"style":true
}
]
(function(exports,require,module,__filename,__dirname){import'../../style/index.less';
^^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError:Unexpectedstring
atnewScript(vm.js:79:7)
atcreateScript(vm.js:251:10)
atObject.runInThisContext(vm.js:303:10)
atModule._compile(internal/modules/cjs/loader.js:657:28)
...
我的相关配置文件:.babel
{
"presets":["@babel/preset-env","@babel/preset-react"],
"plugins":[
"@babel/plugin-proposal-object-rest-spread",
"@babel/plugin-transform-runtime",
[
"import",
{
"libraryName":"antd",
"libraryDirectory":"es",
"style":true
}
]
]
}
server.js
require('ignore-styles');
varfs=require('fs');
varbabelConfig=JSON.parse(fs.readFileSync('./.babelrc'));
require('@babel/register')(babelConfig);
require('./express.js');
express.js
importpathfrom'path';
importfsfrom'fs';
importexpressfrom'express';
importReactfrom'react';
import{renderToString}from'react-dom/server';
import{StaticRouter}from'react-router-dom';
importHomefrom'./src/component/Home';
constROOT_PATH=path.resolve(__dirname);
constBUILD_PATH=path.resolve(ROOT_PATH,'build');
constapp=express();
app.use(express.static(BUILD_PATH));
app.use('*',function(req,res){
letcontext={};
consttemplate=renderToString(
);
if(context.status===404){
res.status(404);
}
fs.readFile(path.resolve(BUILD_PATH+'/index.html'),'utf8',(err,data)=>{
if(err){
console.error(err);
returnres.status(500).send('Anerroroccurred');
}
returnres.send(
data.replace('
',`${template}
`)
)
});
});
constserver=app.listen(3000,()=>{
consthost=server.address().address;
constport=server.address().port;
console.log('serverisstartat',host,port);
});
启动node./server.js
茅侃侃
浏览 1152回答 2
2回答

噜噜哒

将less版本降到3.0以下?!这不是办法。正确的解决办法是在项目的根目录下新建文件:vue.config.js,内容如下:123456789module.exports = {  css: {    loaderOptions: {      less: {        javascriptEnabled: true      }    }  }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript