【typescript】配置ts-import-plugin按需加载antd导致Inline JavaScript报错解决方案(非网上常见2种)

场景复现

  • 为了按需引入,于是我引用了ts-import-plugin,当时这么配置的:
  {
    test: /\.(j|t)sx?$/,
      loader: 'ts-loader',
      exclude: /node_modules/,
      options: {
          transpileOnly: true,
          getCustomTransformers: () => ({
              before: [ tsImportPluginFactory( [{
                  libraryName:'antd',
                  libraryDirectory:'lib',
                  style:true
              }]) ]
          }),
          compilerOptions: {
              module: 'es2015'
          }
      },
  },
  • 然后打包就会报错,提示Inline JavaScript is not enabled. Is it set in your options?

解决方法

  • 网上通常有2种解决办法,一种是下低版本的less,一种是在less的配置上加上:
 options:{
    javascriptEnabled:true
 }
  • 我试了下都是可以的。但是我就产生了疑问,没用按需加载时并没有开启js,为什么用了就要开启?
  • 我去less-loader文档上看到这样一句:
Enable Inline JavaScript (Deprecated)
False by default starting in v3.0.0. Enables evaluation of JavaScript inline in .less files. This created a security problem for some developers who didn't expect user input for style sheets to have executable code.
Replaced with the @plugin option.
  • 说明这方式会引起安全问题,也不推荐打开这选项。这就让我感觉有点意思了。
  • 我看了下我其中一个组件的报错是这么写的:
// https://github.com/ant-design/ant-motion/issues/44
.bezierEasingMixin();
^
Inline JavaScript is not enabled. Is it set in your options?
      in 
      .....
  • 然后我看了一下我那个组件,就单单引入了一个图标。我就想,我这个图标就这么巧用上了贝塞尔曲线?
  • 我就想起配ts-import-plugin时,有个选项是自动引入样式,可以做为false处理。
  • 我将选项作为false之后果然没报错了,并且样式并没有不存在。图标仍好好的出现在页面上,目前我使用的其他样式也都正常。所以其实没必要打开js开关。
   options: {
     transpileOnly: true,
         getCustomTransformers: () => ({
             before: [ tsImportPluginFactory( [{
                 libraryName:'antd',
                 libraryDirectory:'lib',
                 style:false
             }]) ]
         }),
         compilerOptions: {
             module: 'es2015'
         }
     },
  • 并且,我拿项目试验了一下,打开js并且style配置为true,打包后代码4620k,如果配置false,并且关闭js,打包后代码4474k。
  • 你有可能真的不需要那200k代码。
发布了163 篇原创文章 · 获赞 9 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/yehuozhili/article/details/104437923