简体   繁体   中英

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. The important part though is that I want to transform this ES5 require into an ES6 import. 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

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

or you should add svg-url-loader to your webpack config;

 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. If not aliases may also help.

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

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

For example: A loader config in your webpack config may look like this...

 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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