简体   繁体   English

如何将es5 require转换为es6 import

[英]How to convert es5 require to es6 import

I'm using webpack and svg-url-loader to load an SVG file into my react app. 我正在使用webpacksvg-url-loader将SVG文件加载到我的react应用程序中。 The important part though is that I want to transform this ES5 require into an ES6 import. 不过,重要的部分是我想将此ES5需求转换为ES6导入。 Here is the require: 这是要求:

require('!!svg-url-loader?noquotes!../images/mustachio.svg')

and I came up with this import statement: 我想出了这个导入语句:

import mustachio from '!!svg-url-loader?noquotes!../images/mustachio.svg'

But isn't there a cleaner way to do this? 但是,没有更清洁的方法吗?

You should use default webpack require with 您应该使用默认的webpack require

 require('!!svg-url-loader?noquotes!../images/mustachio.svg') 

or you should add svg-url-loader to your webpack config; 或者您应该将svg-url-loader添加到您的webpack配置中;

 module.exports = { module: { rules: [{ test: /\\.svg/, use: { loader: 'svg-url-loader', options: {noquotes: true}} }] } } 

and now you can use 现在您可以使用

 import mustachio from './../images/mustachio.svg'; 

Webpack loader is probably what you want. Webpack loader可能就是您想要的。 If not aliases may also help. 如果没有,别名也可能会有所帮助。

https://webpack.js.org/loaders/ https://webpack.js.org/loaders/

https://webpack.js.org/configuration/resolve/ https://webpack.js.org/configuration/resolve/

For example: A loader config in your webpack config may look like this... 例如:您的webpack配置中的加载器配置可能看起来像这样...

 loaders: [ { test: /\\.css$/, loader: 'style-loader!css-loader'}, { test: /\\.less$/, loader: 'style-loader!css!less' }, { test: /\\.svg$/, loader: 'url?limit=65000&mimetype=image/svg+xml&name=css/[name].[ext]' }, { test: /\\.woff$/, loader: 'url?limit=65000&mimetype=application/font-woff&name=css/[name].[ext]' }, { test: /\\.woff2$/, loader: 'url?limit=65000&mimetype=application/font-woff2&name=css/[name].[ext]' }, { test: /\\.[ot]tf$/, loader: 'url?limit=65000&mimetype=application/octet-stream&name=css/[name].[ext]' }, { test: /\\.eot$/, loader: 'url?limit=65000&mimetype=application/vnd.ms-fontobject&name=css/[name].[ext]' }, { test: /.jsx?$/, loader: 'babel-loader', exclude: /node_modules/, query: { presets: ['es2015', 'react', 'stage-0'], plugins: ['transform-runtime', 'transform-decorators-legacy'] } } ] 

This avoids having to specify your loader on each require or import. 这样避免了在每个需求或导入上都必须指定装载程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM